blob: 3dc1ef7534c625a0f003dcab93ab5119dc5083e2 [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,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800451 OptimizingCompilerStats* stats,
452 const char* name)
453 : HOptimization(graph, name, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800454 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700455 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700456 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100457 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700458 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700459 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700460 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700461 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800462 simplified_(false),
463 vector_length_(0),
464 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700465 vector_static_peeling_factor_(0),
466 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700467 vector_runtime_test_a_(nullptr),
468 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700469 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100470 vector_permanent_map_(nullptr),
471 vector_mode_(kSequential),
472 vector_preheader_(nullptr),
473 vector_header_(nullptr),
474 vector_body_(nullptr),
475 vector_index_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700476}
477
478void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800479 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700480 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800481 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700482 return;
483 }
484
Vladimir Markoca6fff82017-10-03 14:49:14 +0100485 // Phase-local allocator.
486 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700487 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100488
Aart Bik96202302016-10-04 17:33:56 -0700489 // Perform loop optimizations.
490 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800491 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800492 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800493 }
494
Aart Bik96202302016-10-04 17:33:56 -0700495 // Detach.
496 loop_allocator_ = nullptr;
497 last_loop_ = top_loop_ = nullptr;
498}
499
Aart Bikb29f6842017-07-28 15:58:41 -0700500//
501// Loop setup and traversal.
502//
503
Aart Bik96202302016-10-04 17:33:56 -0700504void HLoopOptimization::LocalRun() {
505 // Build the linear order using the phase-local allocator. This step enables building
506 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100507 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
508 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700509
Aart Bik281c6812016-08-26 11:31:48 -0700510 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700511 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700512 if (block->IsLoopHeader()) {
513 AddLoop(block->GetLoopInformation());
514 }
515 }
Aart Bik96202302016-10-04 17:33:56 -0700516
Aart Bik8c4a8542016-10-06 11:36:57 -0700517 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800518 // temporary data structures using the phase-local allocator. All new HIR
519 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700520 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100521 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
522 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700523 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100524 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
525 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800526 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100527 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700528 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800529 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700530 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700531 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800532 vector_refs_ = &refs;
533 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700534 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800535 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700536 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800537 // Detach.
538 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700539 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800540 vector_refs_ = nullptr;
541 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700542 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700543 }
Aart Bik281c6812016-08-26 11:31:48 -0700544}
545
546void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
547 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800548 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700549 if (last_loop_ == nullptr) {
550 // First loop.
551 DCHECK(top_loop_ == nullptr);
552 last_loop_ = top_loop_ = node;
553 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
554 // Inner loop.
555 node->outer = last_loop_;
556 DCHECK(last_loop_->inner == nullptr);
557 last_loop_ = last_loop_->inner = node;
558 } else {
559 // Subsequent loop.
560 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
561 last_loop_ = last_loop_->outer;
562 }
563 node->outer = last_loop_->outer;
564 node->previous = last_loop_;
565 DCHECK(last_loop_->next == nullptr);
566 last_loop_ = last_loop_->next = node;
567 }
568}
569
570void HLoopOptimization::RemoveLoop(LoopNode* node) {
571 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700572 DCHECK(node->inner == nullptr);
573 if (node->previous != nullptr) {
574 // Within sequence.
575 node->previous->next = node->next;
576 if (node->next != nullptr) {
577 node->next->previous = node->previous;
578 }
579 } else {
580 // First of sequence.
581 if (node->outer != nullptr) {
582 node->outer->inner = node->next;
583 } else {
584 top_loop_ = node->next;
585 }
586 if (node->next != nullptr) {
587 node->next->outer = node->outer;
588 node->next->previous = nullptr;
589 }
590 }
Aart Bik281c6812016-08-26 11:31:48 -0700591}
592
Aart Bikb29f6842017-07-28 15:58:41 -0700593bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
594 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700595 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700596 // Visit inner loops first. Recompute induction information for this
597 // loop if the induction of any inner loop has changed.
598 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700599 induction_range_.ReVisit(node->loop_info);
600 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800601 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800602 // Note that since each simplification consists of eliminating code (without
603 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800604 do {
605 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800606 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800607 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700608 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800609 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800610 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700611 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700612 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700613 }
Aart Bik281c6812016-08-26 11:31:48 -0700614 }
Aart Bikb29f6842017-07-28 15:58:41 -0700615 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700616}
617
Aart Bikf8f5a162017-02-06 15:35:29 -0800618//
619// Optimization.
620//
621
Aart Bik281c6812016-08-26 11:31:48 -0700622void HLoopOptimization::SimplifyInduction(LoopNode* node) {
623 HBasicBlock* header = node->loop_info->GetHeader();
624 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700625 // Scan the phis in the header to find opportunities to simplify an induction
626 // cycle that is only used outside the loop. Replace these uses, if any, with
627 // the last value and remove the induction cycle.
628 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
629 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700630 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
631 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800632 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
633 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700634 // Note that it's ok to have replaced uses after the loop with the last value, without
635 // being able to remove the cycle. Environment uses (which are the reason we may not be
636 // able to remove the cycle) within the loop will still hold the right value. We must
637 // have tried first, however, to replace outside uses.
638 if (CanRemoveCycle()) {
639 simplified_ = true;
640 for (HInstruction* i : *iset_) {
641 RemoveFromCycle(i);
642 }
643 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700644 }
Aart Bik482095d2016-10-10 15:39:10 -0700645 }
646 }
647}
648
649void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800650 // Iterate over all basic blocks in the loop-body.
651 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
652 HBasicBlock* block = it.Current();
653 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800654 RemoveDeadInstructions(block->GetPhis());
655 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800656 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800657 if (block->GetPredecessors().size() == 1 &&
658 block->GetSuccessors().size() == 1 &&
659 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800660 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800661 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800662 } else if (block->GetSuccessors().size() == 2) {
663 // Trivial if block can be bypassed to either branch.
664 HBasicBlock* succ0 = block->GetSuccessors()[0];
665 HBasicBlock* succ1 = block->GetSuccessors()[1];
666 HBasicBlock* meet0 = nullptr;
667 HBasicBlock* meet1 = nullptr;
668 if (succ0 != succ1 &&
669 IsGotoBlock(succ0, &meet0) &&
670 IsGotoBlock(succ1, &meet1) &&
671 meet0 == meet1 && // meets again
672 meet0 != block && // no self-loop
673 meet0->GetPhis().IsEmpty()) { // not used for merging
674 simplified_ = true;
675 succ0->DisconnectAndDelete();
676 if (block->Dominates(meet0)) {
677 block->RemoveDominatedBlock(meet0);
678 succ1->AddDominatedBlock(meet0);
679 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700680 }
Aart Bik482095d2016-10-10 15:39:10 -0700681 }
Aart Bik281c6812016-08-26 11:31:48 -0700682 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800683 }
Aart Bik281c6812016-08-26 11:31:48 -0700684}
685
Aart Bikb29f6842017-07-28 15:58:41 -0700686bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700687 HBasicBlock* header = node->loop_info->GetHeader();
688 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700689 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800690 int64_t trip_count = 0;
691 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700692 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700693 }
Aart Bik281c6812016-08-26 11:31:48 -0700694 // Ensure there is only a single loop-body (besides the header).
695 HBasicBlock* body = nullptr;
696 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
697 if (it.Current() != header) {
698 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700699 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700700 }
701 body = it.Current();
702 }
703 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700704 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700705 // Ensure there is only a single exit point.
706 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700707 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700708 }
709 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
710 ? header->GetSuccessors()[1]
711 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700712 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700713 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700714 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700715 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800716 // Detect either an empty loop (no side effects other than plain iteration) or
717 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
718 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700719 HPhi* main_phi = nullptr;
720 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800721 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700722 if (reductions_->empty() && // TODO: possible with some effort
723 (is_empty || trip_count == 1) &&
724 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800725 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800726 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700727 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800728 preheader->MergeInstructionsWith(body);
729 }
730 body->DisconnectAndDelete();
731 exit->RemovePredecessor(header);
732 header->RemoveSuccessor(exit);
733 header->RemoveDominatedBlock(exit);
734 header->DisconnectAndDelete();
735 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800736 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800737 preheader->AddDominatedBlock(exit);
738 exit->SetDominator(preheader);
739 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700740 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800741 }
742 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800743 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700744 if (kEnableVectorization &&
745 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700746 ShouldVectorize(node, body, trip_count) &&
747 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
748 Vectorize(node, body, exit, trip_count);
749 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700750 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700751 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800752 }
Aart Bikb29f6842017-07-28 15:58:41 -0700753 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800754}
755
756//
757// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
758// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
759// Intel Press, June, 2004 (http://www.aartbik.com/).
760//
761
Aart Bik14a68b42017-06-08 14:06:58 -0700762bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800763 // Reset vector bookkeeping.
764 vector_length_ = 0;
765 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700766 vector_static_peeling_factor_ = 0;
767 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800768 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800769 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800770
771 // Phis in the loop-body prevent vectorization.
772 if (!block->GetPhis().IsEmpty()) {
773 return false;
774 }
775
776 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
777 // occurrence, which allows passing down attributes down the use tree.
778 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
779 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
780 return false; // failure to vectorize a left-hand-side
781 }
782 }
783
Aart Bik38a3f212017-10-20 17:02:21 -0700784 // Prepare alignment analysis:
785 // (1) find desired alignment (SIMD vector size in bytes).
786 // (2) initialize static loop peeling votes (peeling factor that will
787 // make one particular reference aligned), never to exceed (1).
788 // (3) variable to record how many references share same alignment.
789 // (4) variable to record suitable candidate for dynamic loop peeling.
790 uint32_t desired_alignment = GetVectorSizeInBytes();
791 DCHECK_LE(desired_alignment, 16u);
792 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
793 uint32_t max_num_same_alignment = 0;
794 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800795
796 // Data dependence analysis. Find each pair of references with same type, where
797 // at least one is a write. Each such pair denotes a possible data dependence.
798 // This analysis exploits the property that differently typed arrays cannot be
799 // aliased, as well as the property that references either point to the same
800 // array or to two completely disjoint arrays, i.e., no partial aliasing.
801 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700802 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800803 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700804 uint32_t num_same_alignment = 0;
805 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800806 for (auto j = i; ++j != vector_refs_->end(); ) {
807 if (i->type == j->type && (i->lhs || j->lhs)) {
808 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
809 HInstruction* a = i->base;
810 HInstruction* b = j->base;
811 HInstruction* x = i->offset;
812 HInstruction* y = j->offset;
813 if (a == b) {
814 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
815 // Conservatively assume a loop-carried data dependence otherwise, and reject.
816 if (x != y) {
817 return false;
818 }
Aart Bik38a3f212017-10-20 17:02:21 -0700819 // Count the number of references that have the same alignment (since
820 // base and offset are the same) and where at least one is a write, so
821 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
822 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800823 } else {
824 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
825 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
826 // generating an explicit a != b disambiguation runtime test on the two references.
827 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700828 // To avoid excessive overhead, we only accept one a != b test.
829 if (vector_runtime_test_a_ == nullptr) {
830 // First test found.
831 vector_runtime_test_a_ = a;
832 vector_runtime_test_b_ = b;
833 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
834 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
835 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800836 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800837 }
838 }
839 }
840 }
Aart Bik38a3f212017-10-20 17:02:21 -0700841 // Update information for finding suitable alignment strategy:
842 // (1) update votes for static loop peeling,
843 // (2) update suitable candidate for dynamic loop peeling.
844 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
845 if (alignment.Base() >= desired_alignment) {
846 // If the array/string object has a known, sufficient alignment, use the
847 // initial offset to compute the static loop peeling vote (this always
848 // works, since elements have natural alignment).
849 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
850 uint32_t vote = (offset == 0)
851 ? 0
852 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
853 DCHECK_LT(vote, 16u);
854 ++peeling_votes[vote];
855 } else if (BaseAlignment() >= desired_alignment &&
856 num_same_alignment > max_num_same_alignment) {
857 // Otherwise, if the array/string object has a known, sufficient alignment
858 // for just the base but with an unknown offset, record the candidate with
859 // the most occurrences for dynamic loop peeling (again, the peeling always
860 // works, since elements have natural alignment).
861 max_num_same_alignment = num_same_alignment;
862 peeling_candidate = &(*i);
863 }
864 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -0800865
Aart Bik38a3f212017-10-20 17:02:21 -0700866 // Find a suitable alignment strategy.
867 SetAlignmentStrategy(peeling_votes, peeling_candidate);
868
869 // Does vectorization seem profitable?
870 if (!IsVectorizationProfitable(trip_count)) {
871 return false;
872 }
Aart Bik14a68b42017-06-08 14:06:58 -0700873
Aart Bikf8f5a162017-02-06 15:35:29 -0800874 // Success!
875 return true;
876}
877
878void HLoopOptimization::Vectorize(LoopNode* node,
879 HBasicBlock* block,
880 HBasicBlock* exit,
881 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800882 HBasicBlock* header = node->loop_info->GetHeader();
883 HBasicBlock* preheader = node->loop_info->GetPreHeader();
884
Aart Bik14a68b42017-06-08 14:06:58 -0700885 // Pick a loop unrolling factor for the vector loop.
886 uint32_t unroll = GetUnrollingFactor(block, trip_count);
887 uint32_t chunk = vector_length_ * unroll;
888
Aart Bik38a3f212017-10-20 17:02:21 -0700889 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
890
Aart Bik14a68b42017-06-08 14:06:58 -0700891 // A cleanup loop is needed, at least, for any unknown trip count or
892 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -0700893 bool needs_cleanup = trip_count == 0 ||
894 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800895
896 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700897 HPhi* main_phi = nullptr;
898 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800899 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700900 vector_header_ = header;
901 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800902
Aart Bikdbbac8f2017-09-01 13:06:08 -0700903 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100904 DataType::Type induc_type = main_phi->GetType();
905 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
906 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700907
Aart Bik38a3f212017-10-20 17:02:21 -0700908 // Generate the trip count for static or dynamic loop peeling, if needed:
909 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -0700910 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -0700911 if (vector_static_peeling_factor_ != 0) {
912 // Static loop peeling for SIMD alignment (using the most suitable
913 // fixed peeling factor found during prior alignment analysis).
914 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
915 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
916 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
917 // Dynamic loop peeling for SIMD alignment (using the most suitable
918 // candidate found during prior alignment analysis):
919 // rem = offset % ALIGN; // adjusted as #elements
920 // ptc = rem == 0 ? 0 : (ALIGN - rem);
921 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
922 uint32_t align = GetVectorSizeInBytes() >> shift;
923 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
924 vector_dynamic_peeling_candidate_->is_string_char_at);
925 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
926 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
927 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
928 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
929 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
930 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
931 induc_type, graph_->GetConstant(induc_type, align), rem));
932 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
933 rem, graph_->GetConstant(induc_type, 0)));
934 ptc = Insert(preheader, new (global_allocator_) HSelect(
935 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
936 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -0700937 }
938
939 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800940 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -0700941 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -0700942 // vtc = stc - (stc - ptc) % chunk;
943 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800944 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
945 HInstruction* vtc = stc;
946 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700947 DCHECK(IsPowerOfTwo(chunk));
948 HInstruction* diff = stc;
949 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -0700950 if (trip_count == 0) {
951 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
952 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
953 }
Aart Bik14a68b42017-06-08 14:06:58 -0700954 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
955 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800956 HInstruction* rem = Insert(
957 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700958 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700959 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800960 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
961 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700962 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800963
964 // Generate runtime disambiguation test:
965 // vtc = a != b ? vtc : 0;
966 if (vector_runtime_test_a_ != nullptr) {
967 HInstruction* rt = Insert(
968 preheader,
969 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
970 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700971 new (global_allocator_)
972 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -0800973 needs_cleanup = true;
974 }
975
Aart Bik38a3f212017-10-20 17:02:21 -0700976 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -0700977 // for ( ; i < ptc; i += 1)
978 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -0700979 //
980 // NOTE: The alignment forced by the peeling loop is preserved even if data is
981 // moved around during suspend checks, since all analysis was based on
982 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -0700983 if (ptc != nullptr) {
984 vector_mode_ = kSequential;
985 GenerateNewLoop(node,
986 block,
987 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
988 vector_index_,
989 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700990 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700991 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -0700992 }
993
994 // Generate vector loop, possibly further unrolled:
995 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800996 // <vectorized-loop-body>
997 vector_mode_ = kVector;
998 GenerateNewLoop(node,
999 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001000 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1001 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001002 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001003 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001004 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001005 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1006
1007 // Generate cleanup loop, if needed:
1008 // for ( ; i < stc; i += 1)
1009 // <loop-body>
1010 if (needs_cleanup) {
1011 vector_mode_ = kSequential;
1012 GenerateNewLoop(node,
1013 block,
1014 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001015 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001016 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001017 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001018 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001019 }
1020
Aart Bik0148de42017-09-05 09:25:01 -07001021 // Link reductions to their final uses.
1022 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1023 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001024 HInstruction* phi = i->first;
1025 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1026 // Deal with regular uses.
1027 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1028 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1029 }
1030 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001031 }
1032 }
1033
Aart Bikf8f5a162017-02-06 15:35:29 -08001034 // Remove the original loop by disconnecting the body block
1035 // and removing all instructions from the header.
1036 block->DisconnectAndDelete();
1037 while (!header->GetFirstInstruction()->IsGoto()) {
1038 header->RemoveInstruction(header->GetFirstInstruction());
1039 }
Aart Bikb29f6842017-07-28 15:58:41 -07001040
Aart Bik14a68b42017-06-08 14:06:58 -07001041 // Update loop hierarchy: the old header now resides in the same outer loop
1042 // as the old preheader. Note that we don't bother putting sequential
1043 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001044 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1045 node->loop_info = vloop;
1046}
1047
1048void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1049 HBasicBlock* block,
1050 HBasicBlock* new_preheader,
1051 HInstruction* lo,
1052 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001053 HInstruction* step,
1054 uint32_t unroll) {
1055 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001056 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001057 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001058 vector_preheader_ = new_preheader,
1059 vector_header_ = vector_preheader_->GetSingleSuccessor();
1060 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001061 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1062 kNoRegNumber,
1063 0,
1064 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001065 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001066 // for (i = lo; i < hi; i += step)
1067 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001068 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1069 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001070 vector_header_->AddInstruction(cond);
1071 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001072 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001073 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001074 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001075 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001076 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001077 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1078 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1079 DCHECK(vectorized_def);
1080 }
1081 // Generate body from the instruction map, but in original program order.
1082 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1083 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1084 auto i = vector_map_->find(it.Current());
1085 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1086 Insert(vector_body_, i->second);
1087 // Deal with instructions that need an environment, such as the scalar intrinsics.
1088 if (i->second->NeedsEnvironment()) {
1089 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1090 }
1091 }
1092 }
Aart Bik0148de42017-09-05 09:25:01 -07001093 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001094 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1095 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001096 }
Aart Bik0148de42017-09-05 09:25:01 -07001097 // Finalize phi inputs for the reductions (if any).
1098 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1099 if (!i->first->IsPhi()) {
1100 DCHECK(i->second->IsPhi());
1101 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1102 }
1103 }
Aart Bikb29f6842017-07-28 15:58:41 -07001104 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001105 phi->AddInput(lo);
1106 phi->AddInput(vector_index_);
1107 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001108}
1109
Aart Bikf8f5a162017-02-06 15:35:29 -08001110bool HLoopOptimization::VectorizeDef(LoopNode* node,
1111 HInstruction* instruction,
1112 bool generate_code) {
1113 // Accept a left-hand-side array base[index] for
1114 // (1) supported vector type,
1115 // (2) loop-invariant base,
1116 // (3) unit stride index,
1117 // (4) vectorizable right-hand-side value.
1118 uint64_t restrictions = kNone;
1119 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001120 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001121 HInstruction* base = instruction->InputAt(0);
1122 HInstruction* index = instruction->InputAt(1);
1123 HInstruction* value = instruction->InputAt(2);
1124 HInstruction* offset = nullptr;
1125 if (TrySetVectorType(type, &restrictions) &&
1126 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001127 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001128 VectorizeUse(node, value, generate_code, type, restrictions)) {
1129 if (generate_code) {
1130 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001131 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001132 } else {
1133 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1134 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001135 return true;
1136 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001137 return false;
1138 }
Aart Bik0148de42017-09-05 09:25:01 -07001139 // Accept a left-hand-side reduction for
1140 // (1) supported vector type,
1141 // (2) vectorizable right-hand-side value.
1142 auto redit = reductions_->find(instruction);
1143 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001144 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001145 // Recognize SAD idiom or direct reduction.
1146 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1147 (TrySetVectorType(type, &restrictions) &&
1148 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001149 if (generate_code) {
1150 HInstruction* new_red = vector_map_->Get(instruction);
1151 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1152 vector_permanent_map_->Overwrite(redit->second, new_red);
1153 }
1154 return true;
1155 }
1156 return false;
1157 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001158 // Branch back okay.
1159 if (instruction->IsGoto()) {
1160 return true;
1161 }
1162 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1163 // Note that actual uses are inspected during right-hand-side tree traversal.
1164 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1165}
1166
Aart Bik304c8a52017-05-23 11:01:13 -07001167// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -08001168bool HLoopOptimization::VectorizeUse(LoopNode* node,
1169 HInstruction* instruction,
1170 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001171 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001172 uint64_t restrictions) {
1173 // Accept anything for which code has already been generated.
1174 if (generate_code) {
1175 if (vector_map_->find(instruction) != vector_map_->end()) {
1176 return true;
1177 }
1178 }
1179 // Continue the right-hand-side tree traversal, passing in proper
1180 // types and vector restrictions along the way. During code generation,
1181 // all new nodes are drawn from the global allocator.
1182 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1183 // Accept invariant use, using scalar expansion.
1184 if (generate_code) {
1185 GenerateVecInv(instruction, type);
1186 }
1187 return true;
1188 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001189 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001190 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1191 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001192 return false;
1193 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001194 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001195 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001196 // (2) loop-invariant base,
1197 // (3) unit stride index,
1198 // (4) vectorizable right-hand-side value.
1199 HInstruction* base = instruction->InputAt(0);
1200 HInstruction* index = instruction->InputAt(1);
1201 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001202 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001203 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001204 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001205 if (generate_code) {
1206 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001207 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001208 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001209 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001210 }
1211 return true;
1212 }
Aart Bik0148de42017-09-05 09:25:01 -07001213 } else if (instruction->IsPhi()) {
1214 // Accept particular phi operations.
1215 if (reductions_->find(instruction) != reductions_->end()) {
1216 // Deal with vector restrictions.
1217 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1218 return false;
1219 }
1220 // Accept a reduction.
1221 if (generate_code) {
1222 GenerateVecReductionPhi(instruction->AsPhi());
1223 }
1224 return true;
1225 }
1226 // TODO: accept right-hand-side induction?
1227 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001228 } else if (instruction->IsTypeConversion()) {
1229 // Accept particular type conversions.
1230 HTypeConversion* conversion = instruction->AsTypeConversion();
1231 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001232 DataType::Type from = conversion->GetInputType();
1233 DataType::Type to = conversion->GetResultType();
1234 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001235 uint32_t size_vec = DataType::Size(type);
1236 uint32_t size_from = DataType::Size(from);
1237 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001238 // Accept an integral conversion
1239 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1240 // (1b) widening from at least vector type, and
1241 // (2) vectorizable operand.
1242 if ((size_to < size_from &&
1243 size_to == size_vec &&
1244 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1245 (size_to >= size_from &&
1246 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001247 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001248 if (generate_code) {
1249 if (vector_mode_ == kVector) {
1250 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1251 } else {
1252 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1253 }
1254 }
1255 return true;
1256 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001257 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001258 DCHECK_EQ(to, type);
1259 // Accept int to float conversion for
1260 // (1) supported int,
1261 // (2) vectorizable operand.
1262 if (TrySetVectorType(from, &restrictions) &&
1263 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1264 if (generate_code) {
1265 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1266 }
1267 return true;
1268 }
1269 }
1270 return false;
1271 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1272 // Accept unary operator for vectorizable operand.
1273 HInstruction* opa = instruction->InputAt(0);
1274 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1275 if (generate_code) {
1276 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1277 }
1278 return true;
1279 }
1280 } else if (instruction->IsAdd() || instruction->IsSub() ||
1281 instruction->IsMul() || instruction->IsDiv() ||
1282 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1283 // Deal with vector restrictions.
1284 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1285 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1286 return false;
1287 }
1288 // Accept binary operator for vectorizable operands.
1289 HInstruction* opa = instruction->InputAt(0);
1290 HInstruction* opb = instruction->InputAt(1);
1291 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1292 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1293 if (generate_code) {
1294 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1295 }
1296 return true;
1297 }
1298 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001299 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001300 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1301 return true;
1302 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001303 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001304 HInstruction* opa = instruction->InputAt(0);
1305 HInstruction* opb = instruction->InputAt(1);
1306 HInstruction* r = opa;
1307 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001308 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1309 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1310 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001311 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1312 // Shifts right need extra care to account for higher order bits.
1313 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1314 if (instruction->IsShr() &&
1315 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1316 return false; // reject, unless all operands are sign-extension narrower
1317 } else if (instruction->IsUShr() &&
1318 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1319 return false; // reject, unless all operands are zero-extension narrower
1320 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001321 }
1322 // Accept shift operator for vectorizable/invariant operands.
1323 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001324 DCHECK(r != nullptr);
1325 if (generate_code && vector_mode_ != kVector) { // de-idiom
1326 r = opa;
1327 }
Aart Bik50e20d52017-05-05 14:07:29 -07001328 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001329 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001330 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001331 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001332 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001333 if (0 <= distance && distance < max_distance) {
1334 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001335 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001336 }
1337 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001338 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001339 }
1340 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001341 // Accept particular intrinsics.
1342 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1343 switch (invoke->GetIntrinsic()) {
1344 case Intrinsics::kMathAbsInt:
1345 case Intrinsics::kMathAbsLong:
1346 case Intrinsics::kMathAbsFloat:
1347 case Intrinsics::kMathAbsDouble: {
1348 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001349 HInstruction* opa = instruction->InputAt(0);
1350 HInstruction* r = opa;
1351 bool is_unsigned = false;
1352 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001353 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001354 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1355 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1356 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001357 }
1358 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001359 DCHECK(r != nullptr);
1360 if (generate_code && vector_mode_ != kVector) { // de-idiom
1361 r = opa;
1362 }
1363 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001364 if (generate_code) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001365 NormalizePackedType(&type, &is_unsigned);
Aart Bik304c8a52017-05-23 11:01:13 -07001366 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001367 }
1368 return true;
1369 }
1370 return false;
1371 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001372 case Intrinsics::kMathMinIntInt:
1373 case Intrinsics::kMathMinLongLong:
1374 case Intrinsics::kMathMinFloatFloat:
1375 case Intrinsics::kMathMinDoubleDouble:
1376 case Intrinsics::kMathMaxIntInt:
1377 case Intrinsics::kMathMaxLongLong:
1378 case Intrinsics::kMathMaxFloatFloat:
1379 case Intrinsics::kMathMaxDoubleDouble: {
1380 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001381 HInstruction* opa = instruction->InputAt(0);
1382 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001383 HInstruction* r = opa;
1384 HInstruction* s = opb;
1385 bool is_unsigned = false;
1386 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1387 return false;
1388 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1389 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1390 return false; // reject, unless all operands are same-extension narrower
1391 }
1392 // Accept MIN/MAX(x, y) for vectorizable operands.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001393 DCHECK(r != nullptr);
1394 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001395 if (generate_code && vector_mode_ != kVector) { // de-idiom
1396 r = opa;
1397 s = opb;
1398 }
1399 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1400 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001401 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001402 GenerateVecOp(
1403 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001404 }
1405 return true;
1406 }
1407 return false;
1408 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001409 default:
1410 return false;
1411 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001412 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001413 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001414}
1415
Aart Bik38a3f212017-10-20 17:02:21 -07001416uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1417 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001418 case InstructionSet::kArm:
1419 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001420 return 8; // 64-bit SIMD
1421 default:
1422 return 16; // 128-bit SIMD
1423 }
1424}
1425
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001426bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001427 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1428 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001429 case InstructionSet::kArm:
1430 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001431 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001432 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001433 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001434 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001435 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001436 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001437 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001438 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001439 case DataType::Type::kUint16:
1440 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001441 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001442 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001443 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001444 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001445 return TrySetVectorLength(2);
1446 default:
1447 break;
1448 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001449 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001450 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001451 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001452 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001453 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001454 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001455 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001456 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001457 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001458 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001459 case DataType::Type::kUint16:
1460 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001461 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001462 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001463 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001464 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001465 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001466 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001467 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001468 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001469 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001470 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001471 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001472 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001473 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001474 return TrySetVectorLength(2);
1475 default:
1476 return false;
1477 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001478 case InstructionSet::kX86:
1479 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001480 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001481 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1482 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001483 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001484 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001485 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001486 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001487 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001488 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001489 case DataType::Type::kUint16:
1490 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001491 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001492 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001493 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001494 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001495 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001496 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001497 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001498 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001499 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001500 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001501 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001502 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001503 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001504 return TrySetVectorLength(2);
1505 default:
1506 break;
1507 } // switch type
1508 }
1509 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001510 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001511 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1512 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001513 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001514 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001515 case DataType::Type::kInt8:
Lena Djokic38e380b2017-10-30 16:17:10 +01001516 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001517 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001518 case DataType::Type::kUint16:
1519 case DataType::Type::kInt16:
Lena Djokic38e380b2017-10-30 16:17:10 +01001520 *restrictions |= kNoDiv | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001521 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001522 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001523 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001524 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001525 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001526 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001527 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001528 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001529 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001530 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001531 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001532 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001533 return TrySetVectorLength(2);
1534 default:
1535 break;
1536 } // switch type
1537 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001538 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001539 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001540 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1541 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001542 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001543 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001544 case DataType::Type::kInt8:
Lena Djokic38e380b2017-10-30 16:17:10 +01001545 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001546 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001547 case DataType::Type::kUint16:
1548 case DataType::Type::kInt16:
Lena Djokic38e380b2017-10-30 16:17:10 +01001549 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001550 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001551 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001552 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001553 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001554 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001555 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001556 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001557 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001558 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001559 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001560 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001561 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001562 return TrySetVectorLength(2);
1563 default:
1564 break;
1565 } // switch type
1566 }
1567 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001568 default:
1569 return false;
1570 } // switch instruction set
1571}
1572
1573bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1574 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1575 // First time set?
1576 if (vector_length_ == 0) {
1577 vector_length_ = length;
1578 }
1579 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1580 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1581 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1582 return vector_length_ == length;
1583}
1584
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001585void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001586 if (vector_map_->find(org) == vector_map_->end()) {
1587 // In scalar code, just use a self pass-through for scalar invariants
1588 // (viz. expression remains itself).
1589 if (vector_mode_ == kSequential) {
1590 vector_map_->Put(org, org);
1591 return;
1592 }
1593 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001594 HInstruction* vector = nullptr;
1595 auto it = vector_permanent_map_->find(org);
1596 if (it != vector_permanent_map_->end()) {
1597 vector = it->second; // reuse during unrolling
1598 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001599 // Generates ReplicateScalar( (optional_type_conv) org ).
1600 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001601 DataType::Type input_type = input->GetType();
1602 if (type != input_type && (type == DataType::Type::kInt64 ||
1603 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001604 input = Insert(vector_preheader_,
1605 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1606 }
1607 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001608 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001609 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1610 }
1611 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001612 }
1613}
1614
1615void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1616 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001617 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001618 int64_t value = 0;
1619 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001620 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001621 if (org->IsPhi()) {
1622 Insert(vector_body_, subscript); // lacks layout placeholder
1623 }
1624 }
1625 vector_map_->Put(org, subscript);
1626 }
1627}
1628
1629void HLoopOptimization::GenerateVecMem(HInstruction* org,
1630 HInstruction* opa,
1631 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001632 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001633 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001634 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001635 HInstruction* vector = nullptr;
1636 if (vector_mode_ == kVector) {
1637 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001638 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001639 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001640 if (opb != nullptr) {
1641 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001642 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001643 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001644 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001645 vector = new (global_allocator_) HVecLoad(global_allocator_,
1646 base,
1647 opa,
1648 type,
1649 org->GetSideEffects(),
1650 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001651 is_string_char_at,
1652 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001653 }
Aart Bik38a3f212017-10-20 17:02:21 -07001654 // Known (forced/adjusted/original) alignment?
1655 if (vector_dynamic_peeling_candidate_ != nullptr) {
1656 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1657 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1658 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1659 vector->AsVecMemoryOperation()->SetAlignment( // forced
1660 Alignment(GetVectorSizeInBytes(), 0));
1661 }
1662 } else {
1663 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1664 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001665 }
1666 } else {
1667 // Scalar store or load.
1668 DCHECK(vector_mode_ == kSequential);
1669 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001670 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001671 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001672 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001673 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001674 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1675 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001676 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001677 }
1678 }
1679 vector_map_->Put(org, vector);
1680}
1681
Aart Bik0148de42017-09-05 09:25:01 -07001682void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1683 DCHECK(reductions_->find(phi) != reductions_->end());
1684 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1685 HInstruction* vector = nullptr;
1686 if (vector_mode_ == kSequential) {
1687 HPhi* new_phi = new (global_allocator_) HPhi(
1688 global_allocator_, kNoRegNumber, 0, phi->GetType());
1689 vector_header_->AddPhi(new_phi);
1690 vector = new_phi;
1691 } else {
1692 // Link vector reduction back to prior unrolled update, or a first phi.
1693 auto it = vector_permanent_map_->find(phi);
1694 if (it != vector_permanent_map_->end()) {
1695 vector = it->second;
1696 } else {
1697 HPhi* new_phi = new (global_allocator_) HPhi(
1698 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1699 vector_header_->AddPhi(new_phi);
1700 vector = new_phi;
1701 }
1702 }
1703 vector_map_->Put(phi, vector);
1704}
1705
1706void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1707 HInstruction* new_phi = vector_map_->Get(phi);
1708 HInstruction* new_init = reductions_->Get(phi);
1709 HInstruction* new_red = vector_map_->Get(reduction);
1710 // Link unrolled vector loop back to new phi.
1711 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1712 DCHECK(new_phi->IsVecOperation());
1713 }
1714 // Prepare the new initialization.
1715 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001716 // Generate a [initial, 0, .., 0] vector for add or
1717 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001718 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001719 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001720 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001721 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001722 if (kind == HVecReduce::ReductionKind::kSum) {
1723 new_init = Insert(vector_preheader_,
1724 new (global_allocator_) HVecSetScalars(global_allocator_,
1725 &new_init,
1726 type,
1727 vector_length,
1728 1,
1729 kNoDexPc));
1730 } else {
1731 new_init = Insert(vector_preheader_,
1732 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1733 new_init,
1734 type,
1735 vector_length,
1736 kNoDexPc));
1737 }
Aart Bik0148de42017-09-05 09:25:01 -07001738 } else {
1739 new_init = ReduceAndExtractIfNeeded(new_init);
1740 }
1741 // Set the phi inputs.
1742 DCHECK(new_phi->IsPhi());
1743 new_phi->AsPhi()->AddInput(new_init);
1744 new_phi->AsPhi()->AddInput(new_red);
1745 // New feed value for next phi (safe mutation in iteration).
1746 reductions_->find(phi)->second = new_phi;
1747}
1748
1749HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1750 if (instruction->IsPhi()) {
1751 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001752 if (HVecOperation::ReturnsSIMDValue(input)) {
1753 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001754 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001755 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001756 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001757 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001758 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1759 // Generate a vector reduction and scalar extract
1760 // x = REDUCE( [x_1, .., x_n] )
1761 // y = x_1
1762 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001763 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001764 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001765 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1766 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001767 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001768 exit->InsertInstructionAfter(instruction, reduce);
1769 }
1770 }
1771 return instruction;
1772}
1773
Aart Bikf8f5a162017-02-06 15:35:29 -08001774#define GENERATE_VEC(x, y) \
1775 if (vector_mode_ == kVector) { \
1776 vector = (x); \
1777 } else { \
1778 DCHECK(vector_mode_ == kSequential); \
1779 vector = (y); \
1780 } \
1781 break;
1782
1783void HLoopOptimization::GenerateVecOp(HInstruction* org,
1784 HInstruction* opa,
1785 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001786 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001787 bool is_unsigned) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001788 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001789 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001790 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001791 switch (org->GetKind()) {
1792 case HInstruction::kNeg:
1793 DCHECK(opb == nullptr);
1794 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001795 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1796 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001797 case HInstruction::kNot:
1798 DCHECK(opb == nullptr);
1799 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001800 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1801 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001802 case HInstruction::kBooleanNot:
1803 DCHECK(opb == nullptr);
1804 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001805 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1806 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001807 case HInstruction::kTypeConversion:
1808 DCHECK(opb == nullptr);
1809 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001810 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1811 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001812 case HInstruction::kAdd:
1813 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001814 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1815 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001816 case HInstruction::kSub:
1817 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001818 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1819 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001820 case HInstruction::kMul:
1821 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001822 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1823 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001824 case HInstruction::kDiv:
1825 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001826 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1827 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001828 case HInstruction::kAnd:
1829 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001830 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1831 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001832 case HInstruction::kOr:
1833 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001834 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1835 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001836 case HInstruction::kXor:
1837 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001838 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1839 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001840 case HInstruction::kShl:
1841 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001842 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1843 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001844 case HInstruction::kShr:
1845 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001846 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1847 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001848 case HInstruction::kUShr:
1849 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001850 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1851 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001852 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001853 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1854 if (vector_mode_ == kVector) {
1855 switch (invoke->GetIntrinsic()) {
1856 case Intrinsics::kMathAbsInt:
1857 case Intrinsics::kMathAbsLong:
1858 case Intrinsics::kMathAbsFloat:
1859 case Intrinsics::kMathAbsDouble:
1860 DCHECK(opb == nullptr);
Aart Bik46b6dbc2017-10-03 11:37:37 -07001861 vector = new (global_allocator_)
1862 HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc);
Aart Bik6daebeb2017-04-03 14:35:41 -07001863 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001864 case Intrinsics::kMathMinIntInt:
1865 case Intrinsics::kMathMinLongLong:
1866 case Intrinsics::kMathMinFloatFloat:
1867 case Intrinsics::kMathMinDoubleDouble: {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001868 NormalizePackedType(&type, &is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001869 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001870 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned, dex_pc);
Aart Bikc8e93c72017-05-10 10:49:22 -07001871 break;
1872 }
1873 case Intrinsics::kMathMaxIntInt:
1874 case Intrinsics::kMathMaxLongLong:
1875 case Intrinsics::kMathMaxFloatFloat:
1876 case Intrinsics::kMathMaxDoubleDouble: {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001877 NormalizePackedType(&type, &is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001878 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001879 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned, dex_pc);
Aart Bikc8e93c72017-05-10 10:49:22 -07001880 break;
1881 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001882 default:
Aart Bik38a3f212017-10-20 17:02:21 -07001883 LOG(FATAL) << "Unsupported SIMD intrinsic " << org->GetId();
Aart Bik6daebeb2017-04-03 14:35:41 -07001884 UNREACHABLE();
1885 } // switch invoke
1886 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001887 // In scalar code, simply clone the method invoke, and replace its operands with the
1888 // corresponding new scalar instructions in the loop. The instruction will get an
1889 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001890 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001891 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001892 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1893 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001894 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001895 invoke->GetType(),
1896 invoke->GetDexPc(),
1897 invoke->GetDexMethodIndex(),
1898 invoke->GetResolvedMethod(),
1899 invoke->GetDispatchInfo(),
1900 invoke->GetInvokeType(),
1901 invoke->GetTargetMethod(),
1902 invoke->GetClinitCheckRequirement());
1903 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001904 size_t num_inputs = inputs.size();
1905 DCHECK_LE(num_args, num_inputs);
1906 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1907 for (size_t index = 0; index < num_inputs; ++index) {
1908 HInstruction* new_input = index < num_args
1909 ? vector_map_->Get(inputs[index])
1910 : inputs[index]; // beyond arguments: just pass through
1911 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001912 }
Aart Bik98990262017-04-10 13:15:57 -07001913 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1914 kNeedsEnvironmentOrCache,
1915 kNoSideEffects,
1916 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001917 vector = new_invoke;
1918 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001919 break;
1920 }
1921 default:
1922 break;
1923 } // switch
1924 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1925 vector_map_->Put(org, vector);
1926}
1927
1928#undef GENERATE_VEC
1929
1930//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001931// Vectorization idioms.
1932//
1933
1934// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001935// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1936// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001937// Provided that the operands are promoted to a wider form to do the arithmetic and
1938// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1939// implementation that operates directly in narrower form (plus one extra bit).
1940// TODO: current version recognizes implicit byte/short/char widening only;
1941// explicit widening from int to long could be added later.
1942bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1943 HInstruction* instruction,
1944 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001945 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001946 uint64_t restrictions) {
1947 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001948 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001949 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001950 if ((instruction->IsShr() ||
1951 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001952 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001953 // Test for (a + b + c) >> 1 for optional constant c.
1954 HInstruction* a = nullptr;
1955 HInstruction* b = nullptr;
1956 int64_t c = 0;
1957 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001958 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001959 // Accept c == 1 (rounded) or c == 0 (not rounded).
1960 bool is_rounded = false;
1961 if (c == 1) {
1962 is_rounded = true;
1963 } else if (c != 0) {
1964 return false;
1965 }
1966 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001967 HInstruction* r = nullptr;
1968 HInstruction* s = nullptr;
1969 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001970 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001971 return false;
1972 }
1973 // Deal with vector restrictions.
1974 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1975 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1976 return false;
1977 }
1978 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1979 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001980 DCHECK(r != nullptr);
1981 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001982 if (generate_code && vector_mode_ != kVector) { // de-idiom
1983 r = instruction->InputAt(0);
1984 s = instruction->InputAt(1);
1985 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001986 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1987 VectorizeUse(node, s, generate_code, type, restrictions)) {
1988 if (generate_code) {
1989 if (vector_mode_ == kVector) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001990 NormalizePackedType(&type, &is_unsigned);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001991 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1992 global_allocator_,
1993 vector_map_->Get(r),
1994 vector_map_->Get(s),
1995 type,
1996 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001997 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001998 is_unsigned,
1999 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002000 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002001 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002002 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002003 }
2004 }
2005 return true;
2006 }
2007 }
2008 }
2009 return false;
2010}
2011
Aart Bikdbbac8f2017-09-01 13:06:08 -07002012// Method recognizes the following idiom:
2013// q += ABS(a - b) for signed operands a, b
2014// Provided that the operands have the same type or are promoted to a wider form.
2015// Since this may involve a vector length change, the idiom is handled by going directly
2016// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2017// TODO: unsigned SAD too?
2018bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2019 HInstruction* instruction,
2020 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002021 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002022 uint64_t restrictions) {
2023 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2024 // are done in the same precision (either int or long).
2025 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002026 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002027 return false;
2028 }
2029 HInstruction* q = instruction->InputAt(0);
2030 HInstruction* v = instruction->InputAt(1);
2031 HInstruction* a = nullptr;
2032 HInstruction* b = nullptr;
2033 if (v->IsInvokeStaticOrDirect() &&
2034 (v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsInt ||
2035 v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsLong)) {
2036 HInstruction* x = v->InputAt(0);
Aart Bikdf011c32017-09-28 12:53:04 -07002037 if (x->GetType() == reduction_type) {
2038 int64_t c = 0;
2039 if (x->IsSub()) {
2040 a = x->InputAt(0);
2041 b = x->InputAt(1);
2042 } else if (IsAddConst(x, /*out*/ &a, /*out*/ &c)) {
2043 b = graph_->GetConstant(reduction_type, -c); // hidden SUB!
2044 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07002045 }
2046 }
2047 if (a == nullptr || b == nullptr) {
2048 return false;
2049 }
2050 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2051 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002052 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002053 HInstruction* r = a;
2054 HInstruction* s = b;
2055 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002056 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002057 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2058 sub_type = b->GetType();
2059 }
2060 if (a->IsTypeConversion() &&
2061 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2062 sub_type = a->InputAt(0)->GetType();
2063 }
2064 if (b->IsTypeConversion() &&
2065 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2066 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002067 }
2068 if (reduction_type != sub_type &&
2069 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2070 return false;
2071 }
2072 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002073 if (!TrySetVectorType(sub_type, &restrictions) ||
2074 HasVectorRestrictions(restrictions, kNoSAD) ||
2075 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002076 return false;
2077 }
2078 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2079 // idiomatic operation. Sequential code uses the original scalar expressions.
2080 DCHECK(r != nullptr);
2081 DCHECK(s != nullptr);
2082 if (generate_code && vector_mode_ != kVector) { // de-idiom
2083 r = s = v->InputAt(0);
2084 }
2085 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2086 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2087 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2088 if (generate_code) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002089 NormalizePackedType(&reduction_type, &is_unsigned);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002090 if (vector_mode_ == kVector) {
2091 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2092 global_allocator_,
2093 vector_map_->Get(q),
2094 vector_map_->Get(r),
2095 vector_map_->Get(s),
2096 reduction_type,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002097 GetOtherVL(reduction_type, sub_type, vector_length_),
2098 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002099 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2100 } else {
2101 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2102 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2103 }
2104 }
2105 return true;
2106 }
2107 return false;
2108}
2109
Aart Bikf3e61ee2017-04-12 17:09:20 -07002110//
Aart Bik14a68b42017-06-08 14:06:58 -07002111// Vectorization heuristics.
2112//
2113
Aart Bik38a3f212017-10-20 17:02:21 -07002114Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2115 DataType::Type type,
2116 bool is_string_char_at,
2117 uint32_t peeling) {
2118 // Combine the alignment and hidden offset that is guaranteed by
2119 // the Android runtime with a known starting index adjusted as bytes.
2120 int64_t value = 0;
2121 if (IsInt64AndGet(offset, /*out*/ &value)) {
2122 uint32_t start_offset =
2123 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2124 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2125 }
2126 // Otherwise, the Android runtime guarantees at least natural alignment.
2127 return Alignment(DataType::Size(type), 0);
2128}
2129
2130void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2131 const ArrayReference* peeling_candidate) {
2132 // Current heuristic: pick the best static loop peeling factor, if any,
2133 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2134 uint32_t max_vote = 0;
2135 for (int32_t i = 0; i < 16; i++) {
2136 if (peeling_votes[i] > max_vote) {
2137 max_vote = peeling_votes[i];
2138 vector_static_peeling_factor_ = i;
2139 }
2140 }
2141 if (max_vote == 0) {
2142 vector_dynamic_peeling_candidate_ = peeling_candidate;
2143 }
2144}
2145
2146uint32_t HLoopOptimization::MaxNumberPeeled() {
2147 if (vector_dynamic_peeling_candidate_ != nullptr) {
2148 return vector_length_ - 1u; // worst-case
2149 }
2150 return vector_static_peeling_factor_; // known exactly
2151}
2152
Aart Bik14a68b42017-06-08 14:06:58 -07002153bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002154 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002155 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002156 // TODO: trip count is really unsigned entity, provided the guarding test
2157 // is satisfied; deal with this more carefully later
2158 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002159 if (vector_length_ == 0) {
2160 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002161 } else if (trip_count < 0) {
2162 return false; // guard against non-taken/large
2163 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002164 return false; // insufficient iterations
2165 }
2166 return true;
2167}
2168
Artem Serovf26bb6c2017-09-01 10:59:03 +01002169static constexpr uint32_t ARM64_SIMD_MAXIMUM_UNROLL_FACTOR = 8;
2170static constexpr uint32_t ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE = 50;
2171
Aart Bik14a68b42017-06-08 14:06:58 -07002172uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002173 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002174 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00002175 case InstructionSet::kArm64: {
Aart Bik521b50f2017-09-09 10:44:45 -07002176 // Don't unroll with insufficient iterations.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002177 // TODO: Unroll loops with unknown trip count.
Aart Bik521b50f2017-09-09 10:44:45 -07002178 DCHECK_NE(vector_length_, 0u);
Aart Bik38a3f212017-10-20 17:02:21 -07002179 if (trip_count < (2 * vector_length_ + max_peel)) {
Aart Bik521b50f2017-09-09 10:44:45 -07002180 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002181 }
Aart Bik521b50f2017-09-09 10:44:45 -07002182 // Don't unroll for large loop body size.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002183 uint32_t instruction_count = block->GetInstructions().CountSize();
Aart Bik521b50f2017-09-09 10:44:45 -07002184 if (instruction_count >= ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE) {
2185 return kNoUnrollingFactor;
2186 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002187 // Find a beneficial unroll factor with the following restrictions:
2188 // - At least one iteration of the transformed loop should be executed.
2189 // - The loop body shouldn't be "too big" (heuristic).
2190 uint32_t uf1 = ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE / instruction_count;
Aart Bik38a3f212017-10-20 17:02:21 -07002191 uint32_t uf2 = (trip_count - max_peel) / vector_length_;
Artem Serovf26bb6c2017-09-01 10:59:03 +01002192 uint32_t unroll_factor =
2193 TruncToPowerOfTwo(std::min({uf1, uf2, ARM64_SIMD_MAXIMUM_UNROLL_FACTOR}));
2194 DCHECK_GE(unroll_factor, 1u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002195 return unroll_factor;
Aart Bik14a68b42017-06-08 14:06:58 -07002196 }
Vladimir Marko33bff252017-11-01 14:35:42 +00002197 case InstructionSet::kX86:
2198 case InstructionSet::kX86_64:
Aart Bik14a68b42017-06-08 14:06:58 -07002199 default:
Aart Bik521b50f2017-09-09 10:44:45 -07002200 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002201 }
2202}
2203
2204//
Aart Bikf8f5a162017-02-06 15:35:29 -08002205// Helpers.
2206//
2207
2208bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002209 // Start with empty phi induction.
2210 iset_->clear();
2211
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002212 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2213 // smart enough to follow strongly connected components (and it's probably not worth
2214 // it to make it so). See b/33775412.
2215 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2216 return false;
2217 }
Aart Bikb29f6842017-07-28 15:58:41 -07002218
2219 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002220 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2221 if (set != nullptr) {
2222 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002223 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002224 // each instruction is removable and, when restrict uses are requested, other than for phi,
2225 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002226 if (!i->IsInBlock()) {
2227 continue;
2228 } else if (!i->IsRemovable()) {
2229 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002230 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002231 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002232 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2233 if (set->find(use.GetUser()) == set->end()) {
2234 return false;
2235 }
2236 }
2237 }
Aart Bike3dedc52016-11-02 17:50:27 -07002238 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002239 }
Aart Bikcc42be02016-10-20 16:14:16 -07002240 return true;
2241 }
2242 return false;
2243}
2244
Aart Bikb29f6842017-07-28 15:58:41 -07002245bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002246 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002247 // Only unclassified phi cycles are candidates for reductions.
2248 if (induction_range_.IsClassified(phi)) {
2249 return false;
2250 }
2251 // Accept operations like x = x + .., provided that the phi and the reduction are
2252 // used exactly once inside the loop, and by each other.
2253 HInputsRef inputs = phi->GetInputs();
2254 if (inputs.size() == 2) {
2255 HInstruction* reduction = inputs[1];
2256 if (HasReductionFormat(reduction, phi)) {
2257 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002258 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002259 bool single_use_inside_loop =
2260 // Reduction update only used by phi.
2261 reduction->GetUses().HasExactlyOneElement() &&
2262 !reduction->HasEnvironmentUses() &&
2263 // Reduction update is only use of phi inside the loop.
2264 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2265 iset_->size() == 1;
2266 iset_->clear(); // leave the way you found it
2267 if (single_use_inside_loop) {
2268 // Link reduction back, and start recording feed value.
2269 reductions_->Put(reduction, phi);
2270 reductions_->Put(phi, phi->InputAt(0));
2271 return true;
2272 }
2273 }
2274 }
2275 return false;
2276}
2277
2278bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2279 // Start with empty phi induction and reductions.
2280 iset_->clear();
2281 reductions_->clear();
2282
2283 // Scan the phis to find the following (the induction structure has already
2284 // been optimized, so we don't need to worry about trivial cases):
2285 // (1) optional reductions in loop,
2286 // (2) the main induction, used in loop control.
2287 HPhi* phi = nullptr;
2288 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2289 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2290 continue;
2291 } else if (phi == nullptr) {
2292 // Found the first candidate for main induction.
2293 phi = it.Current()->AsPhi();
2294 } else {
2295 return false;
2296 }
2297 }
2298
2299 // Then test for a typical loopheader:
2300 // s: SuspendCheck
2301 // c: Condition(phi, bound)
2302 // i: If(c)
2303 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002304 HInstruction* s = block->GetFirstInstruction();
2305 if (s != nullptr && s->IsSuspendCheck()) {
2306 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002307 if (c != nullptr &&
2308 c->IsCondition() &&
2309 c->GetUses().HasExactlyOneElement() && // only used for termination
2310 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002311 HInstruction* i = c->GetNext();
2312 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2313 iset_->insert(c);
2314 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002315 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002316 return true;
2317 }
2318 }
2319 }
2320 }
2321 return false;
2322}
2323
2324bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002325 if (!block->GetPhis().IsEmpty()) {
2326 return false;
2327 }
2328 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2329 HInstruction* instruction = it.Current();
2330 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2331 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002332 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002333 }
2334 return true;
2335}
2336
2337bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2338 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002339 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002340 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2341 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2342 return true;
2343 }
Aart Bikcc42be02016-10-20 16:14:16 -07002344 }
2345 return false;
2346}
2347
Aart Bik482095d2016-10-10 15:39:10 -07002348bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002349 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002350 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002351 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002352 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002353 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2354 HInstruction* user = use.GetUser();
2355 if (iset_->find(user) == iset_->end()) { // not excluded?
2356 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002357 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002358 // If collect_loop_uses is set, simply keep adding those uses to the set.
2359 // Otherwise, reject uses inside the loop that were not already in the set.
2360 if (collect_loop_uses) {
2361 iset_->insert(user);
2362 continue;
2363 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002364 return false;
2365 }
2366 ++*use_count;
2367 }
2368 }
2369 return true;
2370}
2371
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002372bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2373 HInstruction* instruction,
2374 HBasicBlock* block) {
2375 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002376 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002377 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002378 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002379 const HUseList<HInstruction*>& uses = instruction->GetUses();
2380 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2381 HInstruction* user = it->GetUser();
2382 size_t index = it->GetIndex();
2383 ++it; // increment before replacing
2384 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002385 if (kIsDebugBuild) {
2386 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2387 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2388 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2389 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002390 user->ReplaceInput(replacement, index);
2391 induction_range_.Replace(user, instruction, replacement); // update induction
2392 }
2393 }
Aart Bikb29f6842017-07-28 15:58:41 -07002394 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002395 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2396 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2397 HEnvironment* user = it->GetUser();
2398 size_t index = it->GetIndex();
2399 ++it; // increment before replacing
2400 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002401 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002402 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002403 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2404 user->RemoveAsUserOfInput(index);
2405 user->SetRawEnvAt(index, replacement);
2406 replacement->AddEnvUseAt(user, index);
2407 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002408 }
2409 }
Aart Bik807868e2016-11-03 17:51:43 -07002410 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002411 }
Aart Bik807868e2016-11-03 17:51:43 -07002412 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002413}
2414
Aart Bikf8f5a162017-02-06 15:35:29 -08002415bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2416 HInstruction* instruction,
2417 HBasicBlock* block,
2418 bool collect_loop_uses) {
2419 // Assigning the last value is always successful if there are no uses.
2420 // Otherwise, it succeeds in a no early-exit loop by generating the
2421 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002422 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002423 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2424 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002425 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002426}
2427
Aart Bik6b69e0a2017-01-11 10:20:43 -08002428void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2429 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2430 HInstruction* instruction = i.Current();
2431 if (instruction->IsDeadAndRemovable()) {
2432 simplified_ = true;
2433 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2434 }
2435 }
2436}
2437
Aart Bik14a68b42017-06-08 14:06:58 -07002438bool HLoopOptimization::CanRemoveCycle() {
2439 for (HInstruction* i : *iset_) {
2440 // We can never remove instructions that have environment
2441 // uses when we compile 'debuggable'.
2442 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2443 return false;
2444 }
2445 // A deoptimization should never have an environment input removed.
2446 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2447 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2448 return false;
2449 }
2450 }
2451 }
2452 return true;
2453}
2454
Aart Bik281c6812016-08-26 11:31:48 -07002455} // namespace art