blob: abd644ae9b3fcb71bf48d6f4886d407103009337 [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
Aart Bikf8f5a162017-02-06 15:35:29 -080033// Enables vectorization (SIMDization) in the loop optimizer.
34static constexpr bool kEnableVectorization = true;
35
Aart Bik521b50f2017-09-09 10:44:45 -070036// No loop unrolling factor (just one copy of the loop-body).
37static constexpr uint32_t kNoUnrollingFactor = 1;
38
Aart Bik29aa0822018-03-08 11:28:00 -080039// Values that indicate unbounded end.
40static constexpr int64_t kNoLo = std::numeric_limits<int64_t>::min();
41static constexpr int64_t kNoHi = std::numeric_limits<int64_t>::max();
42
Aart Bik38a3f212017-10-20 17:02:21 -070043//
44// Static helpers.
45//
46
47// Base alignment for arrays/strings guaranteed by the Android runtime.
48static uint32_t BaseAlignment() {
49 return kObjectAlignment;
50}
51
52// Hidden offset for arrays/strings guaranteed by the Android runtime.
53static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
54 return is_string_char_at
55 ? mirror::String::ValueOffset().Uint32Value()
56 : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
57}
58
Aart Bik9abf8942016-10-14 09:49:42 -070059// Remove the instruction from the graph. A bit more elaborate than the usual
60// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070061static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070062 instruction->RemoveAsUserOfAllInputs();
63 instruction->RemoveEnvironmentUsers();
64 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010065 RemoveEnvironmentUses(instruction);
66 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070067}
68
Aart Bik807868e2016-11-03 17:51:43 -070069// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070070static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
71 if (block->GetPredecessors().size() == 1 &&
72 block->GetSuccessors().size() == 1 &&
73 block->IsSingleGoto()) {
74 *succ = block->GetSingleSuccessor();
75 return true;
76 }
77 return false;
78}
79
Aart Bik807868e2016-11-03 17:51:43 -070080// Detect an early exit loop.
81static bool IsEarlyExit(HLoopInformation* loop_info) {
82 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
83 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
84 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
85 if (!loop_info->Contains(*successor)) {
86 return true;
87 }
88 }
89 }
90 return false;
91}
92
Aart Bik68ca7022017-09-26 16:44:23 -070093// Forward declaration.
94static bool IsZeroExtensionAndGet(HInstruction* instruction,
95 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070096 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -070097
Aart Bikdf011c32017-09-28 12:53:04 -070098// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -070099// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700100static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100101 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700102 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700103 // Accept any already wider constant that would be handled properly by sign
104 // extension when represented in the *width* of the given narrower data type
Aart Bik4d1a9d42017-10-19 14:40:55 -0700105 // (the fact that Uint8/Uint16 normally zero extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700106 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700107 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700108 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100109 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100110 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700111 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700112 *operand = instruction;
113 return true;
114 }
115 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100116 case DataType::Type::kUint16:
117 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700118 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700119 *operand = instruction;
120 return true;
121 }
122 return false;
123 default:
124 return false;
125 }
126 }
Aart Bikdf011c32017-09-28 12:53:04 -0700127 // An implicit widening conversion of any signed expression sign-extends.
128 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700129 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100130 case DataType::Type::kInt8:
131 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700132 *operand = instruction;
133 return true;
134 default:
135 return false;
136 }
137 }
Aart Bikdf011c32017-09-28 12:53:04 -0700138 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700139 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700140 HInstruction* conv = instruction->InputAt(0);
141 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700142 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700143 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700144 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700145 if (type == from && (from == DataType::Type::kInt8 ||
146 from == DataType::Type::kInt16 ||
147 from == DataType::Type::kInt32)) {
148 *operand = conv;
149 return true;
150 }
151 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700152 case DataType::Type::kInt16:
153 return type == DataType::Type::kUint16 &&
154 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700155 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700156 default:
157 return false;
158 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700159 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700160 return false;
161}
162
Aart Bikdf011c32017-09-28 12:53:04 -0700163// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700164// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700165static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100166 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700167 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700168 // Accept any already wider constant that would be handled properly by zero
169 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700170 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700171 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700172 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700173 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100174 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100175 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700176 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700177 *operand = instruction;
178 return true;
179 }
180 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100181 case DataType::Type::kUint16:
182 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700183 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700184 *operand = instruction;
185 return true;
186 }
187 return false;
188 default:
189 return false;
190 }
191 }
Aart Bikdf011c32017-09-28 12:53:04 -0700192 // An implicit widening conversion of any unsigned expression zero-extends.
193 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100194 switch (type) {
195 case DataType::Type::kUint8:
196 case DataType::Type::kUint16:
197 *operand = instruction;
198 return true;
199 default:
200 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700201 }
202 }
Aart Bikdf011c32017-09-28 12:53:04 -0700203 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700204 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700205 HInstruction* conv = instruction->InputAt(0);
206 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700207 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700208 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700209 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700210 if (type == from && from == DataType::Type::kUint16) {
211 *operand = conv;
212 return true;
213 }
214 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700215 case DataType::Type::kUint16:
216 return type == DataType::Type::kInt16 &&
217 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700218 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700219 default:
220 return false;
221 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700222 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700223 return false;
224}
225
Aart Bik304c8a52017-05-23 11:01:13 -0700226// Detect situations with same-extension narrower operands.
227// Returns true on success and sets is_unsigned accordingly.
228static bool IsNarrowerOperands(HInstruction* a,
229 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100230 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700231 /*out*/ HInstruction** r,
232 /*out*/ HInstruction** s,
233 /*out*/ bool* is_unsigned) {
Aart Bik4d1a9d42017-10-19 14:40:55 -0700234 // Look for a matching sign extension.
235 DataType::Type stype = HVecOperation::ToSignedType(type);
236 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700237 *is_unsigned = false;
238 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700239 }
240 // Look for a matching zero extension.
241 DataType::Type utype = HVecOperation::ToUnsignedType(type);
242 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700243 *is_unsigned = true;
244 return true;
245 }
246 return false;
247}
248
249// As above, single operand.
250static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100251 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700252 /*out*/ HInstruction** r,
253 /*out*/ bool* is_unsigned) {
Aart Bik4d1a9d42017-10-19 14:40:55 -0700254 // Look for a matching sign extension.
255 DataType::Type stype = HVecOperation::ToSignedType(type);
256 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700257 *is_unsigned = false;
258 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700259 }
260 // Look for a matching zero extension.
261 DataType::Type utype = HVecOperation::ToUnsignedType(type);
262 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700263 *is_unsigned = true;
264 return true;
265 }
266 return false;
267}
268
Aart Bikdbbac8f2017-09-01 13:06:08 -0700269// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700270static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100271 DCHECK(DataType::IsIntegralType(other_type));
272 DCHECK(DataType::IsIntegralType(vector_type));
273 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
274 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700275}
276
Aart Bik5f805002017-05-16 16:42:41 -0700277// Detect up to two instructions a and b, and an acccumulated constant c.
278static bool IsAddConstHelper(HInstruction* instruction,
279 /*out*/ HInstruction** a,
280 /*out*/ HInstruction** b,
281 /*out*/ int64_t* c,
282 int32_t depth) {
283 static constexpr int32_t kMaxDepth = 8; // don't search too deep
284 int64_t value = 0;
285 if (IsInt64AndGet(instruction, &value)) {
286 *c += value;
287 return true;
288 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
289 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
290 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
291 } else if (*a == nullptr) {
292 *a = instruction;
293 return true;
294 } else if (*b == nullptr) {
295 *b = instruction;
296 return true;
297 }
298 return false; // too many non-const operands
299}
300
301// Detect a + b + c for an optional constant c.
302static bool IsAddConst(HInstruction* instruction,
303 /*out*/ HInstruction** a,
304 /*out*/ HInstruction** b,
305 /*out*/ int64_t* c) {
306 if (instruction->IsAdd()) {
307 // Try to find a + b and accumulated c.
308 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
309 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
310 *b != nullptr) {
311 return true;
312 }
313 // Found a + b.
314 *a = instruction->InputAt(0);
315 *b = instruction->InputAt(1);
316 *c = 0;
317 return true;
318 }
319 return false;
320}
321
Aart Bikdf011c32017-09-28 12:53:04 -0700322// Detect a + c for constant c.
323static bool IsAddConst(HInstruction* instruction,
324 /*out*/ HInstruction** a,
325 /*out*/ int64_t* c) {
326 if (instruction->IsAdd()) {
327 if (IsInt64AndGet(instruction->InputAt(0), c)) {
328 *a = instruction->InputAt(1);
329 return true;
330 } else if (IsInt64AndGet(instruction->InputAt(1), c)) {
331 *a = instruction->InputAt(0);
332 return true;
333 }
334 }
335 return false;
336}
337
Aart Bik29aa0822018-03-08 11:28:00 -0800338// Detect clipped [lo, hi] range for nested MIN-MAX operations on a clippee,
339// such as MIN(hi, MAX(lo, clippee)) for an arbitrary clippee expression.
340// Example: MIN(10, MIN(20, MAX(0, x))) yields [0, 10] with clippee x.
341static bool IsClipped(HInstruction* instruction,
342 /*out*/ int64_t* lo,
343 /*out*/ int64_t* hi,
344 /*out*/ HInstruction** clippee) {
345 // Recurse into MIN-MAX expressions and 'tighten' the range [lo, hi].
346 if (instruction->IsMin() || instruction->IsMax()) {
347 // Find MIN-MAX(const, ..) or MIN-MAX(.., const).
348 for (int i = 0; i < 2; i++) {
349 int64_t c = 0;
350 if (IsInt64AndGet(instruction->InputAt(i), &c)) {
351 if (instruction->IsMin()) {
352 *hi = std::min(*hi, c);
353 } else {
354 *lo = std::max(*lo, c);
355 }
356 return IsClipped(instruction->InputAt(1 - i), lo, hi, clippee);
357 }
358 }
359 // Recursion fails at any MIN/MAX that does not have one constant
360 // argument, e.g. MIN(x, y) or MAX(2 * x, f()).
361 return false;
362 }
363 // Recursion ends in any other expression. At this point we record the leaf
364 // expression as the clippee and report success on the range [lo, hi].
365 DCHECK(*clippee == nullptr);
366 *clippee = instruction;
367 return true;
368}
369
370// Accept various saturated addition forms.
371static bool IsSaturatedAdd(DataType::Type type, int64_t lo, int64_t hi, bool is_unsigned) {
372 // MIN(r + s, 255) => SAT_ADD_unsigned
373 // MAX(MIN(r + s, 127), -128) => SAT_ADD_signed etc.
374 if (DataType::Size(type) == 1) {
375 return is_unsigned
376 ? (lo <= 0 && hi == std::numeric_limits<uint8_t>::max())
377 : (lo == std::numeric_limits<int8_t>::min() &&
378 hi == std::numeric_limits<int8_t>::max());
379 } else if (DataType::Size(type) == 2) {
380 return is_unsigned
381 ? (lo <= 0 && hi == std::numeric_limits<uint16_t>::max())
382 : (lo == std::numeric_limits<int16_t>::min() &&
383 hi == std::numeric_limits<int16_t>::max());
384 }
385 return false;
386}
387
388// Accept various saturated subtraction forms.
389static bool IsSaturatedSub(DataType::Type type, int64_t lo, int64_t hi, bool is_unsigned) {
390 // MAX(r - s, 0) => SAT_SUB_unsigned
391 // MIN(MAX(r - s, -128), 127) => SAT_ADD_signed etc.
392 if (DataType::Size(type) == 1) {
393 return is_unsigned
394 ? (lo == 0 && hi >= std::numeric_limits<uint8_t>::max())
395 : (lo == std::numeric_limits<int8_t>::min() &&
396 hi == std::numeric_limits<int8_t>::max());
397 } else if (DataType::Size(type) == 2) {
398 return is_unsigned
399 ? (lo == 0 && hi >= std::numeric_limits<uint16_t>::min())
400 : (lo == std::numeric_limits<int16_t>::min() &&
401 hi == std::numeric_limits<int16_t>::max());
402 }
403 return false;
404}
405
Aart Bikb29f6842017-07-28 15:58:41 -0700406// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700407// x = x_phi + ..
408// x = x_phi - ..
Aart Bikb29f6842017-07-28 15:58:41 -0700409// x = min(x_phi, ..)
Aart Bik1f8d51b2018-02-15 10:42:37 -0800410// x = max(x_phi, ..)
Aart Bikb29f6842017-07-28 15:58:41 -0700411static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
Aart Bik1f8d51b2018-02-15 10:42:37 -0800412 if (reduction->IsAdd() || reduction->IsMin() || reduction->IsMax()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700413 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
414 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700415 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700416 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700417 }
418 return false;
419}
420
Aart Bikdbbac8f2017-09-01 13:06:08 -0700421// Translates vector operation to reduction kind.
422static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
423 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700424 return HVecReduce::kSum;
425 } else if (reduction->IsVecMin()) {
426 return HVecReduce::kMin;
427 } else if (reduction->IsVecMax()) {
428 return HVecReduce::kMax;
429 }
Aart Bik38a3f212017-10-20 17:02:21 -0700430 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700431 UNREACHABLE();
432}
433
Aart Bikf8f5a162017-02-06 15:35:29 -0800434// Test vector restrictions.
435static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
436 return (restrictions & tested) != 0;
437}
438
Aart Bikf3e61ee2017-04-12 17:09:20 -0700439// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800440static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
441 DCHECK(block != nullptr);
442 DCHECK(instruction != nullptr);
443 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
444 return instruction;
445}
446
Artem Serov21c7e6f2017-07-27 16:04:42 +0100447// Check that instructions from the induction sets are fully removed: have no uses
448// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100449static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100450 for (HInstruction* instr : *iset) {
451 if (instr->GetBlock() != nullptr ||
452 !instr->GetUses().empty() ||
453 !instr->GetEnvUses().empty() ||
454 HasEnvironmentUsedByOthers(instr)) {
455 return false;
456 }
457 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100458 return true;
459}
460
Aart Bik281c6812016-08-26 11:31:48 -0700461//
Aart Bikb29f6842017-07-28 15:58:41 -0700462// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700463//
464
465HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800466 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700467 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800468 OptimizingCompilerStats* stats,
469 const char* name)
470 : HOptimization(graph, name, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800471 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700472 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700473 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100474 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700475 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700476 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700477 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700478 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800479 simplified_(false),
480 vector_length_(0),
481 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700482 vector_static_peeling_factor_(0),
483 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700484 vector_runtime_test_a_(nullptr),
485 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700486 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100487 vector_permanent_map_(nullptr),
488 vector_mode_(kSequential),
489 vector_preheader_(nullptr),
490 vector_header_(nullptr),
491 vector_body_(nullptr),
492 vector_index_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700493}
494
495void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800496 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700497 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800498 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700499 return;
500 }
501
Vladimir Markoca6fff82017-10-03 14:49:14 +0100502 // Phase-local allocator.
503 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700504 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100505
Aart Bik96202302016-10-04 17:33:56 -0700506 // Perform loop optimizations.
507 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800508 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800509 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800510 }
511
Aart Bik96202302016-10-04 17:33:56 -0700512 // Detach.
513 loop_allocator_ = nullptr;
514 last_loop_ = top_loop_ = nullptr;
515}
516
Aart Bikb29f6842017-07-28 15:58:41 -0700517//
518// Loop setup and traversal.
519//
520
Aart Bik96202302016-10-04 17:33:56 -0700521void HLoopOptimization::LocalRun() {
522 // Build the linear order using the phase-local allocator. This step enables building
523 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100524 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
525 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700526
Aart Bik281c6812016-08-26 11:31:48 -0700527 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700528 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700529 if (block->IsLoopHeader()) {
530 AddLoop(block->GetLoopInformation());
531 }
532 }
Aart Bik96202302016-10-04 17:33:56 -0700533
Aart Bik8c4a8542016-10-06 11:36:57 -0700534 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800535 // temporary data structures using the phase-local allocator. All new HIR
536 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700537 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100538 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
539 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700540 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100541 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
542 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800543 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100544 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700545 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800546 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700547 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700548 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800549 vector_refs_ = &refs;
550 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700551 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800552 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700553 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800554 // Detach.
555 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700556 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800557 vector_refs_ = nullptr;
558 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700559 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700560 }
Aart Bik281c6812016-08-26 11:31:48 -0700561}
562
563void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
564 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800565 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700566 if (last_loop_ == nullptr) {
567 // First loop.
568 DCHECK(top_loop_ == nullptr);
569 last_loop_ = top_loop_ = node;
570 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
571 // Inner loop.
572 node->outer = last_loop_;
573 DCHECK(last_loop_->inner == nullptr);
574 last_loop_ = last_loop_->inner = node;
575 } else {
576 // Subsequent loop.
577 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
578 last_loop_ = last_loop_->outer;
579 }
580 node->outer = last_loop_->outer;
581 node->previous = last_loop_;
582 DCHECK(last_loop_->next == nullptr);
583 last_loop_ = last_loop_->next = node;
584 }
585}
586
587void HLoopOptimization::RemoveLoop(LoopNode* node) {
588 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700589 DCHECK(node->inner == nullptr);
590 if (node->previous != nullptr) {
591 // Within sequence.
592 node->previous->next = node->next;
593 if (node->next != nullptr) {
594 node->next->previous = node->previous;
595 }
596 } else {
597 // First of sequence.
598 if (node->outer != nullptr) {
599 node->outer->inner = node->next;
600 } else {
601 top_loop_ = node->next;
602 }
603 if (node->next != nullptr) {
604 node->next->outer = node->outer;
605 node->next->previous = nullptr;
606 }
607 }
Aart Bik281c6812016-08-26 11:31:48 -0700608}
609
Aart Bikb29f6842017-07-28 15:58:41 -0700610bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
611 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700612 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700613 // Visit inner loops first. Recompute induction information for this
614 // loop if the induction of any inner loop has changed.
615 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700616 induction_range_.ReVisit(node->loop_info);
617 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800618 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800619 // Note that since each simplification consists of eliminating code (without
620 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800621 do {
622 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800623 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800624 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700625 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800626 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800627 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700628 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700629 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700630 }
Aart Bik281c6812016-08-26 11:31:48 -0700631 }
Aart Bikb29f6842017-07-28 15:58:41 -0700632 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700633}
634
Aart Bikf8f5a162017-02-06 15:35:29 -0800635//
636// Optimization.
637//
638
Aart Bik281c6812016-08-26 11:31:48 -0700639void HLoopOptimization::SimplifyInduction(LoopNode* node) {
640 HBasicBlock* header = node->loop_info->GetHeader();
641 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700642 // Scan the phis in the header to find opportunities to simplify an induction
643 // cycle that is only used outside the loop. Replace these uses, if any, with
644 // the last value and remove the induction cycle.
645 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
646 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700647 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
648 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800649 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
650 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700651 // Note that it's ok to have replaced uses after the loop with the last value, without
652 // being able to remove the cycle. Environment uses (which are the reason we may not be
653 // able to remove the cycle) within the loop will still hold the right value. We must
654 // have tried first, however, to replace outside uses.
655 if (CanRemoveCycle()) {
656 simplified_ = true;
657 for (HInstruction* i : *iset_) {
658 RemoveFromCycle(i);
659 }
660 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700661 }
Aart Bik482095d2016-10-10 15:39:10 -0700662 }
663 }
664}
665
666void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800667 // Iterate over all basic blocks in the loop-body.
668 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
669 HBasicBlock* block = it.Current();
670 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800671 RemoveDeadInstructions(block->GetPhis());
672 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800673 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800674 if (block->GetPredecessors().size() == 1 &&
675 block->GetSuccessors().size() == 1 &&
676 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800677 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800678 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800679 } else if (block->GetSuccessors().size() == 2) {
680 // Trivial if block can be bypassed to either branch.
681 HBasicBlock* succ0 = block->GetSuccessors()[0];
682 HBasicBlock* succ1 = block->GetSuccessors()[1];
683 HBasicBlock* meet0 = nullptr;
684 HBasicBlock* meet1 = nullptr;
685 if (succ0 != succ1 &&
686 IsGotoBlock(succ0, &meet0) &&
687 IsGotoBlock(succ1, &meet1) &&
688 meet0 == meet1 && // meets again
689 meet0 != block && // no self-loop
690 meet0->GetPhis().IsEmpty()) { // not used for merging
691 simplified_ = true;
692 succ0->DisconnectAndDelete();
693 if (block->Dominates(meet0)) {
694 block->RemoveDominatedBlock(meet0);
695 succ1->AddDominatedBlock(meet0);
696 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700697 }
Aart Bik482095d2016-10-10 15:39:10 -0700698 }
Aart Bik281c6812016-08-26 11:31:48 -0700699 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800700 }
Aart Bik281c6812016-08-26 11:31:48 -0700701}
702
Aart Bikb29f6842017-07-28 15:58:41 -0700703bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700704 HBasicBlock* header = node->loop_info->GetHeader();
705 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700706 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800707 int64_t trip_count = 0;
708 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700709 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700710 }
Aart Bik281c6812016-08-26 11:31:48 -0700711 // Ensure there is only a single loop-body (besides the header).
712 HBasicBlock* body = nullptr;
713 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
714 if (it.Current() != header) {
715 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700716 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700717 }
718 body = it.Current();
719 }
720 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700721 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700722 // Ensure there is only a single exit point.
723 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700724 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700725 }
726 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
727 ? header->GetSuccessors()[1]
728 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700729 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700730 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700731 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700732 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800733 // Detect either an empty loop (no side effects other than plain iteration) or
734 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
735 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700736 HPhi* main_phi = nullptr;
737 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800738 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700739 if (reductions_->empty() && // TODO: possible with some effort
740 (is_empty || trip_count == 1) &&
741 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800742 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800743 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700744 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800745 preheader->MergeInstructionsWith(body);
746 }
747 body->DisconnectAndDelete();
748 exit->RemovePredecessor(header);
749 header->RemoveSuccessor(exit);
750 header->RemoveDominatedBlock(exit);
751 header->DisconnectAndDelete();
752 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800753 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800754 preheader->AddDominatedBlock(exit);
755 exit->SetDominator(preheader);
756 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700757 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800758 }
759 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800760 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700761 if (kEnableVectorization &&
762 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700763 ShouldVectorize(node, body, trip_count) &&
764 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
765 Vectorize(node, body, exit, trip_count);
766 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700767 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700768 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800769 }
Aart Bikb29f6842017-07-28 15:58:41 -0700770 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800771}
772
773//
774// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
775// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
776// Intel Press, June, 2004 (http://www.aartbik.com/).
777//
778
Aart Bik14a68b42017-06-08 14:06:58 -0700779bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800780 // Reset vector bookkeeping.
781 vector_length_ = 0;
782 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700783 vector_static_peeling_factor_ = 0;
784 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800785 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800786 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800787
788 // Phis in the loop-body prevent vectorization.
789 if (!block->GetPhis().IsEmpty()) {
790 return false;
791 }
792
793 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
794 // occurrence, which allows passing down attributes down the use tree.
795 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
796 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
797 return false; // failure to vectorize a left-hand-side
798 }
799 }
800
Aart Bik38a3f212017-10-20 17:02:21 -0700801 // Prepare alignment analysis:
802 // (1) find desired alignment (SIMD vector size in bytes).
803 // (2) initialize static loop peeling votes (peeling factor that will
804 // make one particular reference aligned), never to exceed (1).
805 // (3) variable to record how many references share same alignment.
806 // (4) variable to record suitable candidate for dynamic loop peeling.
807 uint32_t desired_alignment = GetVectorSizeInBytes();
808 DCHECK_LE(desired_alignment, 16u);
809 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
810 uint32_t max_num_same_alignment = 0;
811 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800812
813 // Data dependence analysis. Find each pair of references with same type, where
814 // at least one is a write. Each such pair denotes a possible data dependence.
815 // This analysis exploits the property that differently typed arrays cannot be
816 // aliased, as well as the property that references either point to the same
817 // array or to two completely disjoint arrays, i.e., no partial aliasing.
818 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700819 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800820 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700821 uint32_t num_same_alignment = 0;
822 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800823 for (auto j = i; ++j != vector_refs_->end(); ) {
824 if (i->type == j->type && (i->lhs || j->lhs)) {
825 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
826 HInstruction* a = i->base;
827 HInstruction* b = j->base;
828 HInstruction* x = i->offset;
829 HInstruction* y = j->offset;
830 if (a == b) {
831 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
832 // Conservatively assume a loop-carried data dependence otherwise, and reject.
833 if (x != y) {
834 return false;
835 }
Aart Bik38a3f212017-10-20 17:02:21 -0700836 // Count the number of references that have the same alignment (since
837 // base and offset are the same) and where at least one is a write, so
838 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
839 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800840 } else {
841 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
842 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
843 // generating an explicit a != b disambiguation runtime test on the two references.
844 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700845 // To avoid excessive overhead, we only accept one a != b test.
846 if (vector_runtime_test_a_ == nullptr) {
847 // First test found.
848 vector_runtime_test_a_ = a;
849 vector_runtime_test_b_ = b;
850 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
851 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
852 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800853 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800854 }
855 }
856 }
857 }
Aart Bik38a3f212017-10-20 17:02:21 -0700858 // Update information for finding suitable alignment strategy:
859 // (1) update votes for static loop peeling,
860 // (2) update suitable candidate for dynamic loop peeling.
861 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
862 if (alignment.Base() >= desired_alignment) {
863 // If the array/string object has a known, sufficient alignment, use the
864 // initial offset to compute the static loop peeling vote (this always
865 // works, since elements have natural alignment).
866 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
867 uint32_t vote = (offset == 0)
868 ? 0
869 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
870 DCHECK_LT(vote, 16u);
871 ++peeling_votes[vote];
872 } else if (BaseAlignment() >= desired_alignment &&
873 num_same_alignment > max_num_same_alignment) {
874 // Otherwise, if the array/string object has a known, sufficient alignment
875 // for just the base but with an unknown offset, record the candidate with
876 // the most occurrences for dynamic loop peeling (again, the peeling always
877 // works, since elements have natural alignment).
878 max_num_same_alignment = num_same_alignment;
879 peeling_candidate = &(*i);
880 }
881 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -0800882
Aart Bik38a3f212017-10-20 17:02:21 -0700883 // Find a suitable alignment strategy.
884 SetAlignmentStrategy(peeling_votes, peeling_candidate);
885
886 // Does vectorization seem profitable?
887 if (!IsVectorizationProfitable(trip_count)) {
888 return false;
889 }
Aart Bik14a68b42017-06-08 14:06:58 -0700890
Aart Bikf8f5a162017-02-06 15:35:29 -0800891 // Success!
892 return true;
893}
894
895void HLoopOptimization::Vectorize(LoopNode* node,
896 HBasicBlock* block,
897 HBasicBlock* exit,
898 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800899 HBasicBlock* header = node->loop_info->GetHeader();
900 HBasicBlock* preheader = node->loop_info->GetPreHeader();
901
Aart Bik14a68b42017-06-08 14:06:58 -0700902 // Pick a loop unrolling factor for the vector loop.
903 uint32_t unroll = GetUnrollingFactor(block, trip_count);
904 uint32_t chunk = vector_length_ * unroll;
905
Aart Bik38a3f212017-10-20 17:02:21 -0700906 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
907
Aart Bik14a68b42017-06-08 14:06:58 -0700908 // A cleanup loop is needed, at least, for any unknown trip count or
909 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -0700910 bool needs_cleanup = trip_count == 0 ||
911 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800912
913 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700914 HPhi* main_phi = nullptr;
915 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800916 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700917 vector_header_ = header;
918 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800919
Aart Bikdbbac8f2017-09-01 13:06:08 -0700920 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100921 DataType::Type induc_type = main_phi->GetType();
922 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
923 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700924
Aart Bik38a3f212017-10-20 17:02:21 -0700925 // Generate the trip count for static or dynamic loop peeling, if needed:
926 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -0700927 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -0700928 if (vector_static_peeling_factor_ != 0) {
929 // Static loop peeling for SIMD alignment (using the most suitable
930 // fixed peeling factor found during prior alignment analysis).
931 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
932 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
933 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
934 // Dynamic loop peeling for SIMD alignment (using the most suitable
935 // candidate found during prior alignment analysis):
936 // rem = offset % ALIGN; // adjusted as #elements
937 // ptc = rem == 0 ? 0 : (ALIGN - rem);
938 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
939 uint32_t align = GetVectorSizeInBytes() >> shift;
940 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
941 vector_dynamic_peeling_candidate_->is_string_char_at);
942 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
943 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
944 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
945 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
946 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
947 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
948 induc_type, graph_->GetConstant(induc_type, align), rem));
949 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
950 rem, graph_->GetConstant(induc_type, 0)));
951 ptc = Insert(preheader, new (global_allocator_) HSelect(
952 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
953 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -0700954 }
955
956 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800957 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -0700958 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -0700959 // vtc = stc - (stc - ptc) % chunk;
960 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800961 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
962 HInstruction* vtc = stc;
963 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700964 DCHECK(IsPowerOfTwo(chunk));
965 HInstruction* diff = stc;
966 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -0700967 if (trip_count == 0) {
968 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
969 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
970 }
Aart Bik14a68b42017-06-08 14:06:58 -0700971 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
972 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800973 HInstruction* rem = Insert(
974 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700975 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700976 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800977 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
978 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700979 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800980
981 // Generate runtime disambiguation test:
982 // vtc = a != b ? vtc : 0;
983 if (vector_runtime_test_a_ != nullptr) {
984 HInstruction* rt = Insert(
985 preheader,
986 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
987 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700988 new (global_allocator_)
989 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -0800990 needs_cleanup = true;
991 }
992
Aart Bik38a3f212017-10-20 17:02:21 -0700993 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -0700994 // for ( ; i < ptc; i += 1)
995 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -0700996 //
997 // NOTE: The alignment forced by the peeling loop is preserved even if data is
998 // moved around during suspend checks, since all analysis was based on
999 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001000 if (ptc != nullptr) {
1001 vector_mode_ = kSequential;
1002 GenerateNewLoop(node,
1003 block,
1004 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1005 vector_index_,
1006 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001007 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001008 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001009 }
1010
1011 // Generate vector loop, possibly further unrolled:
1012 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001013 // <vectorized-loop-body>
1014 vector_mode_ = kVector;
1015 GenerateNewLoop(node,
1016 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001017 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1018 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001019 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001020 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001021 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001022 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1023
1024 // Generate cleanup loop, if needed:
1025 // for ( ; i < stc; i += 1)
1026 // <loop-body>
1027 if (needs_cleanup) {
1028 vector_mode_ = kSequential;
1029 GenerateNewLoop(node,
1030 block,
1031 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001032 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001033 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001034 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001035 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001036 }
1037
Aart Bik0148de42017-09-05 09:25:01 -07001038 // Link reductions to their final uses.
1039 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1040 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001041 HInstruction* phi = i->first;
1042 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1043 // Deal with regular uses.
1044 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1045 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1046 }
1047 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001048 }
1049 }
1050
Aart Bikf8f5a162017-02-06 15:35:29 -08001051 // Remove the original loop by disconnecting the body block
1052 // and removing all instructions from the header.
1053 block->DisconnectAndDelete();
1054 while (!header->GetFirstInstruction()->IsGoto()) {
1055 header->RemoveInstruction(header->GetFirstInstruction());
1056 }
Aart Bikb29f6842017-07-28 15:58:41 -07001057
Aart Bik14a68b42017-06-08 14:06:58 -07001058 // Update loop hierarchy: the old header now resides in the same outer loop
1059 // as the old preheader. Note that we don't bother putting sequential
1060 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001061 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1062 node->loop_info = vloop;
1063}
1064
1065void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1066 HBasicBlock* block,
1067 HBasicBlock* new_preheader,
1068 HInstruction* lo,
1069 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001070 HInstruction* step,
1071 uint32_t unroll) {
1072 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001073 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001074 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001075 vector_preheader_ = new_preheader,
1076 vector_header_ = vector_preheader_->GetSingleSuccessor();
1077 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001078 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1079 kNoRegNumber,
1080 0,
1081 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001082 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001083 // for (i = lo; i < hi; i += step)
1084 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001085 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1086 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001087 vector_header_->AddInstruction(cond);
1088 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001089 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001090 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001091 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001092 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001093 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001094 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1095 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1096 DCHECK(vectorized_def);
1097 }
1098 // Generate body from the instruction map, but in original program order.
1099 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1100 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1101 auto i = vector_map_->find(it.Current());
1102 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1103 Insert(vector_body_, i->second);
1104 // Deal with instructions that need an environment, such as the scalar intrinsics.
1105 if (i->second->NeedsEnvironment()) {
1106 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1107 }
1108 }
1109 }
Aart Bik0148de42017-09-05 09:25:01 -07001110 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001111 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1112 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001113 }
Aart Bik0148de42017-09-05 09:25:01 -07001114 // Finalize phi inputs for the reductions (if any).
1115 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1116 if (!i->first->IsPhi()) {
1117 DCHECK(i->second->IsPhi());
1118 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1119 }
1120 }
Aart Bikb29f6842017-07-28 15:58:41 -07001121 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001122 phi->AddInput(lo);
1123 phi->AddInput(vector_index_);
1124 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001125}
1126
Aart Bikf8f5a162017-02-06 15:35:29 -08001127bool HLoopOptimization::VectorizeDef(LoopNode* node,
1128 HInstruction* instruction,
1129 bool generate_code) {
1130 // Accept a left-hand-side array base[index] for
1131 // (1) supported vector type,
1132 // (2) loop-invariant base,
1133 // (3) unit stride index,
1134 // (4) vectorizable right-hand-side value.
1135 uint64_t restrictions = kNone;
1136 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001137 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001138 HInstruction* base = instruction->InputAt(0);
1139 HInstruction* index = instruction->InputAt(1);
1140 HInstruction* value = instruction->InputAt(2);
1141 HInstruction* offset = nullptr;
1142 if (TrySetVectorType(type, &restrictions) &&
1143 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001144 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001145 VectorizeUse(node, value, generate_code, type, restrictions)) {
1146 if (generate_code) {
1147 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001148 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001149 } else {
1150 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1151 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001152 return true;
1153 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001154 return false;
1155 }
Aart Bik0148de42017-09-05 09:25:01 -07001156 // Accept a left-hand-side reduction for
1157 // (1) supported vector type,
1158 // (2) vectorizable right-hand-side value.
1159 auto redit = reductions_->find(instruction);
1160 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001161 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001162 // Recognize SAD idiom or direct reduction.
1163 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1164 (TrySetVectorType(type, &restrictions) &&
1165 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001166 if (generate_code) {
1167 HInstruction* new_red = vector_map_->Get(instruction);
1168 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1169 vector_permanent_map_->Overwrite(redit->second, new_red);
1170 }
1171 return true;
1172 }
1173 return false;
1174 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001175 // Branch back okay.
1176 if (instruction->IsGoto()) {
1177 return true;
1178 }
1179 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1180 // Note that actual uses are inspected during right-hand-side tree traversal.
1181 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1182}
1183
Aart Bikf8f5a162017-02-06 15:35:29 -08001184bool HLoopOptimization::VectorizeUse(LoopNode* node,
1185 HInstruction* instruction,
1186 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001187 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001188 uint64_t restrictions) {
1189 // Accept anything for which code has already been generated.
1190 if (generate_code) {
1191 if (vector_map_->find(instruction) != vector_map_->end()) {
1192 return true;
1193 }
1194 }
1195 // Continue the right-hand-side tree traversal, passing in proper
1196 // types and vector restrictions along the way. During code generation,
1197 // all new nodes are drawn from the global allocator.
1198 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1199 // Accept invariant use, using scalar expansion.
1200 if (generate_code) {
1201 GenerateVecInv(instruction, type);
1202 }
1203 return true;
1204 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001205 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001206 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1207 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001208 return false;
1209 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001210 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001211 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001212 // (2) loop-invariant base,
1213 // (3) unit stride index,
1214 // (4) vectorizable right-hand-side value.
1215 HInstruction* base = instruction->InputAt(0);
1216 HInstruction* index = instruction->InputAt(1);
1217 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001218 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001219 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001220 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001221 if (generate_code) {
1222 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001223 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001224 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001225 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001226 }
1227 return true;
1228 }
Aart Bik0148de42017-09-05 09:25:01 -07001229 } else if (instruction->IsPhi()) {
1230 // Accept particular phi operations.
1231 if (reductions_->find(instruction) != reductions_->end()) {
1232 // Deal with vector restrictions.
1233 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1234 return false;
1235 }
1236 // Accept a reduction.
1237 if (generate_code) {
1238 GenerateVecReductionPhi(instruction->AsPhi());
1239 }
1240 return true;
1241 }
1242 // TODO: accept right-hand-side induction?
1243 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001244 } else if (instruction->IsTypeConversion()) {
1245 // Accept particular type conversions.
1246 HTypeConversion* conversion = instruction->AsTypeConversion();
1247 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001248 DataType::Type from = conversion->GetInputType();
1249 DataType::Type to = conversion->GetResultType();
1250 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001251 uint32_t size_vec = DataType::Size(type);
1252 uint32_t size_from = DataType::Size(from);
1253 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001254 // Accept an integral conversion
1255 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1256 // (1b) widening from at least vector type, and
1257 // (2) vectorizable operand.
1258 if ((size_to < size_from &&
1259 size_to == size_vec &&
1260 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1261 (size_to >= size_from &&
1262 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001263 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001264 if (generate_code) {
1265 if (vector_mode_ == kVector) {
1266 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1267 } else {
1268 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1269 }
1270 }
1271 return true;
1272 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001273 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001274 DCHECK_EQ(to, type);
1275 // Accept int to float conversion for
1276 // (1) supported int,
1277 // (2) vectorizable operand.
1278 if (TrySetVectorType(from, &restrictions) &&
1279 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1280 if (generate_code) {
1281 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1282 }
1283 return true;
1284 }
1285 }
1286 return false;
1287 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1288 // Accept unary operator for vectorizable operand.
1289 HInstruction* opa = instruction->InputAt(0);
1290 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1291 if (generate_code) {
1292 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1293 }
1294 return true;
1295 }
1296 } else if (instruction->IsAdd() || instruction->IsSub() ||
1297 instruction->IsMul() || instruction->IsDiv() ||
1298 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1299 // Deal with vector restrictions.
1300 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1301 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1302 return false;
1303 }
1304 // Accept binary operator for vectorizable operands.
1305 HInstruction* opa = instruction->InputAt(0);
1306 HInstruction* opb = instruction->InputAt(1);
1307 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1308 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1309 if (generate_code) {
1310 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1311 }
1312 return true;
1313 }
1314 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001315 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001316 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1317 return true;
1318 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001319 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001320 HInstruction* opa = instruction->InputAt(0);
1321 HInstruction* opb = instruction->InputAt(1);
1322 HInstruction* r = opa;
1323 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001324 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1325 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1326 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001327 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1328 // Shifts right need extra care to account for higher order bits.
1329 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1330 if (instruction->IsShr() &&
1331 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1332 return false; // reject, unless all operands are sign-extension narrower
1333 } else if (instruction->IsUShr() &&
1334 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1335 return false; // reject, unless all operands are zero-extension narrower
1336 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001337 }
1338 // Accept shift operator for vectorizable/invariant operands.
1339 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001340 DCHECK(r != nullptr);
1341 if (generate_code && vector_mode_ != kVector) { // de-idiom
1342 r = opa;
1343 }
Aart Bik50e20d52017-05-05 14:07:29 -07001344 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001345 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001346 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001347 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001348 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001349 if (0 <= distance && distance < max_distance) {
1350 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001351 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001352 }
1353 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001354 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001355 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001356 } else if (instruction->IsAbs()) {
1357 // Deal with vector restrictions.
1358 HInstruction* opa = instruction->InputAt(0);
1359 HInstruction* r = opa;
1360 bool is_unsigned = false;
1361 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1362 return false;
1363 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1364 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1365 return false; // reject, unless operand is sign-extension narrower
1366 }
1367 // Accept ABS(x) for vectorizable operand.
1368 DCHECK(r != nullptr);
1369 if (generate_code && vector_mode_ != kVector) { // de-idiom
1370 r = opa;
1371 }
1372 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1373 if (generate_code) {
1374 GenerateVecOp(instruction,
1375 vector_map_->Get(r),
1376 nullptr,
1377 HVecOperation::ToProperType(type, is_unsigned));
1378 }
1379 return true;
1380 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001381 } else if (instruction->IsMin() || instruction->IsMax()) {
Aart Bik29aa0822018-03-08 11:28:00 -08001382 // Recognize saturation arithmetic.
1383 if (VectorizeSaturationIdiom(node, instruction, generate_code, type, restrictions)) {
1384 return true;
1385 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001386 // Deal with vector restrictions.
1387 HInstruction* opa = instruction->InputAt(0);
1388 HInstruction* opb = instruction->InputAt(1);
1389 HInstruction* r = opa;
1390 HInstruction* s = opb;
1391 bool is_unsigned = false;
1392 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1393 return false;
1394 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1395 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1396 return false; // reject, unless all operands are same-extension narrower
1397 }
1398 // Accept MIN/MAX(x, y) for vectorizable operands.
1399 DCHECK(r != nullptr);
1400 DCHECK(s != nullptr);
1401 if (generate_code && vector_mode_ != kVector) { // de-idiom
1402 r = opa;
1403 s = opb;
1404 }
1405 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1406 VectorizeUse(node, s, generate_code, type, restrictions)) {
1407 if (generate_code) {
1408 GenerateVecOp(
1409 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001410 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001411 return true;
1412 }
Aart Bik281c6812016-08-26 11:31:48 -07001413 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001414 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001415}
1416
Aart Bik38a3f212017-10-20 17:02:21 -07001417uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1418 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001419 case InstructionSet::kArm:
1420 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001421 return 8; // 64-bit SIMD
1422 default:
1423 return 16; // 128-bit SIMD
1424 }
1425}
1426
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001427bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001428 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1429 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001430 case InstructionSet::kArm:
1431 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001432 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001433 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001434 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001435 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001436 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001437 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001438 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001439 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001440 case DataType::Type::kUint16:
1441 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001442 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001443 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001444 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001445 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001446 return TrySetVectorLength(2);
1447 default:
1448 break;
1449 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001450 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001451 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001452 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001453 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001454 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001455 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001456 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001457 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001458 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001459 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001460 case DataType::Type::kUint16:
1461 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001462 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001463 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001464 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001465 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001466 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001467 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001468 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001469 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001470 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001471 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001472 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001473 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001474 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001475 return TrySetVectorLength(2);
1476 default:
1477 return false;
1478 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001479 case InstructionSet::kX86:
1480 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001481 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001482 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1483 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001484 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001485 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001486 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001487 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001488 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001489 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001490 case DataType::Type::kUint16:
1491 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001492 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001493 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001494 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001495 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001496 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001497 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001498 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001499 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001500 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001501 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001502 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001503 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001504 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001505 return TrySetVectorLength(2);
1506 default:
1507 break;
1508 } // switch type
1509 }
1510 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001511 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001512 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1513 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001514 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001515 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001516 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001517 *restrictions |= kNoDiv | kNoSaturation;
Lena Djokic51765b02017-06-22 13:49:59 +02001518 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001519 case DataType::Type::kUint16:
1520 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001521 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001522 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001523 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001524 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001525 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001526 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001527 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001528 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001529 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001530 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001531 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001532 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001533 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001534 return TrySetVectorLength(2);
1535 default:
1536 break;
1537 } // switch type
1538 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001539 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001540 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001541 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1542 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001543 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001544 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001545 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001546 *restrictions |= kNoDiv | kNoSaturation;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001547 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001548 case DataType::Type::kUint16:
1549 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001550 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001551 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001552 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001553 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001554 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001555 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001556 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001557 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001558 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001559 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001560 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001561 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001562 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001563 return TrySetVectorLength(2);
1564 default:
1565 break;
1566 } // switch type
1567 }
1568 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001569 default:
1570 return false;
1571 } // switch instruction set
1572}
1573
1574bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1575 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1576 // First time set?
1577 if (vector_length_ == 0) {
1578 vector_length_ = length;
1579 }
1580 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1581 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1582 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1583 return vector_length_ == length;
1584}
1585
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001586void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001587 if (vector_map_->find(org) == vector_map_->end()) {
1588 // In scalar code, just use a self pass-through for scalar invariants
1589 // (viz. expression remains itself).
1590 if (vector_mode_ == kSequential) {
1591 vector_map_->Put(org, org);
1592 return;
1593 }
1594 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001595 HInstruction* vector = nullptr;
1596 auto it = vector_permanent_map_->find(org);
1597 if (it != vector_permanent_map_->end()) {
1598 vector = it->second; // reuse during unrolling
1599 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001600 // Generates ReplicateScalar( (optional_type_conv) org ).
1601 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001602 DataType::Type input_type = input->GetType();
1603 if (type != input_type && (type == DataType::Type::kInt64 ||
1604 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001605 input = Insert(vector_preheader_,
1606 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1607 }
1608 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001609 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001610 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1611 }
1612 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001613 }
1614}
1615
1616void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1617 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001618 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001619 int64_t value = 0;
1620 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001621 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001622 if (org->IsPhi()) {
1623 Insert(vector_body_, subscript); // lacks layout placeholder
1624 }
1625 }
1626 vector_map_->Put(org, subscript);
1627 }
1628}
1629
1630void HLoopOptimization::GenerateVecMem(HInstruction* org,
1631 HInstruction* opa,
1632 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001633 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001634 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001635 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001636 HInstruction* vector = nullptr;
1637 if (vector_mode_ == kVector) {
1638 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001639 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001640 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001641 if (opb != nullptr) {
1642 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001643 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001644 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001645 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001646 vector = new (global_allocator_) HVecLoad(global_allocator_,
1647 base,
1648 opa,
1649 type,
1650 org->GetSideEffects(),
1651 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001652 is_string_char_at,
1653 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001654 }
Aart Bik38a3f212017-10-20 17:02:21 -07001655 // Known (forced/adjusted/original) alignment?
1656 if (vector_dynamic_peeling_candidate_ != nullptr) {
1657 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1658 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1659 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1660 vector->AsVecMemoryOperation()->SetAlignment( // forced
1661 Alignment(GetVectorSizeInBytes(), 0));
1662 }
1663 } else {
1664 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1665 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001666 }
1667 } else {
1668 // Scalar store or load.
1669 DCHECK(vector_mode_ == kSequential);
1670 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001671 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001672 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001673 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001674 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001675 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1676 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001677 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001678 }
1679 }
1680 vector_map_->Put(org, vector);
1681}
1682
Aart Bik0148de42017-09-05 09:25:01 -07001683void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1684 DCHECK(reductions_->find(phi) != reductions_->end());
1685 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1686 HInstruction* vector = nullptr;
1687 if (vector_mode_ == kSequential) {
1688 HPhi* new_phi = new (global_allocator_) HPhi(
1689 global_allocator_, kNoRegNumber, 0, phi->GetType());
1690 vector_header_->AddPhi(new_phi);
1691 vector = new_phi;
1692 } else {
1693 // Link vector reduction back to prior unrolled update, or a first phi.
1694 auto it = vector_permanent_map_->find(phi);
1695 if (it != vector_permanent_map_->end()) {
1696 vector = it->second;
1697 } else {
1698 HPhi* new_phi = new (global_allocator_) HPhi(
1699 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1700 vector_header_->AddPhi(new_phi);
1701 vector = new_phi;
1702 }
1703 }
1704 vector_map_->Put(phi, vector);
1705}
1706
1707void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1708 HInstruction* new_phi = vector_map_->Get(phi);
1709 HInstruction* new_init = reductions_->Get(phi);
1710 HInstruction* new_red = vector_map_->Get(reduction);
1711 // Link unrolled vector loop back to new phi.
1712 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1713 DCHECK(new_phi->IsVecOperation());
1714 }
1715 // Prepare the new initialization.
1716 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001717 // Generate a [initial, 0, .., 0] vector for add or
1718 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001719 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001720 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001721 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001722 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001723 if (kind == HVecReduce::ReductionKind::kSum) {
1724 new_init = Insert(vector_preheader_,
1725 new (global_allocator_) HVecSetScalars(global_allocator_,
1726 &new_init,
1727 type,
1728 vector_length,
1729 1,
1730 kNoDexPc));
1731 } else {
1732 new_init = Insert(vector_preheader_,
1733 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1734 new_init,
1735 type,
1736 vector_length,
1737 kNoDexPc));
1738 }
Aart Bik0148de42017-09-05 09:25:01 -07001739 } else {
1740 new_init = ReduceAndExtractIfNeeded(new_init);
1741 }
1742 // Set the phi inputs.
1743 DCHECK(new_phi->IsPhi());
1744 new_phi->AsPhi()->AddInput(new_init);
1745 new_phi->AsPhi()->AddInput(new_red);
1746 // New feed value for next phi (safe mutation in iteration).
1747 reductions_->find(phi)->second = new_phi;
1748}
1749
1750HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1751 if (instruction->IsPhi()) {
1752 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001753 if (HVecOperation::ReturnsSIMDValue(input)) {
1754 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001755 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001756 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001757 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001758 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001759 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1760 // Generate a vector reduction and scalar extract
1761 // x = REDUCE( [x_1, .., x_n] )
1762 // y = x_1
1763 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001764 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001765 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001766 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1767 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001768 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001769 exit->InsertInstructionAfter(instruction, reduce);
1770 }
1771 }
1772 return instruction;
1773}
1774
Aart Bikf8f5a162017-02-06 15:35:29 -08001775#define GENERATE_VEC(x, y) \
1776 if (vector_mode_ == kVector) { \
1777 vector = (x); \
1778 } else { \
1779 DCHECK(vector_mode_ == kSequential); \
1780 vector = (y); \
1781 } \
1782 break;
1783
1784void HLoopOptimization::GenerateVecOp(HInstruction* org,
1785 HInstruction* opa,
1786 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001787 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001788 bool is_unsigned) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001789 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001790 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001791 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001792 switch (org->GetKind()) {
1793 case HInstruction::kNeg:
1794 DCHECK(opb == nullptr);
1795 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001796 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1797 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001798 case HInstruction::kNot:
1799 DCHECK(opb == nullptr);
1800 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001801 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1802 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001803 case HInstruction::kBooleanNot:
1804 DCHECK(opb == nullptr);
1805 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001806 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1807 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001808 case HInstruction::kTypeConversion:
1809 DCHECK(opb == nullptr);
1810 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001811 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1812 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001813 case HInstruction::kAdd:
1814 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001815 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1816 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001817 case HInstruction::kSub:
1818 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001819 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1820 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001821 case HInstruction::kMul:
1822 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001823 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1824 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001825 case HInstruction::kDiv:
1826 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001827 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1828 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001829 case HInstruction::kAnd:
1830 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001831 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1832 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001833 case HInstruction::kOr:
1834 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001835 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1836 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001837 case HInstruction::kXor:
1838 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001839 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1840 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001841 case HInstruction::kShl:
1842 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001843 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1844 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001845 case HInstruction::kShr:
1846 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001847 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1848 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001849 case HInstruction::kUShr:
1850 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001851 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1852 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik1f8d51b2018-02-15 10:42:37 -08001853 case HInstruction::kMin:
1854 GENERATE_VEC(
1855 new (global_allocator_) HVecMin(global_allocator_,
1856 opa,
1857 opb,
1858 HVecOperation::ToProperType(type, is_unsigned),
1859 vector_length_,
1860 dex_pc),
1861 new (global_allocator_) HMin(org_type, opa, opb, dex_pc));
1862 case HInstruction::kMax:
1863 GENERATE_VEC(
1864 new (global_allocator_) HVecMax(global_allocator_,
1865 opa,
1866 opb,
1867 HVecOperation::ToProperType(type, is_unsigned),
1868 vector_length_,
1869 dex_pc),
1870 new (global_allocator_) HMax(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001871 case HInstruction::kAbs:
1872 DCHECK(opb == nullptr);
1873 GENERATE_VEC(
1874 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1875 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001876 default:
1877 break;
1878 } // switch
1879 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1880 vector_map_->Put(org, vector);
1881}
1882
1883#undef GENERATE_VEC
1884
1885//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001886// Vectorization idioms.
1887//
1888
Aart Bik29aa0822018-03-08 11:28:00 -08001889// Method recognizes single and double clipping saturation arithmetic.
1890bool HLoopOptimization::VectorizeSaturationIdiom(LoopNode* node,
1891 HInstruction* instruction,
1892 bool generate_code,
1893 DataType::Type type,
1894 uint64_t restrictions) {
1895 // Deal with vector restrictions.
1896 if (HasVectorRestrictions(restrictions, kNoSaturation)) {
1897 return false;
1898 }
1899 // Search for clipping of a clippee.
1900 int64_t lo = kNoLo;
1901 int64_t hi = kNoHi;
1902 HInstruction* clippee = nullptr;
1903 if (!IsClipped(instruction, &lo, &hi, &clippee)) {
1904 return false;
1905 }
1906 CHECK(clippee != nullptr);
1907 // Clipped addition or subtraction?
1908 bool is_add = true;
1909 if (clippee->IsAdd()) {
1910 is_add = true;
1911 } else if (clippee->IsSub()) {
1912 is_add = false;
1913 } else {
1914 return false; // clippee is not add/sub
1915 }
1916 // Addition or subtraction on narrower operands?
1917 HInstruction* r = nullptr;
1918 HInstruction* s = nullptr;
1919 bool is_unsigned = false;
1920 if (IsNarrowerOperands(clippee->InputAt(0), clippee->InputAt(1), type, &r, &s, &is_unsigned) &&
1921 (is_add ? IsSaturatedAdd(type, lo, hi, is_unsigned)
1922 : IsSaturatedSub(type, lo, hi, is_unsigned))) {
1923 DCHECK(r != nullptr);
1924 DCHECK(s != nullptr);
1925 } else {
1926 return false;
1927 }
1928 // Accept saturation idiom for vectorizable operands.
1929 if (generate_code && vector_mode_ != kVector) { // de-idiom
1930 r = instruction->InputAt(0);
1931 s = instruction->InputAt(1);
1932 restrictions &= ~(kNoHiBits | kNoMinMax); // allow narrow MIN/MAX in seq
1933 }
1934 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1935 VectorizeUse(node, s, generate_code, type, restrictions)) {
1936 if (generate_code) {
1937 if (vector_mode_ == kVector) {
1938 DataType::Type vtype = HVecOperation::ToProperType(type, is_unsigned);
1939 HInstruction* op1 = vector_map_->Get(r);
1940 HInstruction* op2 = vector_map_->Get(s);
1941 vector_map_->Put(instruction, is_add
1942 ? reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationAdd(
1943 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc))
1944 : reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationSub(
1945 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc)));
1946 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
1947 } else {
1948 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
1949 }
1950 }
1951 return true;
1952 }
1953 return false;
1954}
1955
Aart Bikf3e61ee2017-04-12 17:09:20 -07001956// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001957// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1958// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001959// Provided that the operands are promoted to a wider form to do the arithmetic and
1960// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1961// implementation that operates directly in narrower form (plus one extra bit).
1962// TODO: current version recognizes implicit byte/short/char widening only;
1963// explicit widening from int to long could be added later.
1964bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1965 HInstruction* instruction,
1966 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001967 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001968 uint64_t restrictions) {
1969 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001970 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001971 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001972 if ((instruction->IsShr() ||
1973 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001974 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001975 // Test for (a + b + c) >> 1 for optional constant c.
1976 HInstruction* a = nullptr;
1977 HInstruction* b = nullptr;
1978 int64_t c = 0;
1979 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001980 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001981 // Accept c == 1 (rounded) or c == 0 (not rounded).
1982 bool is_rounded = false;
1983 if (c == 1) {
1984 is_rounded = true;
1985 } else if (c != 0) {
1986 return false;
1987 }
1988 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001989 HInstruction* r = nullptr;
1990 HInstruction* s = nullptr;
1991 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001992 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001993 return false;
1994 }
1995 // Deal with vector restrictions.
1996 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1997 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1998 return false;
1999 }
2000 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2001 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002002 DCHECK(r != nullptr);
2003 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002004 if (generate_code && vector_mode_ != kVector) { // de-idiom
2005 r = instruction->InputAt(0);
2006 s = instruction->InputAt(1);
2007 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002008 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2009 VectorizeUse(node, s, generate_code, type, restrictions)) {
2010 if (generate_code) {
2011 if (vector_mode_ == kVector) {
2012 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2013 global_allocator_,
2014 vector_map_->Get(r),
2015 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002016 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002017 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002018 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002019 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002020 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002021 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002022 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002023 }
2024 }
2025 return true;
2026 }
2027 }
2028 }
2029 return false;
2030}
2031
Aart Bikdbbac8f2017-09-01 13:06:08 -07002032// Method recognizes the following idiom:
2033// q += ABS(a - b) for signed operands a, b
2034// Provided that the operands have the same type or are promoted to a wider form.
2035// Since this may involve a vector length change, the idiom is handled by going directly
2036// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2037// TODO: unsigned SAD too?
2038bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2039 HInstruction* instruction,
2040 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002041 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002042 uint64_t restrictions) {
2043 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2044 // are done in the same precision (either int or long).
2045 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002046 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002047 return false;
2048 }
2049 HInstruction* q = instruction->InputAt(0);
2050 HInstruction* v = instruction->InputAt(1);
2051 HInstruction* a = nullptr;
2052 HInstruction* b = nullptr;
Aart Bik3b2a5952018-03-05 13:55:28 -08002053 if (v->GetType() == reduction_type && v->IsAbs()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002054 HInstruction* x = v->InputAt(0);
Aart Bikdf011c32017-09-28 12:53:04 -07002055 if (x->GetType() == reduction_type) {
2056 int64_t c = 0;
2057 if (x->IsSub()) {
2058 a = x->InputAt(0);
2059 b = x->InputAt(1);
2060 } else if (IsAddConst(x, /*out*/ &a, /*out*/ &c)) {
2061 b = graph_->GetConstant(reduction_type, -c); // hidden SUB!
2062 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07002063 }
2064 }
2065 if (a == nullptr || b == nullptr) {
2066 return false;
2067 }
2068 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2069 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002070 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002071 HInstruction* r = a;
2072 HInstruction* s = b;
2073 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002074 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002075 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2076 sub_type = b->GetType();
2077 }
2078 if (a->IsTypeConversion() &&
2079 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2080 sub_type = a->InputAt(0)->GetType();
2081 }
2082 if (b->IsTypeConversion() &&
2083 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2084 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002085 }
2086 if (reduction_type != sub_type &&
2087 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2088 return false;
2089 }
2090 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002091 if (!TrySetVectorType(sub_type, &restrictions) ||
2092 HasVectorRestrictions(restrictions, kNoSAD) ||
2093 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002094 return false;
2095 }
2096 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2097 // idiomatic operation. Sequential code uses the original scalar expressions.
2098 DCHECK(r != nullptr);
2099 DCHECK(s != nullptr);
2100 if (generate_code && vector_mode_ != kVector) { // de-idiom
2101 r = s = v->InputAt(0);
2102 }
2103 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2104 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2105 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2106 if (generate_code) {
2107 if (vector_mode_ == kVector) {
2108 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2109 global_allocator_,
2110 vector_map_->Get(q),
2111 vector_map_->Get(r),
2112 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002113 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002114 GetOtherVL(reduction_type, sub_type, vector_length_),
2115 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002116 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2117 } else {
2118 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2119 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2120 }
2121 }
2122 return true;
2123 }
2124 return false;
2125}
2126
Aart Bikf3e61ee2017-04-12 17:09:20 -07002127//
Aart Bik14a68b42017-06-08 14:06:58 -07002128// Vectorization heuristics.
2129//
2130
Aart Bik38a3f212017-10-20 17:02:21 -07002131Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2132 DataType::Type type,
2133 bool is_string_char_at,
2134 uint32_t peeling) {
2135 // Combine the alignment and hidden offset that is guaranteed by
2136 // the Android runtime with a known starting index adjusted as bytes.
2137 int64_t value = 0;
2138 if (IsInt64AndGet(offset, /*out*/ &value)) {
2139 uint32_t start_offset =
2140 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2141 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2142 }
2143 // Otherwise, the Android runtime guarantees at least natural alignment.
2144 return Alignment(DataType::Size(type), 0);
2145}
2146
2147void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2148 const ArrayReference* peeling_candidate) {
2149 // Current heuristic: pick the best static loop peeling factor, if any,
2150 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2151 uint32_t max_vote = 0;
2152 for (int32_t i = 0; i < 16; i++) {
2153 if (peeling_votes[i] > max_vote) {
2154 max_vote = peeling_votes[i];
2155 vector_static_peeling_factor_ = i;
2156 }
2157 }
2158 if (max_vote == 0) {
2159 vector_dynamic_peeling_candidate_ = peeling_candidate;
2160 }
2161}
2162
2163uint32_t HLoopOptimization::MaxNumberPeeled() {
2164 if (vector_dynamic_peeling_candidate_ != nullptr) {
2165 return vector_length_ - 1u; // worst-case
2166 }
2167 return vector_static_peeling_factor_; // known exactly
2168}
2169
Aart Bik14a68b42017-06-08 14:06:58 -07002170bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002171 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002172 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002173 // TODO: trip count is really unsigned entity, provided the guarding test
2174 // is satisfied; deal with this more carefully later
2175 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002176 if (vector_length_ == 0) {
2177 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002178 } else if (trip_count < 0) {
2179 return false; // guard against non-taken/large
2180 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002181 return false; // insufficient iterations
2182 }
2183 return true;
2184}
2185
Artem Serovf26bb6c2017-09-01 10:59:03 +01002186static constexpr uint32_t ARM64_SIMD_MAXIMUM_UNROLL_FACTOR = 8;
2187static constexpr uint32_t ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE = 50;
2188
Aart Bik14a68b42017-06-08 14:06:58 -07002189uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002190 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002191 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00002192 case InstructionSet::kArm64: {
Aart Bik521b50f2017-09-09 10:44:45 -07002193 // Don't unroll with insufficient iterations.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002194 // TODO: Unroll loops with unknown trip count.
Aart Bik521b50f2017-09-09 10:44:45 -07002195 DCHECK_NE(vector_length_, 0u);
Aart Bik38a3f212017-10-20 17:02:21 -07002196 if (trip_count < (2 * vector_length_ + max_peel)) {
Aart Bik521b50f2017-09-09 10:44:45 -07002197 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002198 }
Aart Bik521b50f2017-09-09 10:44:45 -07002199 // Don't unroll for large loop body size.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002200 uint32_t instruction_count = block->GetInstructions().CountSize();
Aart Bik521b50f2017-09-09 10:44:45 -07002201 if (instruction_count >= ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE) {
2202 return kNoUnrollingFactor;
2203 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002204 // Find a beneficial unroll factor with the following restrictions:
2205 // - At least one iteration of the transformed loop should be executed.
2206 // - The loop body shouldn't be "too big" (heuristic).
2207 uint32_t uf1 = ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE / instruction_count;
Aart Bik38a3f212017-10-20 17:02:21 -07002208 uint32_t uf2 = (trip_count - max_peel) / vector_length_;
Artem Serovf26bb6c2017-09-01 10:59:03 +01002209 uint32_t unroll_factor =
2210 TruncToPowerOfTwo(std::min({uf1, uf2, ARM64_SIMD_MAXIMUM_UNROLL_FACTOR}));
2211 DCHECK_GE(unroll_factor, 1u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002212 return unroll_factor;
Aart Bik14a68b42017-06-08 14:06:58 -07002213 }
Vladimir Marko33bff252017-11-01 14:35:42 +00002214 case InstructionSet::kX86:
2215 case InstructionSet::kX86_64:
Aart Bik14a68b42017-06-08 14:06:58 -07002216 default:
Aart Bik521b50f2017-09-09 10:44:45 -07002217 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002218 }
2219}
2220
2221//
Aart Bikf8f5a162017-02-06 15:35:29 -08002222// Helpers.
2223//
2224
2225bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002226 // Start with empty phi induction.
2227 iset_->clear();
2228
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002229 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2230 // smart enough to follow strongly connected components (and it's probably not worth
2231 // it to make it so). See b/33775412.
2232 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2233 return false;
2234 }
Aart Bikb29f6842017-07-28 15:58:41 -07002235
2236 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002237 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2238 if (set != nullptr) {
2239 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002240 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002241 // each instruction is removable and, when restrict uses are requested, other than for phi,
2242 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002243 if (!i->IsInBlock()) {
2244 continue;
2245 } else if (!i->IsRemovable()) {
2246 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002247 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002248 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002249 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2250 if (set->find(use.GetUser()) == set->end()) {
2251 return false;
2252 }
2253 }
2254 }
Aart Bike3dedc52016-11-02 17:50:27 -07002255 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002256 }
Aart Bikcc42be02016-10-20 16:14:16 -07002257 return true;
2258 }
2259 return false;
2260}
2261
Aart Bikb29f6842017-07-28 15:58:41 -07002262bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002263 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002264 // Only unclassified phi cycles are candidates for reductions.
2265 if (induction_range_.IsClassified(phi)) {
2266 return false;
2267 }
2268 // Accept operations like x = x + .., provided that the phi and the reduction are
2269 // used exactly once inside the loop, and by each other.
2270 HInputsRef inputs = phi->GetInputs();
2271 if (inputs.size() == 2) {
2272 HInstruction* reduction = inputs[1];
2273 if (HasReductionFormat(reduction, phi)) {
2274 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002275 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002276 bool single_use_inside_loop =
2277 // Reduction update only used by phi.
2278 reduction->GetUses().HasExactlyOneElement() &&
2279 !reduction->HasEnvironmentUses() &&
2280 // Reduction update is only use of phi inside the loop.
2281 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2282 iset_->size() == 1;
2283 iset_->clear(); // leave the way you found it
2284 if (single_use_inside_loop) {
2285 // Link reduction back, and start recording feed value.
2286 reductions_->Put(reduction, phi);
2287 reductions_->Put(phi, phi->InputAt(0));
2288 return true;
2289 }
2290 }
2291 }
2292 return false;
2293}
2294
2295bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2296 // Start with empty phi induction and reductions.
2297 iset_->clear();
2298 reductions_->clear();
2299
2300 // Scan the phis to find the following (the induction structure has already
2301 // been optimized, so we don't need to worry about trivial cases):
2302 // (1) optional reductions in loop,
2303 // (2) the main induction, used in loop control.
2304 HPhi* phi = nullptr;
2305 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2306 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2307 continue;
2308 } else if (phi == nullptr) {
2309 // Found the first candidate for main induction.
2310 phi = it.Current()->AsPhi();
2311 } else {
2312 return false;
2313 }
2314 }
2315
2316 // Then test for a typical loopheader:
2317 // s: SuspendCheck
2318 // c: Condition(phi, bound)
2319 // i: If(c)
2320 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002321 HInstruction* s = block->GetFirstInstruction();
2322 if (s != nullptr && s->IsSuspendCheck()) {
2323 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002324 if (c != nullptr &&
2325 c->IsCondition() &&
2326 c->GetUses().HasExactlyOneElement() && // only used for termination
2327 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002328 HInstruction* i = c->GetNext();
2329 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2330 iset_->insert(c);
2331 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002332 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002333 return true;
2334 }
2335 }
2336 }
2337 }
2338 return false;
2339}
2340
2341bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002342 if (!block->GetPhis().IsEmpty()) {
2343 return false;
2344 }
2345 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2346 HInstruction* instruction = it.Current();
2347 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2348 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002349 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002350 }
2351 return true;
2352}
2353
2354bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2355 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002356 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002357 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2358 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2359 return true;
2360 }
Aart Bikcc42be02016-10-20 16:14:16 -07002361 }
2362 return false;
2363}
2364
Aart Bik482095d2016-10-10 15:39:10 -07002365bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002366 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002367 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002368 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002369 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002370 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2371 HInstruction* user = use.GetUser();
2372 if (iset_->find(user) == iset_->end()) { // not excluded?
2373 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002374 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002375 // If collect_loop_uses is set, simply keep adding those uses to the set.
2376 // Otherwise, reject uses inside the loop that were not already in the set.
2377 if (collect_loop_uses) {
2378 iset_->insert(user);
2379 continue;
2380 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002381 return false;
2382 }
2383 ++*use_count;
2384 }
2385 }
2386 return true;
2387}
2388
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002389bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2390 HInstruction* instruction,
2391 HBasicBlock* block) {
2392 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002393 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002394 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002395 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002396 const HUseList<HInstruction*>& uses = instruction->GetUses();
2397 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2398 HInstruction* user = it->GetUser();
2399 size_t index = it->GetIndex();
2400 ++it; // increment before replacing
2401 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002402 if (kIsDebugBuild) {
2403 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2404 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2405 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2406 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002407 user->ReplaceInput(replacement, index);
2408 induction_range_.Replace(user, instruction, replacement); // update induction
2409 }
2410 }
Aart Bikb29f6842017-07-28 15:58:41 -07002411 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002412 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2413 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2414 HEnvironment* user = it->GetUser();
2415 size_t index = it->GetIndex();
2416 ++it; // increment before replacing
2417 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002418 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002419 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002420 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2421 user->RemoveAsUserOfInput(index);
2422 user->SetRawEnvAt(index, replacement);
2423 replacement->AddEnvUseAt(user, index);
2424 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002425 }
2426 }
Aart Bik807868e2016-11-03 17:51:43 -07002427 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002428 }
Aart Bik807868e2016-11-03 17:51:43 -07002429 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002430}
2431
Aart Bikf8f5a162017-02-06 15:35:29 -08002432bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2433 HInstruction* instruction,
2434 HBasicBlock* block,
2435 bool collect_loop_uses) {
2436 // Assigning the last value is always successful if there are no uses.
2437 // Otherwise, it succeeds in a no early-exit loop by generating the
2438 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002439 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002440 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2441 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002442 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002443}
2444
Aart Bik6b69e0a2017-01-11 10:20:43 -08002445void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2446 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2447 HInstruction* instruction = i.Current();
2448 if (instruction->IsDeadAndRemovable()) {
2449 simplified_ = true;
2450 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2451 }
2452 }
2453}
2454
Aart Bik14a68b42017-06-08 14:06:58 -07002455bool HLoopOptimization::CanRemoveCycle() {
2456 for (HInstruction* i : *iset_) {
2457 // We can never remove instructions that have environment
2458 // uses when we compile 'debuggable'.
2459 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2460 return false;
2461 }
2462 // A deoptimization should never have an environment input removed.
2463 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2464 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2465 return false;
2466 }
2467 }
2468 }
2469 return true;
2470}
2471
Aart Bik281c6812016-08-26 11:31:48 -07002472} // namespace art