blob: 1f47718516571dfa20e543b14076bf95509d49b9 [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 Bik38a3f212017-10-20 17:02:21 -070028#include "mirror/array-inl.h"
29#include "mirror/string.h"
Aart Bik281c6812016-08-26 11:31:48 -070030
31namespace art {
32
Vladimir Markod5d2f2c2017-09-26 12:37:26 +010033// TODO: Clean up the packed type detection so that we have the right type straight away
34// and do not need to go through this normalization.
35static inline void NormalizePackedType(/* inout */ DataType::Type* type,
36 /* inout */ bool* is_unsigned) {
37 switch (*type) {
38 case DataType::Type::kBool:
39 DCHECK(!*is_unsigned);
40 break;
41 case DataType::Type::kUint8:
42 case DataType::Type::kInt8:
43 if (*is_unsigned) {
44 *is_unsigned = false;
45 *type = DataType::Type::kUint8;
46 } else {
47 *type = DataType::Type::kInt8;
48 }
49 break;
50 case DataType::Type::kUint16:
51 case DataType::Type::kInt16:
52 if (*is_unsigned) {
53 *is_unsigned = false;
54 *type = DataType::Type::kUint16;
55 } else {
56 *type = DataType::Type::kInt16;
57 }
58 break;
59 case DataType::Type::kInt32:
60 case DataType::Type::kInt64:
61 // We do not have kUint32 and kUint64 at the moment.
62 break;
63 case DataType::Type::kFloat32:
64 case DataType::Type::kFloat64:
65 DCHECK(!*is_unsigned);
66 break;
67 default:
68 LOG(FATAL) << "Unexpected type " << *type;
69 UNREACHABLE();
70 }
71}
72
Aart Bikf8f5a162017-02-06 15:35:29 -080073// Enables vectorization (SIMDization) in the loop optimizer.
74static constexpr bool kEnableVectorization = true;
75
Aart Bik521b50f2017-09-09 10:44:45 -070076// No loop unrolling factor (just one copy of the loop-body).
77static constexpr uint32_t kNoUnrollingFactor = 1;
78
Aart Bik38a3f212017-10-20 17:02:21 -070079//
80// Static helpers.
81//
82
83// Base alignment for arrays/strings guaranteed by the Android runtime.
84static uint32_t BaseAlignment() {
85 return kObjectAlignment;
86}
87
88// Hidden offset for arrays/strings guaranteed by the Android runtime.
89static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
90 return is_string_char_at
91 ? mirror::String::ValueOffset().Uint32Value()
92 : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
93}
94
Aart Bik9abf8942016-10-14 09:49:42 -070095// Remove the instruction from the graph. A bit more elaborate than the usual
96// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070097static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070098 instruction->RemoveAsUserOfAllInputs();
99 instruction->RemoveEnvironmentUsers();
100 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +0100101 RemoveEnvironmentUses(instruction);
102 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -0700103}
104
Aart Bik807868e2016-11-03 17:51:43 -0700105// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -0700106static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
107 if (block->GetPredecessors().size() == 1 &&
108 block->GetSuccessors().size() == 1 &&
109 block->IsSingleGoto()) {
110 *succ = block->GetSingleSuccessor();
111 return true;
112 }
113 return false;
114}
115
Aart Bik807868e2016-11-03 17:51:43 -0700116// Detect an early exit loop.
117static bool IsEarlyExit(HLoopInformation* loop_info) {
118 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
119 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
120 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
121 if (!loop_info->Contains(*successor)) {
122 return true;
123 }
124 }
125 }
126 return false;
127}
128
Aart Bik68ca7022017-09-26 16:44:23 -0700129// Forward declaration.
130static bool IsZeroExtensionAndGet(HInstruction* instruction,
131 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700132 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700133
Aart Bikdf011c32017-09-28 12:53:04 -0700134// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700135// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700136static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100137 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700138 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700139 // Accept any already wider constant that would be handled properly by sign
140 // extension when represented in the *width* of the given narrower data type
Aart Bik4d1a9d42017-10-19 14:40:55 -0700141 // (the fact that Uint8/Uint16 normally zero extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700142 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700143 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700144 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100145 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100146 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700147 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700148 *operand = instruction;
149 return true;
150 }
151 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100152 case DataType::Type::kUint16:
153 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700154 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700155 *operand = instruction;
156 return true;
157 }
158 return false;
159 default:
160 return false;
161 }
162 }
Aart Bikdf011c32017-09-28 12:53:04 -0700163 // An implicit widening conversion of any signed expression sign-extends.
164 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700165 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100166 case DataType::Type::kInt8:
167 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700168 *operand = instruction;
169 return true;
170 default:
171 return false;
172 }
173 }
Aart Bikdf011c32017-09-28 12:53:04 -0700174 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700175 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700176 HInstruction* conv = instruction->InputAt(0);
177 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700178 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700179 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700180 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700181 if (type == from && (from == DataType::Type::kInt8 ||
182 from == DataType::Type::kInt16 ||
183 from == DataType::Type::kInt32)) {
184 *operand = conv;
185 return true;
186 }
187 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700188 case DataType::Type::kInt16:
189 return type == DataType::Type::kUint16 &&
190 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700191 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700192 default:
193 return false;
194 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700195 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700196 return false;
197}
198
Aart Bikdf011c32017-09-28 12:53:04 -0700199// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700200// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700201static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100202 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700203 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700204 // Accept any already wider constant that would be handled properly by zero
205 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700206 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700207 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700208 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700209 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100210 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100211 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700212 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700213 *operand = instruction;
214 return true;
215 }
216 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100217 case DataType::Type::kUint16:
218 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700219 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700220 *operand = instruction;
221 return true;
222 }
223 return false;
224 default:
225 return false;
226 }
227 }
Aart Bikdf011c32017-09-28 12:53:04 -0700228 // An implicit widening conversion of any unsigned expression zero-extends.
229 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100230 switch (type) {
231 case DataType::Type::kUint8:
232 case DataType::Type::kUint16:
233 *operand = instruction;
234 return true;
235 default:
236 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700237 }
238 }
Aart Bikdf011c32017-09-28 12:53:04 -0700239 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700240 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700241 HInstruction* conv = instruction->InputAt(0);
242 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700243 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700244 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700245 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700246 if (type == from && from == DataType::Type::kUint16) {
247 *operand = conv;
248 return true;
249 }
250 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700251 case DataType::Type::kUint16:
252 return type == DataType::Type::kInt16 &&
253 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700254 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700255 default:
256 return false;
257 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700258 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700259 return false;
260}
261
Aart Bik304c8a52017-05-23 11:01:13 -0700262// Detect situations with same-extension narrower operands.
263// Returns true on success and sets is_unsigned accordingly.
264static bool IsNarrowerOperands(HInstruction* a,
265 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100266 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700267 /*out*/ HInstruction** r,
268 /*out*/ HInstruction** s,
269 /*out*/ bool* is_unsigned) {
Aart Bik4d1a9d42017-10-19 14:40:55 -0700270 // Look for a matching sign extension.
271 DataType::Type stype = HVecOperation::ToSignedType(type);
272 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700273 *is_unsigned = false;
274 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700275 }
276 // Look for a matching zero extension.
277 DataType::Type utype = HVecOperation::ToUnsignedType(type);
278 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700279 *is_unsigned = true;
280 return true;
281 }
282 return false;
283}
284
285// As above, single operand.
286static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100287 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700288 /*out*/ HInstruction** r,
289 /*out*/ bool* is_unsigned) {
Aart Bik4d1a9d42017-10-19 14:40:55 -0700290 // Look for a matching sign extension.
291 DataType::Type stype = HVecOperation::ToSignedType(type);
292 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700293 *is_unsigned = false;
294 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700295 }
296 // Look for a matching zero extension.
297 DataType::Type utype = HVecOperation::ToUnsignedType(type);
298 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700299 *is_unsigned = true;
300 return true;
301 }
302 return false;
303}
304
Aart Bikdbbac8f2017-09-01 13:06:08 -0700305// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700306static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100307 DCHECK(DataType::IsIntegralType(other_type));
308 DCHECK(DataType::IsIntegralType(vector_type));
309 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
310 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700311}
312
Aart Bik5f805002017-05-16 16:42:41 -0700313// Detect up to two instructions a and b, and an acccumulated constant c.
314static bool IsAddConstHelper(HInstruction* instruction,
315 /*out*/ HInstruction** a,
316 /*out*/ HInstruction** b,
317 /*out*/ int64_t* c,
318 int32_t depth) {
319 static constexpr int32_t kMaxDepth = 8; // don't search too deep
320 int64_t value = 0;
321 if (IsInt64AndGet(instruction, &value)) {
322 *c += value;
323 return true;
324 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
325 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
326 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
327 } else if (*a == nullptr) {
328 *a = instruction;
329 return true;
330 } else if (*b == nullptr) {
331 *b = instruction;
332 return true;
333 }
334 return false; // too many non-const operands
335}
336
337// Detect a + b + c for an optional constant c.
338static bool IsAddConst(HInstruction* instruction,
339 /*out*/ HInstruction** a,
340 /*out*/ HInstruction** b,
341 /*out*/ int64_t* c) {
342 if (instruction->IsAdd()) {
343 // Try to find a + b and accumulated c.
344 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
345 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
346 *b != nullptr) {
347 return true;
348 }
349 // Found a + b.
350 *a = instruction->InputAt(0);
351 *b = instruction->InputAt(1);
352 *c = 0;
353 return true;
354 }
355 return false;
356}
357
Aart Bikdf011c32017-09-28 12:53:04 -0700358// Detect a + c for constant c.
359static bool IsAddConst(HInstruction* instruction,
360 /*out*/ HInstruction** a,
361 /*out*/ int64_t* c) {
362 if (instruction->IsAdd()) {
363 if (IsInt64AndGet(instruction->InputAt(0), c)) {
364 *a = instruction->InputAt(1);
365 return true;
366 } else if (IsInt64AndGet(instruction->InputAt(1), c)) {
367 *a = instruction->InputAt(0);
368 return true;
369 }
370 }
371 return false;
372}
373
Aart Bikb29f6842017-07-28 15:58:41 -0700374// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700375// x = x_phi + ..
376// x = x_phi - ..
377// x = max(x_phi, ..)
378// x = min(x_phi, ..)
379static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
380 if (reduction->IsAdd()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700381 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
382 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700383 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700384 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700385 } else if (reduction->IsInvokeStaticOrDirect()) {
386 switch (reduction->AsInvokeStaticOrDirect()->GetIntrinsic()) {
387 case Intrinsics::kMathMinIntInt:
388 case Intrinsics::kMathMinLongLong:
389 case Intrinsics::kMathMinFloatFloat:
390 case Intrinsics::kMathMinDoubleDouble:
391 case Intrinsics::kMathMaxIntInt:
392 case Intrinsics::kMathMaxLongLong:
393 case Intrinsics::kMathMaxFloatFloat:
394 case Intrinsics::kMathMaxDoubleDouble:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700395 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
396 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700397 default:
398 return false;
399 }
400 }
401 return false;
402}
403
Aart Bikdbbac8f2017-09-01 13:06:08 -0700404// Translates vector operation to reduction kind.
405static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
406 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700407 return HVecReduce::kSum;
408 } else if (reduction->IsVecMin()) {
409 return HVecReduce::kMin;
410 } else if (reduction->IsVecMax()) {
411 return HVecReduce::kMax;
412 }
Aart Bik38a3f212017-10-20 17:02:21 -0700413 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700414 UNREACHABLE();
415}
416
Aart Bikf8f5a162017-02-06 15:35:29 -0800417// Test vector restrictions.
418static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
419 return (restrictions & tested) != 0;
420}
421
Aart Bikf3e61ee2017-04-12 17:09:20 -0700422// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800423static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
424 DCHECK(block != nullptr);
425 DCHECK(instruction != nullptr);
426 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
427 return instruction;
428}
429
Artem Serov21c7e6f2017-07-27 16:04:42 +0100430// Check that instructions from the induction sets are fully removed: have no uses
431// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100432static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100433 for (HInstruction* instr : *iset) {
434 if (instr->GetBlock() != nullptr ||
435 !instr->GetUses().empty() ||
436 !instr->GetEnvUses().empty() ||
437 HasEnvironmentUsedByOthers(instr)) {
438 return false;
439 }
440 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100441 return true;
442}
443
Aart Bik281c6812016-08-26 11:31:48 -0700444//
Aart Bikb29f6842017-07-28 15:58:41 -0700445// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700446//
447
448HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800449 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700450 HInductionVarAnalysis* induction_analysis,
451 OptimizingCompilerStats* stats)
452 : HOptimization(graph, kLoopOptimizationPassName, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800453 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700454 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700455 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100456 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700457 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700458 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700459 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700460 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800461 simplified_(false),
462 vector_length_(0),
463 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700464 vector_static_peeling_factor_(0),
465 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700466 vector_runtime_test_a_(nullptr),
467 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700468 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100469 vector_permanent_map_(nullptr),
470 vector_mode_(kSequential),
471 vector_preheader_(nullptr),
472 vector_header_(nullptr),
473 vector_body_(nullptr),
474 vector_index_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700475}
476
477void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800478 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700479 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800480 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700481 return;
482 }
483
Vladimir Markoca6fff82017-10-03 14:49:14 +0100484 // Phase-local allocator.
485 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700486 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100487
Aart Bik96202302016-10-04 17:33:56 -0700488 // Perform loop optimizations.
489 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800490 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800491 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800492 }
493
Aart Bik96202302016-10-04 17:33:56 -0700494 // Detach.
495 loop_allocator_ = nullptr;
496 last_loop_ = top_loop_ = nullptr;
497}
498
Aart Bikb29f6842017-07-28 15:58:41 -0700499//
500// Loop setup and traversal.
501//
502
Aart Bik96202302016-10-04 17:33:56 -0700503void HLoopOptimization::LocalRun() {
504 // Build the linear order using the phase-local allocator. This step enables building
505 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100506 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
507 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700508
Aart Bik281c6812016-08-26 11:31:48 -0700509 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700510 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700511 if (block->IsLoopHeader()) {
512 AddLoop(block->GetLoopInformation());
513 }
514 }
Aart Bik96202302016-10-04 17:33:56 -0700515
Aart Bik8c4a8542016-10-06 11:36:57 -0700516 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800517 // temporary data structures using the phase-local allocator. All new HIR
518 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700519 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100520 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
521 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700522 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100523 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
524 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800525 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100526 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700527 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800528 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700529 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700530 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800531 vector_refs_ = &refs;
532 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700533 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800534 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700535 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800536 // Detach.
537 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700538 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800539 vector_refs_ = nullptr;
540 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700541 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700542 }
Aart Bik281c6812016-08-26 11:31:48 -0700543}
544
545void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
546 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800547 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700548 if (last_loop_ == nullptr) {
549 // First loop.
550 DCHECK(top_loop_ == nullptr);
551 last_loop_ = top_loop_ = node;
552 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
553 // Inner loop.
554 node->outer = last_loop_;
555 DCHECK(last_loop_->inner == nullptr);
556 last_loop_ = last_loop_->inner = node;
557 } else {
558 // Subsequent loop.
559 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
560 last_loop_ = last_loop_->outer;
561 }
562 node->outer = last_loop_->outer;
563 node->previous = last_loop_;
564 DCHECK(last_loop_->next == nullptr);
565 last_loop_ = last_loop_->next = node;
566 }
567}
568
569void HLoopOptimization::RemoveLoop(LoopNode* node) {
570 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700571 DCHECK(node->inner == nullptr);
572 if (node->previous != nullptr) {
573 // Within sequence.
574 node->previous->next = node->next;
575 if (node->next != nullptr) {
576 node->next->previous = node->previous;
577 }
578 } else {
579 // First of sequence.
580 if (node->outer != nullptr) {
581 node->outer->inner = node->next;
582 } else {
583 top_loop_ = node->next;
584 }
585 if (node->next != nullptr) {
586 node->next->outer = node->outer;
587 node->next->previous = nullptr;
588 }
589 }
Aart Bik281c6812016-08-26 11:31:48 -0700590}
591
Aart Bikb29f6842017-07-28 15:58:41 -0700592bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
593 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700594 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700595 // Visit inner loops first. Recompute induction information for this
596 // loop if the induction of any inner loop has changed.
597 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700598 induction_range_.ReVisit(node->loop_info);
599 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800600 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800601 // Note that since each simplification consists of eliminating code (without
602 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800603 do {
604 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800605 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800606 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700607 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800608 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800609 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700610 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700611 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700612 }
Aart Bik281c6812016-08-26 11:31:48 -0700613 }
Aart Bikb29f6842017-07-28 15:58:41 -0700614 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700615}
616
Aart Bikf8f5a162017-02-06 15:35:29 -0800617//
618// Optimization.
619//
620
Aart Bik281c6812016-08-26 11:31:48 -0700621void HLoopOptimization::SimplifyInduction(LoopNode* node) {
622 HBasicBlock* header = node->loop_info->GetHeader();
623 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700624 // Scan the phis in the header to find opportunities to simplify an induction
625 // cycle that is only used outside the loop. Replace these uses, if any, with
626 // the last value and remove the induction cycle.
627 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
628 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700629 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
630 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800631 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
632 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700633 // Note that it's ok to have replaced uses after the loop with the last value, without
634 // being able to remove the cycle. Environment uses (which are the reason we may not be
635 // able to remove the cycle) within the loop will still hold the right value. We must
636 // have tried first, however, to replace outside uses.
637 if (CanRemoveCycle()) {
638 simplified_ = true;
639 for (HInstruction* i : *iset_) {
640 RemoveFromCycle(i);
641 }
642 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700643 }
Aart Bik482095d2016-10-10 15:39:10 -0700644 }
645 }
646}
647
648void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800649 // Iterate over all basic blocks in the loop-body.
650 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
651 HBasicBlock* block = it.Current();
652 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800653 RemoveDeadInstructions(block->GetPhis());
654 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800655 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800656 if (block->GetPredecessors().size() == 1 &&
657 block->GetSuccessors().size() == 1 &&
658 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800659 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800660 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800661 } else if (block->GetSuccessors().size() == 2) {
662 // Trivial if block can be bypassed to either branch.
663 HBasicBlock* succ0 = block->GetSuccessors()[0];
664 HBasicBlock* succ1 = block->GetSuccessors()[1];
665 HBasicBlock* meet0 = nullptr;
666 HBasicBlock* meet1 = nullptr;
667 if (succ0 != succ1 &&
668 IsGotoBlock(succ0, &meet0) &&
669 IsGotoBlock(succ1, &meet1) &&
670 meet0 == meet1 && // meets again
671 meet0 != block && // no self-loop
672 meet0->GetPhis().IsEmpty()) { // not used for merging
673 simplified_ = true;
674 succ0->DisconnectAndDelete();
675 if (block->Dominates(meet0)) {
676 block->RemoveDominatedBlock(meet0);
677 succ1->AddDominatedBlock(meet0);
678 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700679 }
Aart Bik482095d2016-10-10 15:39:10 -0700680 }
Aart Bik281c6812016-08-26 11:31:48 -0700681 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800682 }
Aart Bik281c6812016-08-26 11:31:48 -0700683}
684
Aart Bikb29f6842017-07-28 15:58:41 -0700685bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700686 HBasicBlock* header = node->loop_info->GetHeader();
687 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700688 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800689 int64_t trip_count = 0;
690 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700691 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700692 }
Aart Bik281c6812016-08-26 11:31:48 -0700693 // Ensure there is only a single loop-body (besides the header).
694 HBasicBlock* body = nullptr;
695 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
696 if (it.Current() != header) {
697 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700698 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700699 }
700 body = it.Current();
701 }
702 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700703 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700704 // Ensure there is only a single exit point.
705 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700706 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700707 }
708 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
709 ? header->GetSuccessors()[1]
710 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700711 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700712 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700713 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700714 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800715 // Detect either an empty loop (no side effects other than plain iteration) or
716 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
717 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700718 HPhi* main_phi = nullptr;
719 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800720 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700721 if (reductions_->empty() && // TODO: possible with some effort
722 (is_empty || trip_count == 1) &&
723 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800724 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800725 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700726 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800727 preheader->MergeInstructionsWith(body);
728 }
729 body->DisconnectAndDelete();
730 exit->RemovePredecessor(header);
731 header->RemoveSuccessor(exit);
732 header->RemoveDominatedBlock(exit);
733 header->DisconnectAndDelete();
734 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800735 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800736 preheader->AddDominatedBlock(exit);
737 exit->SetDominator(preheader);
738 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700739 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800740 }
741 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800742 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700743 if (kEnableVectorization &&
744 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700745 ShouldVectorize(node, body, trip_count) &&
746 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
747 Vectorize(node, body, exit, trip_count);
748 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700749 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700750 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800751 }
Aart Bikb29f6842017-07-28 15:58:41 -0700752 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800753}
754
755//
756// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
757// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
758// Intel Press, June, 2004 (http://www.aartbik.com/).
759//
760
Aart Bik14a68b42017-06-08 14:06:58 -0700761bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800762 // Reset vector bookkeeping.
763 vector_length_ = 0;
764 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700765 vector_static_peeling_factor_ = 0;
766 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800767 vector_runtime_test_a_ =
768 vector_runtime_test_b_= nullptr;
769
770 // Phis in the loop-body prevent vectorization.
771 if (!block->GetPhis().IsEmpty()) {
772 return false;
773 }
774
775 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
776 // occurrence, which allows passing down attributes down the use tree.
777 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
778 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
779 return false; // failure to vectorize a left-hand-side
780 }
781 }
782
Aart Bik38a3f212017-10-20 17:02:21 -0700783 // Prepare alignment analysis:
784 // (1) find desired alignment (SIMD vector size in bytes).
785 // (2) initialize static loop peeling votes (peeling factor that will
786 // make one particular reference aligned), never to exceed (1).
787 // (3) variable to record how many references share same alignment.
788 // (4) variable to record suitable candidate for dynamic loop peeling.
789 uint32_t desired_alignment = GetVectorSizeInBytes();
790 DCHECK_LE(desired_alignment, 16u);
791 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
792 uint32_t max_num_same_alignment = 0;
793 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800794
795 // Data dependence analysis. Find each pair of references with same type, where
796 // at least one is a write. Each such pair denotes a possible data dependence.
797 // This analysis exploits the property that differently typed arrays cannot be
798 // aliased, as well as the property that references either point to the same
799 // array or to two completely disjoint arrays, i.e., no partial aliasing.
800 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700801 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800802 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700803 uint32_t num_same_alignment = 0;
804 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800805 for (auto j = i; ++j != vector_refs_->end(); ) {
806 if (i->type == j->type && (i->lhs || j->lhs)) {
807 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
808 HInstruction* a = i->base;
809 HInstruction* b = j->base;
810 HInstruction* x = i->offset;
811 HInstruction* y = j->offset;
812 if (a == b) {
813 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
814 // Conservatively assume a loop-carried data dependence otherwise, and reject.
815 if (x != y) {
816 return false;
817 }
Aart Bik38a3f212017-10-20 17:02:21 -0700818 // Count the number of references that have the same alignment (since
819 // base and offset are the same) and where at least one is a write, so
820 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
821 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800822 } else {
823 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
824 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
825 // generating an explicit a != b disambiguation runtime test on the two references.
826 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700827 // To avoid excessive overhead, we only accept one a != b test.
828 if (vector_runtime_test_a_ == nullptr) {
829 // First test found.
830 vector_runtime_test_a_ = a;
831 vector_runtime_test_b_ = b;
832 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
833 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
834 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800835 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800836 }
837 }
838 }
839 }
Aart Bik38a3f212017-10-20 17:02:21 -0700840 // Update information for finding suitable alignment strategy:
841 // (1) update votes for static loop peeling,
842 // (2) update suitable candidate for dynamic loop peeling.
843 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
844 if (alignment.Base() >= desired_alignment) {
845 // If the array/string object has a known, sufficient alignment, use the
846 // initial offset to compute the static loop peeling vote (this always
847 // works, since elements have natural alignment).
848 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
849 uint32_t vote = (offset == 0)
850 ? 0
851 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
852 DCHECK_LT(vote, 16u);
853 ++peeling_votes[vote];
854 } else if (BaseAlignment() >= desired_alignment &&
855 num_same_alignment > max_num_same_alignment) {
856 // Otherwise, if the array/string object has a known, sufficient alignment
857 // for just the base but with an unknown offset, record the candidate with
858 // the most occurrences for dynamic loop peeling (again, the peeling always
859 // works, since elements have natural alignment).
860 max_num_same_alignment = num_same_alignment;
861 peeling_candidate = &(*i);
862 }
863 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -0800864
Aart Bik38a3f212017-10-20 17:02:21 -0700865 // Find a suitable alignment strategy.
866 SetAlignmentStrategy(peeling_votes, peeling_candidate);
867
868 // Does vectorization seem profitable?
869 if (!IsVectorizationProfitable(trip_count)) {
870 return false;
871 }
Aart Bik14a68b42017-06-08 14:06:58 -0700872
Aart Bikf8f5a162017-02-06 15:35:29 -0800873 // Success!
874 return true;
875}
876
877void HLoopOptimization::Vectorize(LoopNode* node,
878 HBasicBlock* block,
879 HBasicBlock* exit,
880 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800881 HBasicBlock* header = node->loop_info->GetHeader();
882 HBasicBlock* preheader = node->loop_info->GetPreHeader();
883
Aart Bik14a68b42017-06-08 14:06:58 -0700884 // Pick a loop unrolling factor for the vector loop.
885 uint32_t unroll = GetUnrollingFactor(block, trip_count);
886 uint32_t chunk = vector_length_ * unroll;
887
Aart Bik38a3f212017-10-20 17:02:21 -0700888 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
889
Aart Bik14a68b42017-06-08 14:06:58 -0700890 // A cleanup loop is needed, at least, for any unknown trip count or
891 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -0700892 bool needs_cleanup = trip_count == 0 ||
893 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800894
895 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700896 HPhi* main_phi = nullptr;
897 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800898 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700899 vector_header_ = header;
900 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800901
Aart Bikdbbac8f2017-09-01 13:06:08 -0700902 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100903 DataType::Type induc_type = main_phi->GetType();
904 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
905 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700906
Aart Bik38a3f212017-10-20 17:02:21 -0700907 // Generate the trip count for static or dynamic loop peeling, if needed:
908 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -0700909 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -0700910 if (vector_static_peeling_factor_ != 0) {
911 // Static loop peeling for SIMD alignment (using the most suitable
912 // fixed peeling factor found during prior alignment analysis).
913 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
914 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
915 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
916 // Dynamic loop peeling for SIMD alignment (using the most suitable
917 // candidate found during prior alignment analysis):
918 // rem = offset % ALIGN; // adjusted as #elements
919 // ptc = rem == 0 ? 0 : (ALIGN - rem);
920 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
921 uint32_t align = GetVectorSizeInBytes() >> shift;
922 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
923 vector_dynamic_peeling_candidate_->is_string_char_at);
924 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
925 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
926 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
927 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
928 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
929 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
930 induc_type, graph_->GetConstant(induc_type, align), rem));
931 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
932 rem, graph_->GetConstant(induc_type, 0)));
933 ptc = Insert(preheader, new (global_allocator_) HSelect(
934 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
935 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -0700936 }
937
938 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800939 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -0700940 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -0700941 // vtc = stc - (stc - ptc) % chunk;
942 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800943 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
944 HInstruction* vtc = stc;
945 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700946 DCHECK(IsPowerOfTwo(chunk));
947 HInstruction* diff = stc;
948 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -0700949 if (trip_count == 0) {
950 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
951 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
952 }
Aart Bik14a68b42017-06-08 14:06:58 -0700953 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
954 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800955 HInstruction* rem = Insert(
956 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700957 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700958 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800959 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
960 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700961 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800962
963 // Generate runtime disambiguation test:
964 // vtc = a != b ? vtc : 0;
965 if (vector_runtime_test_a_ != nullptr) {
966 HInstruction* rt = Insert(
967 preheader,
968 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
969 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700970 new (global_allocator_)
971 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -0800972 needs_cleanup = true;
973 }
974
Aart Bik38a3f212017-10-20 17:02:21 -0700975 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -0700976 // for ( ; i < ptc; i += 1)
977 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -0700978 //
979 // NOTE: The alignment forced by the peeling loop is preserved even if data is
980 // moved around during suspend checks, since all analysis was based on
981 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -0700982 if (ptc != nullptr) {
983 vector_mode_ = kSequential;
984 GenerateNewLoop(node,
985 block,
986 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
987 vector_index_,
988 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700989 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700990 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -0700991 }
992
993 // Generate vector loop, possibly further unrolled:
994 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800995 // <vectorized-loop-body>
996 vector_mode_ = kVector;
997 GenerateNewLoop(node,
998 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700999 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1000 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001001 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001002 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001003 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001004 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1005
1006 // Generate cleanup loop, if needed:
1007 // for ( ; i < stc; i += 1)
1008 // <loop-body>
1009 if (needs_cleanup) {
1010 vector_mode_ = kSequential;
1011 GenerateNewLoop(node,
1012 block,
1013 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001014 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001015 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001016 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001017 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001018 }
1019
Aart Bik0148de42017-09-05 09:25:01 -07001020 // Link reductions to their final uses.
1021 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1022 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001023 HInstruction* phi = i->first;
1024 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1025 // Deal with regular uses.
1026 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1027 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1028 }
1029 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001030 }
1031 }
1032
Aart Bikf8f5a162017-02-06 15:35:29 -08001033 // Remove the original loop by disconnecting the body block
1034 // and removing all instructions from the header.
1035 block->DisconnectAndDelete();
1036 while (!header->GetFirstInstruction()->IsGoto()) {
1037 header->RemoveInstruction(header->GetFirstInstruction());
1038 }
Aart Bikb29f6842017-07-28 15:58:41 -07001039
Aart Bik14a68b42017-06-08 14:06:58 -07001040 // Update loop hierarchy: the old header now resides in the same outer loop
1041 // as the old preheader. Note that we don't bother putting sequential
1042 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001043 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1044 node->loop_info = vloop;
1045}
1046
1047void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1048 HBasicBlock* block,
1049 HBasicBlock* new_preheader,
1050 HInstruction* lo,
1051 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001052 HInstruction* step,
1053 uint32_t unroll) {
1054 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001055 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001056 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001057 vector_preheader_ = new_preheader,
1058 vector_header_ = vector_preheader_->GetSingleSuccessor();
1059 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001060 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1061 kNoRegNumber,
1062 0,
1063 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001064 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001065 // for (i = lo; i < hi; i += step)
1066 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001067 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1068 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001069 vector_header_->AddInstruction(cond);
1070 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001071 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001072 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001073 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001074 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001075 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001076 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1077 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1078 DCHECK(vectorized_def);
1079 }
1080 // Generate body from the instruction map, but in original program order.
1081 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1082 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1083 auto i = vector_map_->find(it.Current());
1084 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1085 Insert(vector_body_, i->second);
1086 // Deal with instructions that need an environment, such as the scalar intrinsics.
1087 if (i->second->NeedsEnvironment()) {
1088 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1089 }
1090 }
1091 }
Aart Bik0148de42017-09-05 09:25:01 -07001092 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001093 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1094 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001095 }
Aart Bik0148de42017-09-05 09:25:01 -07001096 // Finalize phi inputs for the reductions (if any).
1097 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1098 if (!i->first->IsPhi()) {
1099 DCHECK(i->second->IsPhi());
1100 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1101 }
1102 }
Aart Bikb29f6842017-07-28 15:58:41 -07001103 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001104 phi->AddInput(lo);
1105 phi->AddInput(vector_index_);
1106 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001107}
1108
Aart Bikf8f5a162017-02-06 15:35:29 -08001109bool HLoopOptimization::VectorizeDef(LoopNode* node,
1110 HInstruction* instruction,
1111 bool generate_code) {
1112 // Accept a left-hand-side array base[index] for
1113 // (1) supported vector type,
1114 // (2) loop-invariant base,
1115 // (3) unit stride index,
1116 // (4) vectorizable right-hand-side value.
1117 uint64_t restrictions = kNone;
1118 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001119 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001120 HInstruction* base = instruction->InputAt(0);
1121 HInstruction* index = instruction->InputAt(1);
1122 HInstruction* value = instruction->InputAt(2);
1123 HInstruction* offset = nullptr;
1124 if (TrySetVectorType(type, &restrictions) &&
1125 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001126 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001127 VectorizeUse(node, value, generate_code, type, restrictions)) {
1128 if (generate_code) {
1129 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001130 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001131 } else {
1132 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1133 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001134 return true;
1135 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001136 return false;
1137 }
Aart Bik0148de42017-09-05 09:25:01 -07001138 // Accept a left-hand-side reduction for
1139 // (1) supported vector type,
1140 // (2) vectorizable right-hand-side value.
1141 auto redit = reductions_->find(instruction);
1142 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001143 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001144 // Recognize SAD idiom or direct reduction.
1145 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1146 (TrySetVectorType(type, &restrictions) &&
1147 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001148 if (generate_code) {
1149 HInstruction* new_red = vector_map_->Get(instruction);
1150 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1151 vector_permanent_map_->Overwrite(redit->second, new_red);
1152 }
1153 return true;
1154 }
1155 return false;
1156 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001157 // Branch back okay.
1158 if (instruction->IsGoto()) {
1159 return true;
1160 }
1161 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1162 // Note that actual uses are inspected during right-hand-side tree traversal.
1163 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1164}
1165
Aart Bik304c8a52017-05-23 11:01:13 -07001166// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -08001167bool HLoopOptimization::VectorizeUse(LoopNode* node,
1168 HInstruction* instruction,
1169 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001170 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001171 uint64_t restrictions) {
1172 // Accept anything for which code has already been generated.
1173 if (generate_code) {
1174 if (vector_map_->find(instruction) != vector_map_->end()) {
1175 return true;
1176 }
1177 }
1178 // Continue the right-hand-side tree traversal, passing in proper
1179 // types and vector restrictions along the way. During code generation,
1180 // all new nodes are drawn from the global allocator.
1181 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1182 // Accept invariant use, using scalar expansion.
1183 if (generate_code) {
1184 GenerateVecInv(instruction, type);
1185 }
1186 return true;
1187 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001188 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001189 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1190 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001191 return false;
1192 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001193 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001194 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001195 // (2) loop-invariant base,
1196 // (3) unit stride index,
1197 // (4) vectorizable right-hand-side value.
1198 HInstruction* base = instruction->InputAt(0);
1199 HInstruction* index = instruction->InputAt(1);
1200 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001201 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001202 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001203 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001204 if (generate_code) {
1205 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001206 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001207 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001208 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001209 }
1210 return true;
1211 }
Aart Bik0148de42017-09-05 09:25:01 -07001212 } else if (instruction->IsPhi()) {
1213 // Accept particular phi operations.
1214 if (reductions_->find(instruction) != reductions_->end()) {
1215 // Deal with vector restrictions.
1216 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1217 return false;
1218 }
1219 // Accept a reduction.
1220 if (generate_code) {
1221 GenerateVecReductionPhi(instruction->AsPhi());
1222 }
1223 return true;
1224 }
1225 // TODO: accept right-hand-side induction?
1226 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001227 } else if (instruction->IsTypeConversion()) {
1228 // Accept particular type conversions.
1229 HTypeConversion* conversion = instruction->AsTypeConversion();
1230 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001231 DataType::Type from = conversion->GetInputType();
1232 DataType::Type to = conversion->GetResultType();
1233 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001234 uint32_t size_vec = DataType::Size(type);
1235 uint32_t size_from = DataType::Size(from);
1236 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001237 // Accept an integral conversion
1238 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1239 // (1b) widening from at least vector type, and
1240 // (2) vectorizable operand.
1241 if ((size_to < size_from &&
1242 size_to == size_vec &&
1243 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1244 (size_to >= size_from &&
1245 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001246 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001247 if (generate_code) {
1248 if (vector_mode_ == kVector) {
1249 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1250 } else {
1251 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1252 }
1253 }
1254 return true;
1255 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001256 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001257 DCHECK_EQ(to, type);
1258 // Accept int to float conversion for
1259 // (1) supported int,
1260 // (2) vectorizable operand.
1261 if (TrySetVectorType(from, &restrictions) &&
1262 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1263 if (generate_code) {
1264 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1265 }
1266 return true;
1267 }
1268 }
1269 return false;
1270 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1271 // Accept unary operator for vectorizable operand.
1272 HInstruction* opa = instruction->InputAt(0);
1273 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1274 if (generate_code) {
1275 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1276 }
1277 return true;
1278 }
1279 } else if (instruction->IsAdd() || instruction->IsSub() ||
1280 instruction->IsMul() || instruction->IsDiv() ||
1281 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1282 // Deal with vector restrictions.
1283 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1284 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1285 return false;
1286 }
1287 // Accept binary operator for vectorizable operands.
1288 HInstruction* opa = instruction->InputAt(0);
1289 HInstruction* opb = instruction->InputAt(1);
1290 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1291 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1292 if (generate_code) {
1293 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1294 }
1295 return true;
1296 }
1297 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001298 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001299 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1300 return true;
1301 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001302 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001303 HInstruction* opa = instruction->InputAt(0);
1304 HInstruction* opb = instruction->InputAt(1);
1305 HInstruction* r = opa;
1306 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001307 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1308 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1309 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001310 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1311 // Shifts right need extra care to account for higher order bits.
1312 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1313 if (instruction->IsShr() &&
1314 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1315 return false; // reject, unless all operands are sign-extension narrower
1316 } else if (instruction->IsUShr() &&
1317 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1318 return false; // reject, unless all operands are zero-extension narrower
1319 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001320 }
1321 // Accept shift operator for vectorizable/invariant operands.
1322 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001323 DCHECK(r != nullptr);
1324 if (generate_code && vector_mode_ != kVector) { // de-idiom
1325 r = opa;
1326 }
Aart Bik50e20d52017-05-05 14:07:29 -07001327 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001328 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001329 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001330 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001331 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001332 if (0 <= distance && distance < max_distance) {
1333 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001334 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001335 }
1336 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001337 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001338 }
1339 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001340 // Accept particular intrinsics.
1341 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1342 switch (invoke->GetIntrinsic()) {
1343 case Intrinsics::kMathAbsInt:
1344 case Intrinsics::kMathAbsLong:
1345 case Intrinsics::kMathAbsFloat:
1346 case Intrinsics::kMathAbsDouble: {
1347 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001348 HInstruction* opa = instruction->InputAt(0);
1349 HInstruction* r = opa;
1350 bool is_unsigned = false;
1351 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001352 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001353 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1354 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1355 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001356 }
1357 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001358 DCHECK(r != nullptr);
1359 if (generate_code && vector_mode_ != kVector) { // de-idiom
1360 r = opa;
1361 }
1362 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001363 if (generate_code) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001364 NormalizePackedType(&type, &is_unsigned);
Aart Bik304c8a52017-05-23 11:01:13 -07001365 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001366 }
1367 return true;
1368 }
1369 return false;
1370 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001371 case Intrinsics::kMathMinIntInt:
1372 case Intrinsics::kMathMinLongLong:
1373 case Intrinsics::kMathMinFloatFloat:
1374 case Intrinsics::kMathMinDoubleDouble:
1375 case Intrinsics::kMathMaxIntInt:
1376 case Intrinsics::kMathMaxLongLong:
1377 case Intrinsics::kMathMaxFloatFloat:
1378 case Intrinsics::kMathMaxDoubleDouble: {
1379 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001380 HInstruction* opa = instruction->InputAt(0);
1381 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001382 HInstruction* r = opa;
1383 HInstruction* s = opb;
1384 bool is_unsigned = false;
1385 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1386 return false;
1387 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1388 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1389 return false; // reject, unless all operands are same-extension narrower
1390 }
1391 // Accept MIN/MAX(x, y) for vectorizable operands.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001392 DCHECK(r != nullptr);
1393 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001394 if (generate_code && vector_mode_ != kVector) { // de-idiom
1395 r = opa;
1396 s = opb;
1397 }
1398 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1399 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001400 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001401 GenerateVecOp(
1402 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001403 }
1404 return true;
1405 }
1406 return false;
1407 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001408 default:
1409 return false;
1410 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001411 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001412 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001413}
1414
Aart Bik38a3f212017-10-20 17:02:21 -07001415uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1416 switch (compiler_driver_->GetInstructionSet()) {
1417 case kArm:
1418 case kThumb2:
1419 return 8; // 64-bit SIMD
1420 default:
1421 return 16; // 128-bit SIMD
1422 }
1423}
1424
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001425bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001426 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1427 switch (compiler_driver_->GetInstructionSet()) {
1428 case kArm:
1429 case kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001430 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001431 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001432 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001433 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001434 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001435 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001436 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001437 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001438 case DataType::Type::kUint16:
1439 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001440 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001441 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001442 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001443 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001444 return TrySetVectorLength(2);
1445 default:
1446 break;
1447 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001448 return false;
1449 case kArm64:
1450 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001451 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001452 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001453 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001454 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001455 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001456 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001457 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001458 case DataType::Type::kUint16:
1459 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001460 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001461 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001462 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001463 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001464 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001465 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001466 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001467 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001468 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001469 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001470 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001471 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001472 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001473 return TrySetVectorLength(2);
1474 default:
1475 return false;
1476 }
1477 case kX86:
1478 case kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001479 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001480 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1481 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001482 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001483 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001484 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001485 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001486 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001487 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001488 case DataType::Type::kUint16:
1489 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001490 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001491 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001492 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001493 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001494 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001495 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001496 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001497 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001498 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001499 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001500 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001501 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001502 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001503 return TrySetVectorLength(2);
1504 default:
1505 break;
1506 } // switch type
1507 }
1508 return false;
1509 case kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001510 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1511 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001512 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001513 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001514 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001515 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001516 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001517 case DataType::Type::kUint16:
1518 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001519 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001520 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001521 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001522 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001523 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001524 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001525 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Lena Djokic51765b02017-06-22 13:49:59 +02001526 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001527 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001528 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001529 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001530 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001531 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001532 return TrySetVectorLength(2);
1533 default:
1534 break;
1535 } // switch type
1536 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001537 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001538 case kMips64:
1539 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1540 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001541 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001542 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001543 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001544 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001545 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001546 case DataType::Type::kUint16:
1547 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001548 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001549 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001550 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001551 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001552 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001553 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001554 *restrictions |= kNoDiv | kNoReduction | kNoSAD;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001555 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001556 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001557 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001558 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001559 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001560 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001561 return TrySetVectorLength(2);
1562 default:
1563 break;
1564 } // switch type
1565 }
1566 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001567 default:
1568 return false;
1569 } // switch instruction set
1570}
1571
1572bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1573 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1574 // First time set?
1575 if (vector_length_ == 0) {
1576 vector_length_ = length;
1577 }
1578 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1579 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1580 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1581 return vector_length_ == length;
1582}
1583
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001584void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001585 if (vector_map_->find(org) == vector_map_->end()) {
1586 // In scalar code, just use a self pass-through for scalar invariants
1587 // (viz. expression remains itself).
1588 if (vector_mode_ == kSequential) {
1589 vector_map_->Put(org, org);
1590 return;
1591 }
1592 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001593 HInstruction* vector = nullptr;
1594 auto it = vector_permanent_map_->find(org);
1595 if (it != vector_permanent_map_->end()) {
1596 vector = it->second; // reuse during unrolling
1597 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001598 // Generates ReplicateScalar( (optional_type_conv) org ).
1599 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001600 DataType::Type input_type = input->GetType();
1601 if (type != input_type && (type == DataType::Type::kInt64 ||
1602 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001603 input = Insert(vector_preheader_,
1604 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1605 }
1606 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001607 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001608 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1609 }
1610 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001611 }
1612}
1613
1614void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1615 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001616 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001617 int64_t value = 0;
1618 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001619 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001620 if (org->IsPhi()) {
1621 Insert(vector_body_, subscript); // lacks layout placeholder
1622 }
1623 }
1624 vector_map_->Put(org, subscript);
1625 }
1626}
1627
1628void HLoopOptimization::GenerateVecMem(HInstruction* org,
1629 HInstruction* opa,
1630 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001631 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001632 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001633 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001634 HInstruction* vector = nullptr;
1635 if (vector_mode_ == kVector) {
1636 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001637 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001638 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001639 if (opb != nullptr) {
1640 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001641 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001642 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001643 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001644 vector = new (global_allocator_) HVecLoad(global_allocator_,
1645 base,
1646 opa,
1647 type,
1648 org->GetSideEffects(),
1649 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001650 is_string_char_at,
1651 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001652 }
Aart Bik38a3f212017-10-20 17:02:21 -07001653 // Known (forced/adjusted/original) alignment?
1654 if (vector_dynamic_peeling_candidate_ != nullptr) {
1655 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1656 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1657 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1658 vector->AsVecMemoryOperation()->SetAlignment( // forced
1659 Alignment(GetVectorSizeInBytes(), 0));
1660 }
1661 } else {
1662 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1663 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001664 }
1665 } else {
1666 // Scalar store or load.
1667 DCHECK(vector_mode_ == kSequential);
1668 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001669 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001670 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001671 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001672 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001673 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1674 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001675 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001676 }
1677 }
1678 vector_map_->Put(org, vector);
1679}
1680
Aart Bik0148de42017-09-05 09:25:01 -07001681void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1682 DCHECK(reductions_->find(phi) != reductions_->end());
1683 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1684 HInstruction* vector = nullptr;
1685 if (vector_mode_ == kSequential) {
1686 HPhi* new_phi = new (global_allocator_) HPhi(
1687 global_allocator_, kNoRegNumber, 0, phi->GetType());
1688 vector_header_->AddPhi(new_phi);
1689 vector = new_phi;
1690 } else {
1691 // Link vector reduction back to prior unrolled update, or a first phi.
1692 auto it = vector_permanent_map_->find(phi);
1693 if (it != vector_permanent_map_->end()) {
1694 vector = it->second;
1695 } else {
1696 HPhi* new_phi = new (global_allocator_) HPhi(
1697 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1698 vector_header_->AddPhi(new_phi);
1699 vector = new_phi;
1700 }
1701 }
1702 vector_map_->Put(phi, vector);
1703}
1704
1705void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1706 HInstruction* new_phi = vector_map_->Get(phi);
1707 HInstruction* new_init = reductions_->Get(phi);
1708 HInstruction* new_red = vector_map_->Get(reduction);
1709 // Link unrolled vector loop back to new phi.
1710 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1711 DCHECK(new_phi->IsVecOperation());
1712 }
1713 // Prepare the new initialization.
1714 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001715 // Generate a [initial, 0, .., 0] vector for add or
1716 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001717 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001718 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001719 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001720 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001721 if (kind == HVecReduce::ReductionKind::kSum) {
1722 new_init = Insert(vector_preheader_,
1723 new (global_allocator_) HVecSetScalars(global_allocator_,
1724 &new_init,
1725 type,
1726 vector_length,
1727 1,
1728 kNoDexPc));
1729 } else {
1730 new_init = Insert(vector_preheader_,
1731 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1732 new_init,
1733 type,
1734 vector_length,
1735 kNoDexPc));
1736 }
Aart Bik0148de42017-09-05 09:25:01 -07001737 } else {
1738 new_init = ReduceAndExtractIfNeeded(new_init);
1739 }
1740 // Set the phi inputs.
1741 DCHECK(new_phi->IsPhi());
1742 new_phi->AsPhi()->AddInput(new_init);
1743 new_phi->AsPhi()->AddInput(new_red);
1744 // New feed value for next phi (safe mutation in iteration).
1745 reductions_->find(phi)->second = new_phi;
1746}
1747
1748HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1749 if (instruction->IsPhi()) {
1750 HInstruction* input = instruction->InputAt(1);
Aart Bik38a3f212017-10-20 17:02:21 -07001751 if (input->IsVecOperation() && !input->IsVecExtractScalar()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001752 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001753 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001754 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001755 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001756 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1757 // Generate a vector reduction and scalar extract
1758 // x = REDUCE( [x_1, .., x_n] )
1759 // y = x_1
1760 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001761 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001762 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001763 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1764 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001765 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001766 exit->InsertInstructionAfter(instruction, reduce);
1767 }
1768 }
1769 return instruction;
1770}
1771
Aart Bikf8f5a162017-02-06 15:35:29 -08001772#define GENERATE_VEC(x, y) \
1773 if (vector_mode_ == kVector) { \
1774 vector = (x); \
1775 } else { \
1776 DCHECK(vector_mode_ == kSequential); \
1777 vector = (y); \
1778 } \
1779 break;
1780
1781void HLoopOptimization::GenerateVecOp(HInstruction* org,
1782 HInstruction* opa,
1783 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001784 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001785 bool is_unsigned) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001786 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001787 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001788 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001789 switch (org->GetKind()) {
1790 case HInstruction::kNeg:
1791 DCHECK(opb == nullptr);
1792 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001793 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1794 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001795 case HInstruction::kNot:
1796 DCHECK(opb == nullptr);
1797 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001798 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1799 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001800 case HInstruction::kBooleanNot:
1801 DCHECK(opb == nullptr);
1802 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001803 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1804 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001805 case HInstruction::kTypeConversion:
1806 DCHECK(opb == nullptr);
1807 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001808 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1809 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001810 case HInstruction::kAdd:
1811 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001812 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1813 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001814 case HInstruction::kSub:
1815 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001816 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1817 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001818 case HInstruction::kMul:
1819 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001820 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1821 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001822 case HInstruction::kDiv:
1823 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001824 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1825 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001826 case HInstruction::kAnd:
1827 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001828 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1829 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001830 case HInstruction::kOr:
1831 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001832 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1833 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001834 case HInstruction::kXor:
1835 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001836 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1837 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001838 case HInstruction::kShl:
1839 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001840 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1841 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001842 case HInstruction::kShr:
1843 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001844 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1845 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001846 case HInstruction::kUShr:
1847 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001848 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1849 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001850 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001851 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1852 if (vector_mode_ == kVector) {
1853 switch (invoke->GetIntrinsic()) {
1854 case Intrinsics::kMathAbsInt:
1855 case Intrinsics::kMathAbsLong:
1856 case Intrinsics::kMathAbsFloat:
1857 case Intrinsics::kMathAbsDouble:
1858 DCHECK(opb == nullptr);
Aart Bik46b6dbc2017-10-03 11:37:37 -07001859 vector = new (global_allocator_)
1860 HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc);
Aart Bik6daebeb2017-04-03 14:35:41 -07001861 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001862 case Intrinsics::kMathMinIntInt:
1863 case Intrinsics::kMathMinLongLong:
1864 case Intrinsics::kMathMinFloatFloat:
1865 case Intrinsics::kMathMinDoubleDouble: {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001866 NormalizePackedType(&type, &is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001867 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001868 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned, dex_pc);
Aart Bikc8e93c72017-05-10 10:49:22 -07001869 break;
1870 }
1871 case Intrinsics::kMathMaxIntInt:
1872 case Intrinsics::kMathMaxLongLong:
1873 case Intrinsics::kMathMaxFloatFloat:
1874 case Intrinsics::kMathMaxDoubleDouble: {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001875 NormalizePackedType(&type, &is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001876 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001877 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned, dex_pc);
Aart Bikc8e93c72017-05-10 10:49:22 -07001878 break;
1879 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001880 default:
Aart Bik38a3f212017-10-20 17:02:21 -07001881 LOG(FATAL) << "Unsupported SIMD intrinsic " << org->GetId();
Aart Bik6daebeb2017-04-03 14:35:41 -07001882 UNREACHABLE();
1883 } // switch invoke
1884 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001885 // In scalar code, simply clone the method invoke, and replace its operands with the
1886 // corresponding new scalar instructions in the loop. The instruction will get an
1887 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001888 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001889 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001890 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1891 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001892 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001893 invoke->GetType(),
1894 invoke->GetDexPc(),
1895 invoke->GetDexMethodIndex(),
1896 invoke->GetResolvedMethod(),
1897 invoke->GetDispatchInfo(),
1898 invoke->GetInvokeType(),
1899 invoke->GetTargetMethod(),
1900 invoke->GetClinitCheckRequirement());
1901 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001902 size_t num_inputs = inputs.size();
1903 DCHECK_LE(num_args, num_inputs);
1904 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1905 for (size_t index = 0; index < num_inputs; ++index) {
1906 HInstruction* new_input = index < num_args
1907 ? vector_map_->Get(inputs[index])
1908 : inputs[index]; // beyond arguments: just pass through
1909 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001910 }
Aart Bik98990262017-04-10 13:15:57 -07001911 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1912 kNeedsEnvironmentOrCache,
1913 kNoSideEffects,
1914 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001915 vector = new_invoke;
1916 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001917 break;
1918 }
1919 default:
1920 break;
1921 } // switch
1922 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1923 vector_map_->Put(org, vector);
1924}
1925
1926#undef GENERATE_VEC
1927
1928//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001929// Vectorization idioms.
1930//
1931
1932// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001933// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1934// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001935// Provided that the operands are promoted to a wider form to do the arithmetic and
1936// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1937// implementation that operates directly in narrower form (plus one extra bit).
1938// TODO: current version recognizes implicit byte/short/char widening only;
1939// explicit widening from int to long could be added later.
1940bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1941 HInstruction* instruction,
1942 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001943 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001944 uint64_t restrictions) {
1945 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001946 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001947 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001948 if ((instruction->IsShr() ||
1949 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001950 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001951 // Test for (a + b + c) >> 1 for optional constant c.
1952 HInstruction* a = nullptr;
1953 HInstruction* b = nullptr;
1954 int64_t c = 0;
1955 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001956 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001957 // Accept c == 1 (rounded) or c == 0 (not rounded).
1958 bool is_rounded = false;
1959 if (c == 1) {
1960 is_rounded = true;
1961 } else if (c != 0) {
1962 return false;
1963 }
1964 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001965 HInstruction* r = nullptr;
1966 HInstruction* s = nullptr;
1967 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001968 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001969 return false;
1970 }
1971 // Deal with vector restrictions.
1972 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1973 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1974 return false;
1975 }
1976 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1977 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001978 DCHECK(r != nullptr);
1979 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001980 if (generate_code && vector_mode_ != kVector) { // de-idiom
1981 r = instruction->InputAt(0);
1982 s = instruction->InputAt(1);
1983 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001984 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1985 VectorizeUse(node, s, generate_code, type, restrictions)) {
1986 if (generate_code) {
1987 if (vector_mode_ == kVector) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001988 NormalizePackedType(&type, &is_unsigned);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001989 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1990 global_allocator_,
1991 vector_map_->Get(r),
1992 vector_map_->Get(s),
1993 type,
1994 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001995 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001996 is_unsigned,
1997 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07001998 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001999 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002000 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002001 }
2002 }
2003 return true;
2004 }
2005 }
2006 }
2007 return false;
2008}
2009
Aart Bikdbbac8f2017-09-01 13:06:08 -07002010// Method recognizes the following idiom:
2011// q += ABS(a - b) for signed operands a, b
2012// Provided that the operands have the same type or are promoted to a wider form.
2013// Since this may involve a vector length change, the idiom is handled by going directly
2014// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2015// TODO: unsigned SAD too?
2016bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2017 HInstruction* instruction,
2018 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002019 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002020 uint64_t restrictions) {
2021 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2022 // are done in the same precision (either int or long).
2023 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002024 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002025 return false;
2026 }
2027 HInstruction* q = instruction->InputAt(0);
2028 HInstruction* v = instruction->InputAt(1);
2029 HInstruction* a = nullptr;
2030 HInstruction* b = nullptr;
2031 if (v->IsInvokeStaticOrDirect() &&
2032 (v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsInt ||
2033 v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsLong)) {
2034 HInstruction* x = v->InputAt(0);
Aart Bikdf011c32017-09-28 12:53:04 -07002035 if (x->GetType() == reduction_type) {
2036 int64_t c = 0;
2037 if (x->IsSub()) {
2038 a = x->InputAt(0);
2039 b = x->InputAt(1);
2040 } else if (IsAddConst(x, /*out*/ &a, /*out*/ &c)) {
2041 b = graph_->GetConstant(reduction_type, -c); // hidden SUB!
2042 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07002043 }
2044 }
2045 if (a == nullptr || b == nullptr) {
2046 return false;
2047 }
2048 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2049 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002050 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002051 HInstruction* r = a;
2052 HInstruction* s = b;
2053 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002054 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002055 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2056 sub_type = b->GetType();
2057 }
2058 if (a->IsTypeConversion() &&
2059 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2060 sub_type = a->InputAt(0)->GetType();
2061 }
2062 if (b->IsTypeConversion() &&
2063 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2064 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002065 }
2066 if (reduction_type != sub_type &&
2067 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2068 return false;
2069 }
2070 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002071 if (!TrySetVectorType(sub_type, &restrictions) ||
2072 HasVectorRestrictions(restrictions, kNoSAD) ||
2073 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002074 return false;
2075 }
2076 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2077 // idiomatic operation. Sequential code uses the original scalar expressions.
2078 DCHECK(r != nullptr);
2079 DCHECK(s != nullptr);
2080 if (generate_code && vector_mode_ != kVector) { // de-idiom
2081 r = s = v->InputAt(0);
2082 }
2083 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2084 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2085 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2086 if (generate_code) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002087 NormalizePackedType(&reduction_type, &is_unsigned);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002088 if (vector_mode_ == kVector) {
2089 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2090 global_allocator_,
2091 vector_map_->Get(q),
2092 vector_map_->Get(r),
2093 vector_map_->Get(s),
2094 reduction_type,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002095 GetOtherVL(reduction_type, sub_type, vector_length_),
2096 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002097 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2098 } else {
2099 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2100 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2101 }
2102 }
2103 return true;
2104 }
2105 return false;
2106}
2107
Aart Bikf3e61ee2017-04-12 17:09:20 -07002108//
Aart Bik14a68b42017-06-08 14:06:58 -07002109// Vectorization heuristics.
2110//
2111
Aart Bik38a3f212017-10-20 17:02:21 -07002112Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2113 DataType::Type type,
2114 bool is_string_char_at,
2115 uint32_t peeling) {
2116 // Combine the alignment and hidden offset that is guaranteed by
2117 // the Android runtime with a known starting index adjusted as bytes.
2118 int64_t value = 0;
2119 if (IsInt64AndGet(offset, /*out*/ &value)) {
2120 uint32_t start_offset =
2121 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2122 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2123 }
2124 // Otherwise, the Android runtime guarantees at least natural alignment.
2125 return Alignment(DataType::Size(type), 0);
2126}
2127
2128void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2129 const ArrayReference* peeling_candidate) {
2130 // Current heuristic: pick the best static loop peeling factor, if any,
2131 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2132 uint32_t max_vote = 0;
2133 for (int32_t i = 0; i < 16; i++) {
2134 if (peeling_votes[i] > max_vote) {
2135 max_vote = peeling_votes[i];
2136 vector_static_peeling_factor_ = i;
2137 }
2138 }
2139 if (max_vote == 0) {
2140 vector_dynamic_peeling_candidate_ = peeling_candidate;
2141 }
2142}
2143
2144uint32_t HLoopOptimization::MaxNumberPeeled() {
2145 if (vector_dynamic_peeling_candidate_ != nullptr) {
2146 return vector_length_ - 1u; // worst-case
2147 }
2148 return vector_static_peeling_factor_; // known exactly
2149}
2150
Aart Bik14a68b42017-06-08 14:06:58 -07002151bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002152 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002153 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002154 // TODO: trip count is really unsigned entity, provided the guarding test
2155 // is satisfied; deal with this more carefully later
2156 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002157 if (vector_length_ == 0) {
2158 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002159 } else if (trip_count < 0) {
2160 return false; // guard against non-taken/large
2161 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002162 return false; // insufficient iterations
2163 }
2164 return true;
2165}
2166
Artem Serovf26bb6c2017-09-01 10:59:03 +01002167static constexpr uint32_t ARM64_SIMD_MAXIMUM_UNROLL_FACTOR = 8;
2168static constexpr uint32_t ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE = 50;
2169
Aart Bik14a68b42017-06-08 14:06:58 -07002170uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002171 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002172 switch (compiler_driver_->GetInstructionSet()) {
Artem Serovf26bb6c2017-09-01 10:59:03 +01002173 case kArm64: {
Aart Bik521b50f2017-09-09 10:44:45 -07002174 // Don't unroll with insufficient iterations.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002175 // TODO: Unroll loops with unknown trip count.
Aart Bik521b50f2017-09-09 10:44:45 -07002176 DCHECK_NE(vector_length_, 0u);
Aart Bik38a3f212017-10-20 17:02:21 -07002177 if (trip_count < (2 * vector_length_ + max_peel)) {
Aart Bik521b50f2017-09-09 10:44:45 -07002178 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002179 }
Aart Bik521b50f2017-09-09 10:44:45 -07002180 // Don't unroll for large loop body size.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002181 uint32_t instruction_count = block->GetInstructions().CountSize();
Aart Bik521b50f2017-09-09 10:44:45 -07002182 if (instruction_count >= ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE) {
2183 return kNoUnrollingFactor;
2184 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002185 // Find a beneficial unroll factor with the following restrictions:
2186 // - At least one iteration of the transformed loop should be executed.
2187 // - The loop body shouldn't be "too big" (heuristic).
2188 uint32_t uf1 = ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE / instruction_count;
Aart Bik38a3f212017-10-20 17:02:21 -07002189 uint32_t uf2 = (trip_count - max_peel) / vector_length_;
Artem Serovf26bb6c2017-09-01 10:59:03 +01002190 uint32_t unroll_factor =
2191 TruncToPowerOfTwo(std::min({uf1, uf2, ARM64_SIMD_MAXIMUM_UNROLL_FACTOR}));
2192 DCHECK_GE(unroll_factor, 1u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002193 return unroll_factor;
Aart Bik14a68b42017-06-08 14:06:58 -07002194 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002195 case kX86:
2196 case kX86_64:
Aart Bik14a68b42017-06-08 14:06:58 -07002197 default:
Aart Bik521b50f2017-09-09 10:44:45 -07002198 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002199 }
2200}
2201
2202//
Aart Bikf8f5a162017-02-06 15:35:29 -08002203// Helpers.
2204//
2205
2206bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002207 // Start with empty phi induction.
2208 iset_->clear();
2209
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002210 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2211 // smart enough to follow strongly connected components (and it's probably not worth
2212 // it to make it so). See b/33775412.
2213 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2214 return false;
2215 }
Aart Bikb29f6842017-07-28 15:58:41 -07002216
2217 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002218 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2219 if (set != nullptr) {
2220 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002221 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002222 // each instruction is removable and, when restrict uses are requested, other than for phi,
2223 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002224 if (!i->IsInBlock()) {
2225 continue;
2226 } else if (!i->IsRemovable()) {
2227 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002228 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002229 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002230 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2231 if (set->find(use.GetUser()) == set->end()) {
2232 return false;
2233 }
2234 }
2235 }
Aart Bike3dedc52016-11-02 17:50:27 -07002236 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002237 }
Aart Bikcc42be02016-10-20 16:14:16 -07002238 return true;
2239 }
2240 return false;
2241}
2242
Aart Bikb29f6842017-07-28 15:58:41 -07002243bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002244 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002245 // Only unclassified phi cycles are candidates for reductions.
2246 if (induction_range_.IsClassified(phi)) {
2247 return false;
2248 }
2249 // Accept operations like x = x + .., provided that the phi and the reduction are
2250 // used exactly once inside the loop, and by each other.
2251 HInputsRef inputs = phi->GetInputs();
2252 if (inputs.size() == 2) {
2253 HInstruction* reduction = inputs[1];
2254 if (HasReductionFormat(reduction, phi)) {
2255 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002256 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002257 bool single_use_inside_loop =
2258 // Reduction update only used by phi.
2259 reduction->GetUses().HasExactlyOneElement() &&
2260 !reduction->HasEnvironmentUses() &&
2261 // Reduction update is only use of phi inside the loop.
2262 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2263 iset_->size() == 1;
2264 iset_->clear(); // leave the way you found it
2265 if (single_use_inside_loop) {
2266 // Link reduction back, and start recording feed value.
2267 reductions_->Put(reduction, phi);
2268 reductions_->Put(phi, phi->InputAt(0));
2269 return true;
2270 }
2271 }
2272 }
2273 return false;
2274}
2275
2276bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2277 // Start with empty phi induction and reductions.
2278 iset_->clear();
2279 reductions_->clear();
2280
2281 // Scan the phis to find the following (the induction structure has already
2282 // been optimized, so we don't need to worry about trivial cases):
2283 // (1) optional reductions in loop,
2284 // (2) the main induction, used in loop control.
2285 HPhi* phi = nullptr;
2286 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2287 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2288 continue;
2289 } else if (phi == nullptr) {
2290 // Found the first candidate for main induction.
2291 phi = it.Current()->AsPhi();
2292 } else {
2293 return false;
2294 }
2295 }
2296
2297 // Then test for a typical loopheader:
2298 // s: SuspendCheck
2299 // c: Condition(phi, bound)
2300 // i: If(c)
2301 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002302 HInstruction* s = block->GetFirstInstruction();
2303 if (s != nullptr && s->IsSuspendCheck()) {
2304 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002305 if (c != nullptr &&
2306 c->IsCondition() &&
2307 c->GetUses().HasExactlyOneElement() && // only used for termination
2308 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002309 HInstruction* i = c->GetNext();
2310 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2311 iset_->insert(c);
2312 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002313 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002314 return true;
2315 }
2316 }
2317 }
2318 }
2319 return false;
2320}
2321
2322bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002323 if (!block->GetPhis().IsEmpty()) {
2324 return false;
2325 }
2326 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2327 HInstruction* instruction = it.Current();
2328 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2329 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002330 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002331 }
2332 return true;
2333}
2334
2335bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2336 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002337 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002338 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2339 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2340 return true;
2341 }
Aart Bikcc42be02016-10-20 16:14:16 -07002342 }
2343 return false;
2344}
2345
Aart Bik482095d2016-10-10 15:39:10 -07002346bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002347 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002348 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002349 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002350 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002351 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2352 HInstruction* user = use.GetUser();
2353 if (iset_->find(user) == iset_->end()) { // not excluded?
2354 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002355 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002356 // If collect_loop_uses is set, simply keep adding those uses to the set.
2357 // Otherwise, reject uses inside the loop that were not already in the set.
2358 if (collect_loop_uses) {
2359 iset_->insert(user);
2360 continue;
2361 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002362 return false;
2363 }
2364 ++*use_count;
2365 }
2366 }
2367 return true;
2368}
2369
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002370bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2371 HInstruction* instruction,
2372 HBasicBlock* block) {
2373 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002374 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002375 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002376 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002377 const HUseList<HInstruction*>& uses = instruction->GetUses();
2378 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2379 HInstruction* user = it->GetUser();
2380 size_t index = it->GetIndex();
2381 ++it; // increment before replacing
2382 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002383 if (kIsDebugBuild) {
2384 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2385 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2386 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2387 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002388 user->ReplaceInput(replacement, index);
2389 induction_range_.Replace(user, instruction, replacement); // update induction
2390 }
2391 }
Aart Bikb29f6842017-07-28 15:58:41 -07002392 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002393 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2394 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2395 HEnvironment* user = it->GetUser();
2396 size_t index = it->GetIndex();
2397 ++it; // increment before replacing
2398 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002399 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002400 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002401 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2402 user->RemoveAsUserOfInput(index);
2403 user->SetRawEnvAt(index, replacement);
2404 replacement->AddEnvUseAt(user, index);
2405 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002406 }
2407 }
Aart Bik807868e2016-11-03 17:51:43 -07002408 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002409 }
Aart Bik807868e2016-11-03 17:51:43 -07002410 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002411}
2412
Aart Bikf8f5a162017-02-06 15:35:29 -08002413bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2414 HInstruction* instruction,
2415 HBasicBlock* block,
2416 bool collect_loop_uses) {
2417 // Assigning the last value is always successful if there are no uses.
2418 // Otherwise, it succeeds in a no early-exit loop by generating the
2419 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002420 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002421 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2422 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002423 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002424}
2425
Aart Bik6b69e0a2017-01-11 10:20:43 -08002426void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2427 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2428 HInstruction* instruction = i.Current();
2429 if (instruction->IsDeadAndRemovable()) {
2430 simplified_ = true;
2431 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2432 }
2433 }
2434}
2435
Aart Bik14a68b42017-06-08 14:06:58 -07002436bool HLoopOptimization::CanRemoveCycle() {
2437 for (HInstruction* i : *iset_) {
2438 // We can never remove instructions that have environment
2439 // uses when we compile 'debuggable'.
2440 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2441 return false;
2442 }
2443 // A deoptimization should never have an environment input removed.
2444 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2445 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2446 return false;
2447 }
2448 }
2449 }
2450 return true;
2451}
2452
Aart Bik281c6812016-08-26 11:31:48 -07002453} // namespace art