blob: e1fb7ac17e0ad8a453db40144f394c0228e2d1fd [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 Bik38a3f212017-10-20 17:02:21 -070039//
40// Static helpers.
41//
42
43// Base alignment for arrays/strings guaranteed by the Android runtime.
44static uint32_t BaseAlignment() {
45 return kObjectAlignment;
46}
47
48// Hidden offset for arrays/strings guaranteed by the Android runtime.
49static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
50 return is_string_char_at
51 ? mirror::String::ValueOffset().Uint32Value()
52 : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
53}
54
Aart Bik9abf8942016-10-14 09:49:42 -070055// Remove the instruction from the graph. A bit more elaborate than the usual
56// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070057static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070058 instruction->RemoveAsUserOfAllInputs();
59 instruction->RemoveEnvironmentUsers();
60 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010061 RemoveEnvironmentUses(instruction);
62 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070063}
64
Aart Bik807868e2016-11-03 17:51:43 -070065// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070066static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
67 if (block->GetPredecessors().size() == 1 &&
68 block->GetSuccessors().size() == 1 &&
69 block->IsSingleGoto()) {
70 *succ = block->GetSingleSuccessor();
71 return true;
72 }
73 return false;
74}
75
Aart Bik807868e2016-11-03 17:51:43 -070076// Detect an early exit loop.
77static bool IsEarlyExit(HLoopInformation* loop_info) {
78 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
79 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
80 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
81 if (!loop_info->Contains(*successor)) {
82 return true;
83 }
84 }
85 }
86 return false;
87}
88
Aart Bik68ca7022017-09-26 16:44:23 -070089// Forward declaration.
90static bool IsZeroExtensionAndGet(HInstruction* instruction,
91 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070092 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -070093
Aart Bikdf011c32017-09-28 12:53:04 -070094// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -070095// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070096static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010097 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070098 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070099 // Accept any already wider constant that would be handled properly by sign
100 // extension when represented in the *width* of the given narrower data type
Aart Bik4d1a9d42017-10-19 14:40:55 -0700101 // (the fact that Uint8/Uint16 normally zero extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700102 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700103 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700104 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100105 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100106 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700107 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700108 *operand = instruction;
109 return true;
110 }
111 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100112 case DataType::Type::kUint16:
113 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700114 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700115 *operand = instruction;
116 return true;
117 }
118 return false;
119 default:
120 return false;
121 }
122 }
Aart Bikdf011c32017-09-28 12:53:04 -0700123 // An implicit widening conversion of any signed expression sign-extends.
124 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700125 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100126 case DataType::Type::kInt8:
127 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700128 *operand = instruction;
129 return true;
130 default:
131 return false;
132 }
133 }
Aart Bikdf011c32017-09-28 12:53:04 -0700134 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700135 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700136 HInstruction* conv = instruction->InputAt(0);
137 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700138 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700139 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700140 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700141 if (type == from && (from == DataType::Type::kInt8 ||
142 from == DataType::Type::kInt16 ||
143 from == DataType::Type::kInt32)) {
144 *operand = conv;
145 return true;
146 }
147 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700148 case DataType::Type::kInt16:
149 return type == DataType::Type::kUint16 &&
150 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700151 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700152 default:
153 return false;
154 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700155 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700156 return false;
157}
158
Aart Bikdf011c32017-09-28 12:53:04 -0700159// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700160// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700161static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100162 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700163 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700164 // Accept any already wider constant that would be handled properly by zero
165 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700166 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700167 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700168 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700169 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100170 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100171 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700172 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700173 *operand = instruction;
174 return true;
175 }
176 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100177 case DataType::Type::kUint16:
178 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700179 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700180 *operand = instruction;
181 return true;
182 }
183 return false;
184 default:
185 return false;
186 }
187 }
Aart Bikdf011c32017-09-28 12:53:04 -0700188 // An implicit widening conversion of any unsigned expression zero-extends.
189 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100190 switch (type) {
191 case DataType::Type::kUint8:
192 case DataType::Type::kUint16:
193 *operand = instruction;
194 return true;
195 default:
196 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700197 }
198 }
Aart Bikdf011c32017-09-28 12:53:04 -0700199 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700200 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700201 HInstruction* conv = instruction->InputAt(0);
202 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700203 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700204 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700205 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700206 if (type == from && from == DataType::Type::kUint16) {
207 *operand = conv;
208 return true;
209 }
210 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700211 case DataType::Type::kUint16:
212 return type == DataType::Type::kInt16 &&
213 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700214 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700215 default:
216 return false;
217 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700218 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700219 return false;
220}
221
Aart Bik304c8a52017-05-23 11:01:13 -0700222// Detect situations with same-extension narrower operands.
223// Returns true on success and sets is_unsigned accordingly.
224static bool IsNarrowerOperands(HInstruction* a,
225 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100226 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700227 /*out*/ HInstruction** r,
228 /*out*/ HInstruction** s,
229 /*out*/ bool* is_unsigned) {
Aart Bik4d1a9d42017-10-19 14:40:55 -0700230 // Look for a matching sign extension.
231 DataType::Type stype = HVecOperation::ToSignedType(type);
232 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700233 *is_unsigned = false;
234 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700235 }
236 // Look for a matching zero extension.
237 DataType::Type utype = HVecOperation::ToUnsignedType(type);
238 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700239 *is_unsigned = true;
240 return true;
241 }
242 return false;
243}
244
245// As above, single operand.
246static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100247 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700248 /*out*/ HInstruction** r,
249 /*out*/ bool* is_unsigned) {
Aart Bik4d1a9d42017-10-19 14:40:55 -0700250 // Look for a matching sign extension.
251 DataType::Type stype = HVecOperation::ToSignedType(type);
252 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700253 *is_unsigned = false;
254 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700255 }
256 // Look for a matching zero extension.
257 DataType::Type utype = HVecOperation::ToUnsignedType(type);
258 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700259 *is_unsigned = true;
260 return true;
261 }
262 return false;
263}
264
Aart Bikdbbac8f2017-09-01 13:06:08 -0700265// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700266static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100267 DCHECK(DataType::IsIntegralType(other_type));
268 DCHECK(DataType::IsIntegralType(vector_type));
269 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
270 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700271}
272
Aart Bik5f805002017-05-16 16:42:41 -0700273// Detect up to two instructions a and b, and an acccumulated constant c.
274static bool IsAddConstHelper(HInstruction* instruction,
275 /*out*/ HInstruction** a,
276 /*out*/ HInstruction** b,
277 /*out*/ int64_t* c,
278 int32_t depth) {
279 static constexpr int32_t kMaxDepth = 8; // don't search too deep
280 int64_t value = 0;
281 if (IsInt64AndGet(instruction, &value)) {
282 *c += value;
283 return true;
284 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
285 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
286 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
287 } else if (*a == nullptr) {
288 *a = instruction;
289 return true;
290 } else if (*b == nullptr) {
291 *b = instruction;
292 return true;
293 }
294 return false; // too many non-const operands
295}
296
297// Detect a + b + c for an optional constant c.
298static bool IsAddConst(HInstruction* instruction,
299 /*out*/ HInstruction** a,
300 /*out*/ HInstruction** b,
301 /*out*/ int64_t* c) {
302 if (instruction->IsAdd()) {
303 // Try to find a + b and accumulated c.
304 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
305 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
306 *b != nullptr) {
307 return true;
308 }
309 // Found a + b.
310 *a = instruction->InputAt(0);
311 *b = instruction->InputAt(1);
312 *c = 0;
313 return true;
314 }
315 return false;
316}
317
Aart Bikdf011c32017-09-28 12:53:04 -0700318// Detect a + c for constant c.
319static bool IsAddConst(HInstruction* instruction,
320 /*out*/ HInstruction** a,
321 /*out*/ int64_t* c) {
322 if (instruction->IsAdd()) {
323 if (IsInt64AndGet(instruction->InputAt(0), c)) {
324 *a = instruction->InputAt(1);
325 return true;
326 } else if (IsInt64AndGet(instruction->InputAt(1), c)) {
327 *a = instruction->InputAt(0);
328 return true;
329 }
330 }
331 return false;
332}
333
Aart Bik29aa0822018-03-08 11:28:00 -0800334// Detect clipped [lo, hi] range for nested MIN-MAX operations on a clippee,
335// such as MIN(hi, MAX(lo, clippee)) for an arbitrary clippee expression.
336// Example: MIN(10, MIN(20, MAX(0, x))) yields [0, 10] with clippee x.
Aart Bik1a381022018-03-15 15:51:37 -0700337static HInstruction* FindClippee(HInstruction* instruction,
338 /*out*/ int64_t* lo,
339 /*out*/ int64_t* hi) {
340 // Iterate into MIN(.., c)-MAX(.., c) expressions and 'tighten' the range [lo, hi].
341 while (instruction->IsMin() || instruction->IsMax()) {
342 HBinaryOperation* min_max = instruction->AsBinaryOperation();
343 DCHECK(min_max->GetType() == DataType::Type::kInt32 ||
344 min_max->GetType() == DataType::Type::kInt64);
345 // Process the constant.
346 HConstant* right = min_max->GetConstantRight();
347 if (right == nullptr) {
348 break;
349 } else if (instruction->IsMin()) {
350 *hi = std::min(*hi, Int64FromConstant(right));
351 } else {
352 *lo = std::max(*lo, Int64FromConstant(right));
Aart Bik29aa0822018-03-08 11:28:00 -0800353 }
Aart Bik1a381022018-03-15 15:51:37 -0700354 instruction = min_max->GetLeastConstantLeft();
Aart Bik29aa0822018-03-08 11:28:00 -0800355 }
Aart Bik1a381022018-03-15 15:51:37 -0700356 // Iteration ends in any other expression (possibly MIN/MAX without constant).
357 // This leaf expression is the clippee with range [lo, hi].
358 return instruction;
Aart Bik29aa0822018-03-08 11:28:00 -0800359}
360
361// Accept various saturated addition forms.
362static bool IsSaturatedAdd(DataType::Type type, int64_t lo, int64_t hi, bool is_unsigned) {
363 // MIN(r + s, 255) => SAT_ADD_unsigned
364 // MAX(MIN(r + s, 127), -128) => SAT_ADD_signed etc.
365 if (DataType::Size(type) == 1) {
366 return is_unsigned
367 ? (lo <= 0 && hi == std::numeric_limits<uint8_t>::max())
368 : (lo == std::numeric_limits<int8_t>::min() &&
369 hi == std::numeric_limits<int8_t>::max());
370 } else if (DataType::Size(type) == 2) {
371 return is_unsigned
372 ? (lo <= 0 && hi == std::numeric_limits<uint16_t>::max())
373 : (lo == std::numeric_limits<int16_t>::min() &&
374 hi == std::numeric_limits<int16_t>::max());
375 }
376 return false;
377}
378
379// Accept various saturated subtraction forms.
380static bool IsSaturatedSub(DataType::Type type, int64_t lo, int64_t hi, bool is_unsigned) {
381 // MAX(r - s, 0) => SAT_SUB_unsigned
382 // MIN(MAX(r - s, -128), 127) => SAT_ADD_signed etc.
383 if (DataType::Size(type) == 1) {
384 return is_unsigned
385 ? (lo == 0 && hi >= std::numeric_limits<uint8_t>::max())
386 : (lo == std::numeric_limits<int8_t>::min() &&
387 hi == std::numeric_limits<int8_t>::max());
388 } else if (DataType::Size(type) == 2) {
389 return is_unsigned
390 ? (lo == 0 && hi >= std::numeric_limits<uint16_t>::min())
391 : (lo == std::numeric_limits<int16_t>::min() &&
392 hi == std::numeric_limits<int16_t>::max());
393 }
394 return false;
395}
396
Aart Bikb29f6842017-07-28 15:58:41 -0700397// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700398// x = x_phi + ..
399// x = x_phi - ..
Aart Bikb29f6842017-07-28 15:58:41 -0700400// x = min(x_phi, ..)
Aart Bik1f8d51b2018-02-15 10:42:37 -0800401// x = max(x_phi, ..)
Aart Bikb29f6842017-07-28 15:58:41 -0700402static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
Aart Bik1f8d51b2018-02-15 10:42:37 -0800403 if (reduction->IsAdd() || reduction->IsMin() || reduction->IsMax()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700404 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
405 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700406 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700407 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700408 }
409 return false;
410}
411
Aart Bikdbbac8f2017-09-01 13:06:08 -0700412// Translates vector operation to reduction kind.
413static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
414 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700415 return HVecReduce::kSum;
416 } else if (reduction->IsVecMin()) {
417 return HVecReduce::kMin;
418 } else if (reduction->IsVecMax()) {
419 return HVecReduce::kMax;
420 }
Aart Bik38a3f212017-10-20 17:02:21 -0700421 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700422 UNREACHABLE();
423}
424
Aart Bikf8f5a162017-02-06 15:35:29 -0800425// Test vector restrictions.
426static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
427 return (restrictions & tested) != 0;
428}
429
Aart Bikf3e61ee2017-04-12 17:09:20 -0700430// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800431static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
432 DCHECK(block != nullptr);
433 DCHECK(instruction != nullptr);
434 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
435 return instruction;
436}
437
Artem Serov21c7e6f2017-07-27 16:04:42 +0100438// Check that instructions from the induction sets are fully removed: have no uses
439// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100440static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100441 for (HInstruction* instr : *iset) {
442 if (instr->GetBlock() != nullptr ||
443 !instr->GetUses().empty() ||
444 !instr->GetEnvUses().empty() ||
445 HasEnvironmentUsedByOthers(instr)) {
446 return false;
447 }
448 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100449 return true;
450}
451
Aart Bik281c6812016-08-26 11:31:48 -0700452//
Aart Bikb29f6842017-07-28 15:58:41 -0700453// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700454//
455
456HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800457 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700458 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800459 OptimizingCompilerStats* stats,
460 const char* name)
461 : HOptimization(graph, name, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800462 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700463 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700464 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100465 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700466 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700467 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700468 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700469 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800470 simplified_(false),
471 vector_length_(0),
472 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700473 vector_static_peeling_factor_(0),
474 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700475 vector_runtime_test_a_(nullptr),
476 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700477 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100478 vector_permanent_map_(nullptr),
479 vector_mode_(kSequential),
480 vector_preheader_(nullptr),
481 vector_header_(nullptr),
482 vector_body_(nullptr),
483 vector_index_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700484}
485
486void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800487 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700488 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800489 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700490 return;
491 }
492
Vladimir Markoca6fff82017-10-03 14:49:14 +0100493 // Phase-local allocator.
494 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700495 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100496
Aart Bik96202302016-10-04 17:33:56 -0700497 // Perform loop optimizations.
498 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800499 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800500 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800501 }
502
Aart Bik96202302016-10-04 17:33:56 -0700503 // Detach.
504 loop_allocator_ = nullptr;
505 last_loop_ = top_loop_ = nullptr;
506}
507
Aart Bikb29f6842017-07-28 15:58:41 -0700508//
509// Loop setup and traversal.
510//
511
Aart Bik96202302016-10-04 17:33:56 -0700512void HLoopOptimization::LocalRun() {
513 // Build the linear order using the phase-local allocator. This step enables building
514 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100515 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
516 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700517
Aart Bik281c6812016-08-26 11:31:48 -0700518 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700519 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700520 if (block->IsLoopHeader()) {
521 AddLoop(block->GetLoopInformation());
522 }
523 }
Aart Bik96202302016-10-04 17:33:56 -0700524
Aart Bik8c4a8542016-10-06 11:36:57 -0700525 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800526 // temporary data structures using the phase-local allocator. All new HIR
527 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700528 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100529 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
530 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700531 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100532 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
533 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800534 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100535 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700536 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800537 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700538 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700539 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800540 vector_refs_ = &refs;
541 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700542 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800543 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700544 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800545 // Detach.
546 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700547 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800548 vector_refs_ = nullptr;
549 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700550 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700551 }
Aart Bik281c6812016-08-26 11:31:48 -0700552}
553
554void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
555 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800556 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700557 if (last_loop_ == nullptr) {
558 // First loop.
559 DCHECK(top_loop_ == nullptr);
560 last_loop_ = top_loop_ = node;
561 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
562 // Inner loop.
563 node->outer = last_loop_;
564 DCHECK(last_loop_->inner == nullptr);
565 last_loop_ = last_loop_->inner = node;
566 } else {
567 // Subsequent loop.
568 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
569 last_loop_ = last_loop_->outer;
570 }
571 node->outer = last_loop_->outer;
572 node->previous = last_loop_;
573 DCHECK(last_loop_->next == nullptr);
574 last_loop_ = last_loop_->next = node;
575 }
576}
577
578void HLoopOptimization::RemoveLoop(LoopNode* node) {
579 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700580 DCHECK(node->inner == nullptr);
581 if (node->previous != nullptr) {
582 // Within sequence.
583 node->previous->next = node->next;
584 if (node->next != nullptr) {
585 node->next->previous = node->previous;
586 }
587 } else {
588 // First of sequence.
589 if (node->outer != nullptr) {
590 node->outer->inner = node->next;
591 } else {
592 top_loop_ = node->next;
593 }
594 if (node->next != nullptr) {
595 node->next->outer = node->outer;
596 node->next->previous = nullptr;
597 }
598 }
Aart Bik281c6812016-08-26 11:31:48 -0700599}
600
Aart Bikb29f6842017-07-28 15:58:41 -0700601bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
602 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700603 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700604 // Visit inner loops first. Recompute induction information for this
605 // loop if the induction of any inner loop has changed.
606 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700607 induction_range_.ReVisit(node->loop_info);
608 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800609 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800610 // Note that since each simplification consists of eliminating code (without
611 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800612 do {
613 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800614 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800615 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700616 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800617 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800618 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700619 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700620 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700621 }
Aart Bik281c6812016-08-26 11:31:48 -0700622 }
Aart Bikb29f6842017-07-28 15:58:41 -0700623 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700624}
625
Aart Bikf8f5a162017-02-06 15:35:29 -0800626//
627// Optimization.
628//
629
Aart Bik281c6812016-08-26 11:31:48 -0700630void HLoopOptimization::SimplifyInduction(LoopNode* node) {
631 HBasicBlock* header = node->loop_info->GetHeader();
632 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700633 // Scan the phis in the header to find opportunities to simplify an induction
634 // cycle that is only used outside the loop. Replace these uses, if any, with
635 // the last value and remove the induction cycle.
636 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
637 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700638 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
639 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800640 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
641 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700642 // Note that it's ok to have replaced uses after the loop with the last value, without
643 // being able to remove the cycle. Environment uses (which are the reason we may not be
644 // able to remove the cycle) within the loop will still hold the right value. We must
645 // have tried first, however, to replace outside uses.
646 if (CanRemoveCycle()) {
647 simplified_ = true;
648 for (HInstruction* i : *iset_) {
649 RemoveFromCycle(i);
650 }
651 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700652 }
Aart Bik482095d2016-10-10 15:39:10 -0700653 }
654 }
655}
656
657void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800658 // Iterate over all basic blocks in the loop-body.
659 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
660 HBasicBlock* block = it.Current();
661 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800662 RemoveDeadInstructions(block->GetPhis());
663 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800664 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800665 if (block->GetPredecessors().size() == 1 &&
666 block->GetSuccessors().size() == 1 &&
667 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800668 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800669 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800670 } else if (block->GetSuccessors().size() == 2) {
671 // Trivial if block can be bypassed to either branch.
672 HBasicBlock* succ0 = block->GetSuccessors()[0];
673 HBasicBlock* succ1 = block->GetSuccessors()[1];
674 HBasicBlock* meet0 = nullptr;
675 HBasicBlock* meet1 = nullptr;
676 if (succ0 != succ1 &&
677 IsGotoBlock(succ0, &meet0) &&
678 IsGotoBlock(succ1, &meet1) &&
679 meet0 == meet1 && // meets again
680 meet0 != block && // no self-loop
681 meet0->GetPhis().IsEmpty()) { // not used for merging
682 simplified_ = true;
683 succ0->DisconnectAndDelete();
684 if (block->Dominates(meet0)) {
685 block->RemoveDominatedBlock(meet0);
686 succ1->AddDominatedBlock(meet0);
687 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700688 }
Aart Bik482095d2016-10-10 15:39:10 -0700689 }
Aart Bik281c6812016-08-26 11:31:48 -0700690 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800691 }
Aart Bik281c6812016-08-26 11:31:48 -0700692}
693
Aart Bikb29f6842017-07-28 15:58:41 -0700694bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700695 HBasicBlock* header = node->loop_info->GetHeader();
696 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700697 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800698 int64_t trip_count = 0;
699 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700700 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700701 }
Aart Bik281c6812016-08-26 11:31:48 -0700702 // Ensure there is only a single loop-body (besides the header).
703 HBasicBlock* body = nullptr;
704 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
705 if (it.Current() != header) {
706 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700707 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700708 }
709 body = it.Current();
710 }
711 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700712 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700713 // Ensure there is only a single exit point.
714 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700715 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700716 }
717 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
718 ? header->GetSuccessors()[1]
719 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700720 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700721 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700722 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700723 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800724 // Detect either an empty loop (no side effects other than plain iteration) or
725 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
726 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700727 HPhi* main_phi = nullptr;
728 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800729 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700730 if (reductions_->empty() && // TODO: possible with some effort
731 (is_empty || trip_count == 1) &&
732 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800733 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800734 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700735 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800736 preheader->MergeInstructionsWith(body);
737 }
738 body->DisconnectAndDelete();
739 exit->RemovePredecessor(header);
740 header->RemoveSuccessor(exit);
741 header->RemoveDominatedBlock(exit);
742 header->DisconnectAndDelete();
743 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800744 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800745 preheader->AddDominatedBlock(exit);
746 exit->SetDominator(preheader);
747 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700748 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800749 }
750 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800751 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700752 if (kEnableVectorization &&
753 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700754 ShouldVectorize(node, body, trip_count) &&
755 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
756 Vectorize(node, body, exit, trip_count);
757 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700758 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700759 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800760 }
Aart Bikb29f6842017-07-28 15:58:41 -0700761 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800762}
763
764//
765// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
766// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
767// Intel Press, June, 2004 (http://www.aartbik.com/).
768//
769
Aart Bik14a68b42017-06-08 14:06:58 -0700770bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800771 // Reset vector bookkeeping.
772 vector_length_ = 0;
773 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700774 vector_static_peeling_factor_ = 0;
775 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800776 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800777 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800778
779 // Phis in the loop-body prevent vectorization.
780 if (!block->GetPhis().IsEmpty()) {
781 return false;
782 }
783
784 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
785 // occurrence, which allows passing down attributes down the use tree.
786 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
787 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
788 return false; // failure to vectorize a left-hand-side
789 }
790 }
791
Aart Bik38a3f212017-10-20 17:02:21 -0700792 // Prepare alignment analysis:
793 // (1) find desired alignment (SIMD vector size in bytes).
794 // (2) initialize static loop peeling votes (peeling factor that will
795 // make one particular reference aligned), never to exceed (1).
796 // (3) variable to record how many references share same alignment.
797 // (4) variable to record suitable candidate for dynamic loop peeling.
798 uint32_t desired_alignment = GetVectorSizeInBytes();
799 DCHECK_LE(desired_alignment, 16u);
800 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
801 uint32_t max_num_same_alignment = 0;
802 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800803
804 // Data dependence analysis. Find each pair of references with same type, where
805 // at least one is a write. Each such pair denotes a possible data dependence.
806 // This analysis exploits the property that differently typed arrays cannot be
807 // aliased, as well as the property that references either point to the same
808 // array or to two completely disjoint arrays, i.e., no partial aliasing.
809 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700810 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800811 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700812 uint32_t num_same_alignment = 0;
813 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800814 for (auto j = i; ++j != vector_refs_->end(); ) {
815 if (i->type == j->type && (i->lhs || j->lhs)) {
816 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
817 HInstruction* a = i->base;
818 HInstruction* b = j->base;
819 HInstruction* x = i->offset;
820 HInstruction* y = j->offset;
821 if (a == b) {
822 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
823 // Conservatively assume a loop-carried data dependence otherwise, and reject.
824 if (x != y) {
825 return false;
826 }
Aart Bik38a3f212017-10-20 17:02:21 -0700827 // Count the number of references that have the same alignment (since
828 // base and offset are the same) and where at least one is a write, so
829 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
830 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800831 } else {
832 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
833 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
834 // generating an explicit a != b disambiguation runtime test on the two references.
835 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700836 // To avoid excessive overhead, we only accept one a != b test.
837 if (vector_runtime_test_a_ == nullptr) {
838 // First test found.
839 vector_runtime_test_a_ = a;
840 vector_runtime_test_b_ = b;
841 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
842 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
843 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800844 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800845 }
846 }
847 }
848 }
Aart Bik38a3f212017-10-20 17:02:21 -0700849 // Update information for finding suitable alignment strategy:
850 // (1) update votes for static loop peeling,
851 // (2) update suitable candidate for dynamic loop peeling.
852 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
853 if (alignment.Base() >= desired_alignment) {
854 // If the array/string object has a known, sufficient alignment, use the
855 // initial offset to compute the static loop peeling vote (this always
856 // works, since elements have natural alignment).
857 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
858 uint32_t vote = (offset == 0)
859 ? 0
860 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
861 DCHECK_LT(vote, 16u);
862 ++peeling_votes[vote];
863 } else if (BaseAlignment() >= desired_alignment &&
864 num_same_alignment > max_num_same_alignment) {
865 // Otherwise, if the array/string object has a known, sufficient alignment
866 // for just the base but with an unknown offset, record the candidate with
867 // the most occurrences for dynamic loop peeling (again, the peeling always
868 // works, since elements have natural alignment).
869 max_num_same_alignment = num_same_alignment;
870 peeling_candidate = &(*i);
871 }
872 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -0800873
Aart Bik38a3f212017-10-20 17:02:21 -0700874 // Find a suitable alignment strategy.
875 SetAlignmentStrategy(peeling_votes, peeling_candidate);
876
877 // Does vectorization seem profitable?
878 if (!IsVectorizationProfitable(trip_count)) {
879 return false;
880 }
Aart Bik14a68b42017-06-08 14:06:58 -0700881
Aart Bikf8f5a162017-02-06 15:35:29 -0800882 // Success!
883 return true;
884}
885
886void HLoopOptimization::Vectorize(LoopNode* node,
887 HBasicBlock* block,
888 HBasicBlock* exit,
889 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800890 HBasicBlock* header = node->loop_info->GetHeader();
891 HBasicBlock* preheader = node->loop_info->GetPreHeader();
892
Aart Bik14a68b42017-06-08 14:06:58 -0700893 // Pick a loop unrolling factor for the vector loop.
894 uint32_t unroll = GetUnrollingFactor(block, trip_count);
895 uint32_t chunk = vector_length_ * unroll;
896
Aart Bik38a3f212017-10-20 17:02:21 -0700897 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
898
Aart Bik14a68b42017-06-08 14:06:58 -0700899 // A cleanup loop is needed, at least, for any unknown trip count or
900 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -0700901 bool needs_cleanup = trip_count == 0 ||
902 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800903
904 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700905 HPhi* main_phi = nullptr;
906 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800907 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700908 vector_header_ = header;
909 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800910
Aart Bikdbbac8f2017-09-01 13:06:08 -0700911 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100912 DataType::Type induc_type = main_phi->GetType();
913 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
914 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700915
Aart Bik38a3f212017-10-20 17:02:21 -0700916 // Generate the trip count for static or dynamic loop peeling, if needed:
917 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -0700918 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -0700919 if (vector_static_peeling_factor_ != 0) {
920 // Static loop peeling for SIMD alignment (using the most suitable
921 // fixed peeling factor found during prior alignment analysis).
922 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
923 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
924 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
925 // Dynamic loop peeling for SIMD alignment (using the most suitable
926 // candidate found during prior alignment analysis):
927 // rem = offset % ALIGN; // adjusted as #elements
928 // ptc = rem == 0 ? 0 : (ALIGN - rem);
929 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
930 uint32_t align = GetVectorSizeInBytes() >> shift;
931 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
932 vector_dynamic_peeling_candidate_->is_string_char_at);
933 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
934 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
935 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
936 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
937 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
938 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
939 induc_type, graph_->GetConstant(induc_type, align), rem));
940 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
941 rem, graph_->GetConstant(induc_type, 0)));
942 ptc = Insert(preheader, new (global_allocator_) HSelect(
943 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
944 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -0700945 }
946
947 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800948 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -0700949 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -0700950 // vtc = stc - (stc - ptc) % chunk;
951 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800952 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
953 HInstruction* vtc = stc;
954 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700955 DCHECK(IsPowerOfTwo(chunk));
956 HInstruction* diff = stc;
957 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -0700958 if (trip_count == 0) {
959 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
960 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
961 }
Aart Bik14a68b42017-06-08 14:06:58 -0700962 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
963 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800964 HInstruction* rem = Insert(
965 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700966 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700967 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800968 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
969 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700970 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800971
972 // Generate runtime disambiguation test:
973 // vtc = a != b ? vtc : 0;
974 if (vector_runtime_test_a_ != nullptr) {
975 HInstruction* rt = Insert(
976 preheader,
977 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
978 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700979 new (global_allocator_)
980 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -0800981 needs_cleanup = true;
982 }
983
Aart Bik38a3f212017-10-20 17:02:21 -0700984 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -0700985 // for ( ; i < ptc; i += 1)
986 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -0700987 //
988 // NOTE: The alignment forced by the peeling loop is preserved even if data is
989 // moved around during suspend checks, since all analysis was based on
990 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -0700991 if (ptc != nullptr) {
992 vector_mode_ = kSequential;
993 GenerateNewLoop(node,
994 block,
995 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
996 vector_index_,
997 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700998 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700999 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001000 }
1001
1002 // Generate vector loop, possibly further unrolled:
1003 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001004 // <vectorized-loop-body>
1005 vector_mode_ = kVector;
1006 GenerateNewLoop(node,
1007 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001008 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1009 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001010 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001011 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001012 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001013 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1014
1015 // Generate cleanup loop, if needed:
1016 // for ( ; i < stc; i += 1)
1017 // <loop-body>
1018 if (needs_cleanup) {
1019 vector_mode_ = kSequential;
1020 GenerateNewLoop(node,
1021 block,
1022 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001023 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001024 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001025 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001026 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001027 }
1028
Aart Bik0148de42017-09-05 09:25:01 -07001029 // Link reductions to their final uses.
1030 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1031 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001032 HInstruction* phi = i->first;
1033 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1034 // Deal with regular uses.
1035 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1036 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1037 }
1038 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001039 }
1040 }
1041
Aart Bikf8f5a162017-02-06 15:35:29 -08001042 // Remove the original loop by disconnecting the body block
1043 // and removing all instructions from the header.
1044 block->DisconnectAndDelete();
1045 while (!header->GetFirstInstruction()->IsGoto()) {
1046 header->RemoveInstruction(header->GetFirstInstruction());
1047 }
Aart Bikb29f6842017-07-28 15:58:41 -07001048
Aart Bik14a68b42017-06-08 14:06:58 -07001049 // Update loop hierarchy: the old header now resides in the same outer loop
1050 // as the old preheader. Note that we don't bother putting sequential
1051 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001052 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1053 node->loop_info = vloop;
1054}
1055
1056void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1057 HBasicBlock* block,
1058 HBasicBlock* new_preheader,
1059 HInstruction* lo,
1060 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001061 HInstruction* step,
1062 uint32_t unroll) {
1063 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001064 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001065 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001066 vector_preheader_ = new_preheader,
1067 vector_header_ = vector_preheader_->GetSingleSuccessor();
1068 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001069 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1070 kNoRegNumber,
1071 0,
1072 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001073 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001074 // for (i = lo; i < hi; i += step)
1075 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001076 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1077 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001078 vector_header_->AddInstruction(cond);
1079 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001080 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001081 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001082 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001083 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001084 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001085 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1086 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1087 DCHECK(vectorized_def);
1088 }
1089 // Generate body from the instruction map, but in original program order.
1090 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1091 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1092 auto i = vector_map_->find(it.Current());
1093 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1094 Insert(vector_body_, i->second);
1095 // Deal with instructions that need an environment, such as the scalar intrinsics.
1096 if (i->second->NeedsEnvironment()) {
1097 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1098 }
1099 }
1100 }
Aart Bik0148de42017-09-05 09:25:01 -07001101 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001102 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1103 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001104 }
Aart Bik0148de42017-09-05 09:25:01 -07001105 // Finalize phi inputs for the reductions (if any).
1106 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1107 if (!i->first->IsPhi()) {
1108 DCHECK(i->second->IsPhi());
1109 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1110 }
1111 }
Aart Bikb29f6842017-07-28 15:58:41 -07001112 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001113 phi->AddInput(lo);
1114 phi->AddInput(vector_index_);
1115 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001116}
1117
Aart Bikf8f5a162017-02-06 15:35:29 -08001118bool HLoopOptimization::VectorizeDef(LoopNode* node,
1119 HInstruction* instruction,
1120 bool generate_code) {
1121 // Accept a left-hand-side array base[index] for
1122 // (1) supported vector type,
1123 // (2) loop-invariant base,
1124 // (3) unit stride index,
1125 // (4) vectorizable right-hand-side value.
1126 uint64_t restrictions = kNone;
1127 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001128 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001129 HInstruction* base = instruction->InputAt(0);
1130 HInstruction* index = instruction->InputAt(1);
1131 HInstruction* value = instruction->InputAt(2);
1132 HInstruction* offset = nullptr;
1133 if (TrySetVectorType(type, &restrictions) &&
1134 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001135 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001136 VectorizeUse(node, value, generate_code, type, restrictions)) {
1137 if (generate_code) {
1138 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001139 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001140 } else {
1141 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1142 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001143 return true;
1144 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001145 return false;
1146 }
Aart Bik0148de42017-09-05 09:25:01 -07001147 // Accept a left-hand-side reduction for
1148 // (1) supported vector type,
1149 // (2) vectorizable right-hand-side value.
1150 auto redit = reductions_->find(instruction);
1151 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001152 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001153 // Recognize SAD idiom or direct reduction.
1154 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1155 (TrySetVectorType(type, &restrictions) &&
1156 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001157 if (generate_code) {
1158 HInstruction* new_red = vector_map_->Get(instruction);
1159 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1160 vector_permanent_map_->Overwrite(redit->second, new_red);
1161 }
1162 return true;
1163 }
1164 return false;
1165 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001166 // Branch back okay.
1167 if (instruction->IsGoto()) {
1168 return true;
1169 }
1170 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1171 // Note that actual uses are inspected during right-hand-side tree traversal.
1172 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1173}
1174
Aart Bikf8f5a162017-02-06 15:35:29 -08001175bool HLoopOptimization::VectorizeUse(LoopNode* node,
1176 HInstruction* instruction,
1177 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001178 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001179 uint64_t restrictions) {
1180 // Accept anything for which code has already been generated.
1181 if (generate_code) {
1182 if (vector_map_->find(instruction) != vector_map_->end()) {
1183 return true;
1184 }
1185 }
1186 // Continue the right-hand-side tree traversal, passing in proper
1187 // types and vector restrictions along the way. During code generation,
1188 // all new nodes are drawn from the global allocator.
1189 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1190 // Accept invariant use, using scalar expansion.
1191 if (generate_code) {
1192 GenerateVecInv(instruction, type);
1193 }
1194 return true;
1195 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001196 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001197 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1198 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001199 return false;
1200 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001201 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001202 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001203 // (2) loop-invariant base,
1204 // (3) unit stride index,
1205 // (4) vectorizable right-hand-side value.
1206 HInstruction* base = instruction->InputAt(0);
1207 HInstruction* index = instruction->InputAt(1);
1208 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001209 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001210 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001211 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001212 if (generate_code) {
1213 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001214 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001215 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001216 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001217 }
1218 return true;
1219 }
Aart Bik0148de42017-09-05 09:25:01 -07001220 } else if (instruction->IsPhi()) {
1221 // Accept particular phi operations.
1222 if (reductions_->find(instruction) != reductions_->end()) {
1223 // Deal with vector restrictions.
1224 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1225 return false;
1226 }
1227 // Accept a reduction.
1228 if (generate_code) {
1229 GenerateVecReductionPhi(instruction->AsPhi());
1230 }
1231 return true;
1232 }
1233 // TODO: accept right-hand-side induction?
1234 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001235 } else if (instruction->IsTypeConversion()) {
1236 // Accept particular type conversions.
1237 HTypeConversion* conversion = instruction->AsTypeConversion();
1238 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001239 DataType::Type from = conversion->GetInputType();
1240 DataType::Type to = conversion->GetResultType();
1241 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001242 uint32_t size_vec = DataType::Size(type);
1243 uint32_t size_from = DataType::Size(from);
1244 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001245 // Accept an integral conversion
1246 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1247 // (1b) widening from at least vector type, and
1248 // (2) vectorizable operand.
1249 if ((size_to < size_from &&
1250 size_to == size_vec &&
1251 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1252 (size_to >= size_from &&
1253 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001254 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001255 if (generate_code) {
1256 if (vector_mode_ == kVector) {
1257 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1258 } else {
1259 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1260 }
1261 }
1262 return true;
1263 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001264 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001265 DCHECK_EQ(to, type);
1266 // Accept int to float conversion for
1267 // (1) supported int,
1268 // (2) vectorizable operand.
1269 if (TrySetVectorType(from, &restrictions) &&
1270 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1271 if (generate_code) {
1272 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1273 }
1274 return true;
1275 }
1276 }
1277 return false;
1278 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1279 // Accept unary operator for vectorizable operand.
1280 HInstruction* opa = instruction->InputAt(0);
1281 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1282 if (generate_code) {
1283 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1284 }
1285 return true;
1286 }
1287 } else if (instruction->IsAdd() || instruction->IsSub() ||
1288 instruction->IsMul() || instruction->IsDiv() ||
1289 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1290 // Deal with vector restrictions.
1291 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1292 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1293 return false;
1294 }
1295 // Accept binary operator for vectorizable operands.
1296 HInstruction* opa = instruction->InputAt(0);
1297 HInstruction* opb = instruction->InputAt(1);
1298 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1299 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1300 if (generate_code) {
1301 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1302 }
1303 return true;
1304 }
1305 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001306 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001307 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1308 return true;
1309 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001310 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001311 HInstruction* opa = instruction->InputAt(0);
1312 HInstruction* opb = instruction->InputAt(1);
1313 HInstruction* r = opa;
1314 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001315 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1316 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1317 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001318 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1319 // Shifts right need extra care to account for higher order bits.
1320 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1321 if (instruction->IsShr() &&
1322 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1323 return false; // reject, unless all operands are sign-extension narrower
1324 } else if (instruction->IsUShr() &&
1325 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1326 return false; // reject, unless all operands are zero-extension narrower
1327 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001328 }
1329 // Accept shift operator for vectorizable/invariant operands.
1330 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001331 DCHECK(r != nullptr);
1332 if (generate_code && vector_mode_ != kVector) { // de-idiom
1333 r = opa;
1334 }
Aart Bik50e20d52017-05-05 14:07:29 -07001335 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001336 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001337 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001338 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001339 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001340 if (0 <= distance && distance < max_distance) {
1341 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001342 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001343 }
1344 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001345 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001346 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001347 } else if (instruction->IsAbs()) {
1348 // Deal with vector restrictions.
1349 HInstruction* opa = instruction->InputAt(0);
1350 HInstruction* r = opa;
1351 bool is_unsigned = false;
1352 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1353 return false;
1354 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1355 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1356 return false; // reject, unless operand is sign-extension narrower
1357 }
1358 // Accept ABS(x) for vectorizable operand.
1359 DCHECK(r != nullptr);
1360 if (generate_code && vector_mode_ != kVector) { // de-idiom
1361 r = opa;
1362 }
1363 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1364 if (generate_code) {
1365 GenerateVecOp(instruction,
1366 vector_map_->Get(r),
1367 nullptr,
1368 HVecOperation::ToProperType(type, is_unsigned));
1369 }
1370 return true;
1371 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001372 } else if (instruction->IsMin() || instruction->IsMax()) {
Aart Bik29aa0822018-03-08 11:28:00 -08001373 // Recognize saturation arithmetic.
1374 if (VectorizeSaturationIdiom(node, instruction, generate_code, type, restrictions)) {
1375 return true;
1376 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001377 // Deal with vector restrictions.
1378 HInstruction* opa = instruction->InputAt(0);
1379 HInstruction* opb = instruction->InputAt(1);
1380 HInstruction* r = opa;
1381 HInstruction* s = opb;
1382 bool is_unsigned = false;
1383 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1384 return false;
1385 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1386 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1387 return false; // reject, unless all operands are same-extension narrower
1388 }
1389 // Accept MIN/MAX(x, y) for vectorizable operands.
1390 DCHECK(r != nullptr);
1391 DCHECK(s != nullptr);
1392 if (generate_code && vector_mode_ != kVector) { // de-idiom
1393 r = opa;
1394 s = opb;
1395 }
1396 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1397 VectorizeUse(node, s, generate_code, type, restrictions)) {
1398 if (generate_code) {
1399 GenerateVecOp(
1400 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001401 }
Aart Bik1f8d51b2018-02-15 10:42:37 -08001402 return true;
1403 }
Aart Bik281c6812016-08-26 11:31:48 -07001404 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001405 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001406}
1407
Aart Bik38a3f212017-10-20 17:02:21 -07001408uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1409 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001410 case InstructionSet::kArm:
1411 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001412 return 8; // 64-bit SIMD
1413 default:
1414 return 16; // 128-bit SIMD
1415 }
1416}
1417
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001418bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001419 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1420 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001421 case InstructionSet::kArm:
1422 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001423 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001424 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001425 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001426 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001427 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001428 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001429 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001430 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001431 case DataType::Type::kUint16:
1432 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001433 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001434 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001435 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001436 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001437 return TrySetVectorLength(2);
1438 default:
1439 break;
1440 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001441 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001442 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001443 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001444 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001445 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001446 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001447 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001448 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001449 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001450 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001451 case DataType::Type::kUint16:
1452 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001453 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001454 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001455 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001456 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001457 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001458 case DataType::Type::kInt64:
Aart Bikc8e93c72017-05-10 10:49:22 -07001459 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001460 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001461 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001462 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001463 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001464 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001465 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001466 return TrySetVectorLength(2);
1467 default:
1468 return false;
1469 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001470 case InstructionSet::kX86:
1471 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001472 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001473 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1474 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001475 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001476 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001477 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001478 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001479 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001480 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001481 case DataType::Type::kUint16:
1482 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001483 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001484 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001485 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001486 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001487 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001488 case DataType::Type::kInt64:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001489 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001490 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001491 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001492 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001493 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001494 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001495 *restrictions |= kNoMinMax | kNoReduction; // minmax: -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001496 return TrySetVectorLength(2);
1497 default:
1498 break;
1499 } // switch type
1500 }
1501 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001502 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001503 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1504 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001505 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001506 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001507 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001508 *restrictions |= kNoDiv | kNoSaturation;
Lena Djokic51765b02017-06-22 13:49:59 +02001509 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001510 case DataType::Type::kUint16:
1511 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001512 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001513 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001514 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001515 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001516 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001517 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001518 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001519 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001520 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001521 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001522 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001523 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001524 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Lena Djokic51765b02017-06-22 13:49:59 +02001525 return TrySetVectorLength(2);
1526 default:
1527 break;
1528 } // switch type
1529 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001530 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001531 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001532 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1533 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001534 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001535 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001536 case DataType::Type::kInt8:
Aart Bik29aa0822018-03-08 11:28:00 -08001537 *restrictions |= kNoDiv | kNoSaturation;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001538 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001539 case DataType::Type::kUint16:
1540 case DataType::Type::kInt16:
Aart Bik29aa0822018-03-08 11:28:00 -08001541 *restrictions |= kNoDiv | kNoSaturation | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001542 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001543 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001544 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001545 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001546 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001547 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001548 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001549 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001550 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001551 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001552 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001553 *restrictions |= kNoMinMax | kNoReduction; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001554 return TrySetVectorLength(2);
1555 default:
1556 break;
1557 } // switch type
1558 }
1559 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001560 default:
1561 return false;
1562 } // switch instruction set
1563}
1564
1565bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1566 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1567 // First time set?
1568 if (vector_length_ == 0) {
1569 vector_length_ = length;
1570 }
1571 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1572 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1573 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1574 return vector_length_ == length;
1575}
1576
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001577void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001578 if (vector_map_->find(org) == vector_map_->end()) {
1579 // In scalar code, just use a self pass-through for scalar invariants
1580 // (viz. expression remains itself).
1581 if (vector_mode_ == kSequential) {
1582 vector_map_->Put(org, org);
1583 return;
1584 }
1585 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001586 HInstruction* vector = nullptr;
1587 auto it = vector_permanent_map_->find(org);
1588 if (it != vector_permanent_map_->end()) {
1589 vector = it->second; // reuse during unrolling
1590 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001591 // Generates ReplicateScalar( (optional_type_conv) org ).
1592 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001593 DataType::Type input_type = input->GetType();
1594 if (type != input_type && (type == DataType::Type::kInt64 ||
1595 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001596 input = Insert(vector_preheader_,
1597 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1598 }
1599 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001600 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001601 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1602 }
1603 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001604 }
1605}
1606
1607void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1608 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001609 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001610 int64_t value = 0;
1611 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001612 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001613 if (org->IsPhi()) {
1614 Insert(vector_body_, subscript); // lacks layout placeholder
1615 }
1616 }
1617 vector_map_->Put(org, subscript);
1618 }
1619}
1620
1621void HLoopOptimization::GenerateVecMem(HInstruction* org,
1622 HInstruction* opa,
1623 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001624 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001625 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001626 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001627 HInstruction* vector = nullptr;
1628 if (vector_mode_ == kVector) {
1629 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001630 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001631 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001632 if (opb != nullptr) {
1633 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001634 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001635 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001636 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001637 vector = new (global_allocator_) HVecLoad(global_allocator_,
1638 base,
1639 opa,
1640 type,
1641 org->GetSideEffects(),
1642 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001643 is_string_char_at,
1644 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001645 }
Aart Bik38a3f212017-10-20 17:02:21 -07001646 // Known (forced/adjusted/original) alignment?
1647 if (vector_dynamic_peeling_candidate_ != nullptr) {
1648 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1649 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1650 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1651 vector->AsVecMemoryOperation()->SetAlignment( // forced
1652 Alignment(GetVectorSizeInBytes(), 0));
1653 }
1654 } else {
1655 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1656 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001657 }
1658 } else {
1659 // Scalar store or load.
1660 DCHECK(vector_mode_ == kSequential);
1661 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001662 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001663 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001664 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001665 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001666 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1667 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001668 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001669 }
1670 }
1671 vector_map_->Put(org, vector);
1672}
1673
Aart Bik0148de42017-09-05 09:25:01 -07001674void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1675 DCHECK(reductions_->find(phi) != reductions_->end());
1676 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1677 HInstruction* vector = nullptr;
1678 if (vector_mode_ == kSequential) {
1679 HPhi* new_phi = new (global_allocator_) HPhi(
1680 global_allocator_, kNoRegNumber, 0, phi->GetType());
1681 vector_header_->AddPhi(new_phi);
1682 vector = new_phi;
1683 } else {
1684 // Link vector reduction back to prior unrolled update, or a first phi.
1685 auto it = vector_permanent_map_->find(phi);
1686 if (it != vector_permanent_map_->end()) {
1687 vector = it->second;
1688 } else {
1689 HPhi* new_phi = new (global_allocator_) HPhi(
1690 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1691 vector_header_->AddPhi(new_phi);
1692 vector = new_phi;
1693 }
1694 }
1695 vector_map_->Put(phi, vector);
1696}
1697
1698void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1699 HInstruction* new_phi = vector_map_->Get(phi);
1700 HInstruction* new_init = reductions_->Get(phi);
1701 HInstruction* new_red = vector_map_->Get(reduction);
1702 // Link unrolled vector loop back to new phi.
1703 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1704 DCHECK(new_phi->IsVecOperation());
1705 }
1706 // Prepare the new initialization.
1707 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001708 // Generate a [initial, 0, .., 0] vector for add or
1709 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001710 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001711 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001712 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001713 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001714 if (kind == HVecReduce::ReductionKind::kSum) {
1715 new_init = Insert(vector_preheader_,
1716 new (global_allocator_) HVecSetScalars(global_allocator_,
1717 &new_init,
1718 type,
1719 vector_length,
1720 1,
1721 kNoDexPc));
1722 } else {
1723 new_init = Insert(vector_preheader_,
1724 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1725 new_init,
1726 type,
1727 vector_length,
1728 kNoDexPc));
1729 }
Aart Bik0148de42017-09-05 09:25:01 -07001730 } else {
1731 new_init = ReduceAndExtractIfNeeded(new_init);
1732 }
1733 // Set the phi inputs.
1734 DCHECK(new_phi->IsPhi());
1735 new_phi->AsPhi()->AddInput(new_init);
1736 new_phi->AsPhi()->AddInput(new_red);
1737 // New feed value for next phi (safe mutation in iteration).
1738 reductions_->find(phi)->second = new_phi;
1739}
1740
1741HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1742 if (instruction->IsPhi()) {
1743 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001744 if (HVecOperation::ReturnsSIMDValue(input)) {
1745 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001746 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001747 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001748 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001749 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001750 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1751 // Generate a vector reduction and scalar extract
1752 // x = REDUCE( [x_1, .., x_n] )
1753 // y = x_1
1754 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001755 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001756 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001757 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1758 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001759 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001760 exit->InsertInstructionAfter(instruction, reduce);
1761 }
1762 }
1763 return instruction;
1764}
1765
Aart Bikf8f5a162017-02-06 15:35:29 -08001766#define GENERATE_VEC(x, y) \
1767 if (vector_mode_ == kVector) { \
1768 vector = (x); \
1769 } else { \
1770 DCHECK(vector_mode_ == kSequential); \
1771 vector = (y); \
1772 } \
1773 break;
1774
1775void HLoopOptimization::GenerateVecOp(HInstruction* org,
1776 HInstruction* opa,
1777 HInstruction* opb,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001778 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -07001779 bool is_unsigned) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001780 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001781 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001782 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001783 switch (org->GetKind()) {
1784 case HInstruction::kNeg:
1785 DCHECK(opb == nullptr);
1786 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001787 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1788 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001789 case HInstruction::kNot:
1790 DCHECK(opb == nullptr);
1791 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001792 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1793 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001794 case HInstruction::kBooleanNot:
1795 DCHECK(opb == nullptr);
1796 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001797 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1798 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001799 case HInstruction::kTypeConversion:
1800 DCHECK(opb == nullptr);
1801 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001802 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1803 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001804 case HInstruction::kAdd:
1805 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001806 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1807 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001808 case HInstruction::kSub:
1809 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001810 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1811 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001812 case HInstruction::kMul:
1813 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001814 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1815 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001816 case HInstruction::kDiv:
1817 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001818 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1819 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001820 case HInstruction::kAnd:
1821 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001822 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1823 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001824 case HInstruction::kOr:
1825 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001826 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1827 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001828 case HInstruction::kXor:
1829 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001830 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1831 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001832 case HInstruction::kShl:
1833 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001834 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1835 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001836 case HInstruction::kShr:
1837 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001838 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1839 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001840 case HInstruction::kUShr:
1841 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001842 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1843 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik1f8d51b2018-02-15 10:42:37 -08001844 case HInstruction::kMin:
1845 GENERATE_VEC(
1846 new (global_allocator_) HVecMin(global_allocator_,
1847 opa,
1848 opb,
1849 HVecOperation::ToProperType(type, is_unsigned),
1850 vector_length_,
1851 dex_pc),
1852 new (global_allocator_) HMin(org_type, opa, opb, dex_pc));
1853 case HInstruction::kMax:
1854 GENERATE_VEC(
1855 new (global_allocator_) HVecMax(global_allocator_,
1856 opa,
1857 opb,
1858 HVecOperation::ToProperType(type, is_unsigned),
1859 vector_length_,
1860 dex_pc),
1861 new (global_allocator_) HMax(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001862 case HInstruction::kAbs:
1863 DCHECK(opb == nullptr);
1864 GENERATE_VEC(
1865 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1866 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001867 default:
1868 break;
1869 } // switch
1870 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1871 vector_map_->Put(org, vector);
1872}
1873
1874#undef GENERATE_VEC
1875
1876//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001877// Vectorization idioms.
1878//
1879
Aart Bik29aa0822018-03-08 11:28:00 -08001880// Method recognizes single and double clipping saturation arithmetic.
1881bool HLoopOptimization::VectorizeSaturationIdiom(LoopNode* node,
1882 HInstruction* instruction,
1883 bool generate_code,
1884 DataType::Type type,
1885 uint64_t restrictions) {
1886 // Deal with vector restrictions.
1887 if (HasVectorRestrictions(restrictions, kNoSaturation)) {
1888 return false;
1889 }
Aart Bik1a381022018-03-15 15:51:37 -07001890 // Restrict type (generalize if one day we generalize allowed MIN/MAX integral types).
1891 if (instruction->GetType() != DataType::Type::kInt32 &&
1892 instruction->GetType() != DataType::Type::kInt64) {
Aart Bik29aa0822018-03-08 11:28:00 -08001893 return false;
1894 }
Aart Bik29aa0822018-03-08 11:28:00 -08001895 // Clipped addition or subtraction?
Aart Bik1a381022018-03-15 15:51:37 -07001896 int64_t lo = std::numeric_limits<int64_t>::min();
1897 int64_t hi = std::numeric_limits<int64_t>::max();
1898 HInstruction* clippee = FindClippee(instruction, &lo, &hi);
Aart Bik29aa0822018-03-08 11:28:00 -08001899 bool is_add = true;
1900 if (clippee->IsAdd()) {
1901 is_add = true;
1902 } else if (clippee->IsSub()) {
1903 is_add = false;
1904 } else {
1905 return false; // clippee is not add/sub
1906 }
1907 // Addition or subtraction on narrower operands?
1908 HInstruction* r = nullptr;
1909 HInstruction* s = nullptr;
1910 bool is_unsigned = false;
1911 if (IsNarrowerOperands(clippee->InputAt(0), clippee->InputAt(1), type, &r, &s, &is_unsigned) &&
1912 (is_add ? IsSaturatedAdd(type, lo, hi, is_unsigned)
1913 : IsSaturatedSub(type, lo, hi, is_unsigned))) {
1914 DCHECK(r != nullptr);
1915 DCHECK(s != nullptr);
1916 } else {
1917 return false;
1918 }
1919 // Accept saturation idiom for vectorizable operands.
1920 if (generate_code && vector_mode_ != kVector) { // de-idiom
1921 r = instruction->InputAt(0);
1922 s = instruction->InputAt(1);
1923 restrictions &= ~(kNoHiBits | kNoMinMax); // allow narrow MIN/MAX in seq
1924 }
1925 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1926 VectorizeUse(node, s, generate_code, type, restrictions)) {
1927 if (generate_code) {
1928 if (vector_mode_ == kVector) {
1929 DataType::Type vtype = HVecOperation::ToProperType(type, is_unsigned);
1930 HInstruction* op1 = vector_map_->Get(r);
1931 HInstruction* op2 = vector_map_->Get(s);
1932 vector_map_->Put(instruction, is_add
1933 ? reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationAdd(
1934 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc))
1935 : reinterpret_cast<HInstruction*>(new (global_allocator_) HVecSaturationSub(
1936 global_allocator_, op1, op2, vtype, vector_length_, kNoDexPc)));
1937 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
1938 } else {
1939 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
1940 }
1941 }
1942 return true;
1943 }
1944 return false;
1945}
1946
Aart Bikf3e61ee2017-04-12 17:09:20 -07001947// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001948// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1949// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001950// Provided that the operands are promoted to a wider form to do the arithmetic and
1951// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1952// implementation that operates directly in narrower form (plus one extra bit).
1953// TODO: current version recognizes implicit byte/short/char widening only;
1954// explicit widening from int to long could be added later.
1955bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1956 HInstruction* instruction,
1957 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001958 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001959 uint64_t restrictions) {
1960 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001961 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001962 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001963 if ((instruction->IsShr() ||
1964 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001965 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001966 // Test for (a + b + c) >> 1 for optional constant c.
1967 HInstruction* a = nullptr;
1968 HInstruction* b = nullptr;
1969 int64_t c = 0;
1970 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001971 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001972 // Accept c == 1 (rounded) or c == 0 (not rounded).
1973 bool is_rounded = false;
1974 if (c == 1) {
1975 is_rounded = true;
1976 } else if (c != 0) {
1977 return false;
1978 }
1979 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001980 HInstruction* r = nullptr;
1981 HInstruction* s = nullptr;
1982 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001983 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001984 return false;
1985 }
1986 // Deal with vector restrictions.
1987 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1988 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1989 return false;
1990 }
1991 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1992 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001993 DCHECK(r != nullptr);
1994 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001995 if (generate_code && vector_mode_ != kVector) { // de-idiom
1996 r = instruction->InputAt(0);
1997 s = instruction->InputAt(1);
1998 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001999 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2000 VectorizeUse(node, s, generate_code, type, restrictions)) {
2001 if (generate_code) {
2002 if (vector_mode_ == kVector) {
2003 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2004 global_allocator_,
2005 vector_map_->Get(r),
2006 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002007 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002008 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002009 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002010 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002011 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002012 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002013 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002014 }
2015 }
2016 return true;
2017 }
2018 }
2019 }
2020 return false;
2021}
2022
Aart Bikdbbac8f2017-09-01 13:06:08 -07002023// Method recognizes the following idiom:
2024// q += ABS(a - b) for signed operands a, b
2025// Provided that the operands have the same type or are promoted to a wider form.
2026// Since this may involve a vector length change, the idiom is handled by going directly
2027// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2028// TODO: unsigned SAD too?
2029bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2030 HInstruction* instruction,
2031 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002032 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002033 uint64_t restrictions) {
2034 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2035 // are done in the same precision (either int or long).
2036 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002037 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002038 return false;
2039 }
2040 HInstruction* q = instruction->InputAt(0);
2041 HInstruction* v = instruction->InputAt(1);
2042 HInstruction* a = nullptr;
2043 HInstruction* b = nullptr;
Aart Bik3b2a5952018-03-05 13:55:28 -08002044 if (v->GetType() == reduction_type && v->IsAbs()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002045 HInstruction* x = v->InputAt(0);
Aart Bikdf011c32017-09-28 12:53:04 -07002046 if (x->GetType() == reduction_type) {
2047 int64_t c = 0;
2048 if (x->IsSub()) {
2049 a = x->InputAt(0);
2050 b = x->InputAt(1);
2051 } else if (IsAddConst(x, /*out*/ &a, /*out*/ &c)) {
2052 b = graph_->GetConstant(reduction_type, -c); // hidden SUB!
2053 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07002054 }
2055 }
2056 if (a == nullptr || b == nullptr) {
2057 return false;
2058 }
2059 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2060 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002061 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002062 HInstruction* r = a;
2063 HInstruction* s = b;
2064 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002065 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002066 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2067 sub_type = b->GetType();
2068 }
2069 if (a->IsTypeConversion() &&
2070 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2071 sub_type = a->InputAt(0)->GetType();
2072 }
2073 if (b->IsTypeConversion() &&
2074 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2075 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002076 }
2077 if (reduction_type != sub_type &&
2078 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2079 return false;
2080 }
2081 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002082 if (!TrySetVectorType(sub_type, &restrictions) ||
2083 HasVectorRestrictions(restrictions, kNoSAD) ||
2084 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002085 return false;
2086 }
2087 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2088 // idiomatic operation. Sequential code uses the original scalar expressions.
2089 DCHECK(r != nullptr);
2090 DCHECK(s != nullptr);
2091 if (generate_code && vector_mode_ != kVector) { // de-idiom
2092 r = s = v->InputAt(0);
2093 }
2094 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2095 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2096 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2097 if (generate_code) {
2098 if (vector_mode_ == kVector) {
2099 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2100 global_allocator_,
2101 vector_map_->Get(q),
2102 vector_map_->Get(r),
2103 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002104 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002105 GetOtherVL(reduction_type, sub_type, vector_length_),
2106 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002107 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2108 } else {
2109 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2110 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2111 }
2112 }
2113 return true;
2114 }
2115 return false;
2116}
2117
Aart Bikf3e61ee2017-04-12 17:09:20 -07002118//
Aart Bik14a68b42017-06-08 14:06:58 -07002119// Vectorization heuristics.
2120//
2121
Aart Bik38a3f212017-10-20 17:02:21 -07002122Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2123 DataType::Type type,
2124 bool is_string_char_at,
2125 uint32_t peeling) {
2126 // Combine the alignment and hidden offset that is guaranteed by
2127 // the Android runtime with a known starting index adjusted as bytes.
2128 int64_t value = 0;
2129 if (IsInt64AndGet(offset, /*out*/ &value)) {
2130 uint32_t start_offset =
2131 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2132 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2133 }
2134 // Otherwise, the Android runtime guarantees at least natural alignment.
2135 return Alignment(DataType::Size(type), 0);
2136}
2137
2138void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2139 const ArrayReference* peeling_candidate) {
2140 // Current heuristic: pick the best static loop peeling factor, if any,
2141 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2142 uint32_t max_vote = 0;
2143 for (int32_t i = 0; i < 16; i++) {
2144 if (peeling_votes[i] > max_vote) {
2145 max_vote = peeling_votes[i];
2146 vector_static_peeling_factor_ = i;
2147 }
2148 }
2149 if (max_vote == 0) {
2150 vector_dynamic_peeling_candidate_ = peeling_candidate;
2151 }
2152}
2153
2154uint32_t HLoopOptimization::MaxNumberPeeled() {
2155 if (vector_dynamic_peeling_candidate_ != nullptr) {
2156 return vector_length_ - 1u; // worst-case
2157 }
2158 return vector_static_peeling_factor_; // known exactly
2159}
2160
Aart Bik14a68b42017-06-08 14:06:58 -07002161bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002162 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002163 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002164 // TODO: trip count is really unsigned entity, provided the guarding test
2165 // is satisfied; deal with this more carefully later
2166 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002167 if (vector_length_ == 0) {
2168 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002169 } else if (trip_count < 0) {
2170 return false; // guard against non-taken/large
2171 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002172 return false; // insufficient iterations
2173 }
2174 return true;
2175}
2176
Artem Serovf26bb6c2017-09-01 10:59:03 +01002177static constexpr uint32_t ARM64_SIMD_MAXIMUM_UNROLL_FACTOR = 8;
2178static constexpr uint32_t ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE = 50;
2179
Aart Bik14a68b42017-06-08 14:06:58 -07002180uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002181 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002182 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00002183 case InstructionSet::kArm64: {
Aart Bik521b50f2017-09-09 10:44:45 -07002184 // Don't unroll with insufficient iterations.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002185 // TODO: Unroll loops with unknown trip count.
Aart Bik521b50f2017-09-09 10:44:45 -07002186 DCHECK_NE(vector_length_, 0u);
Aart Bik38a3f212017-10-20 17:02:21 -07002187 if (trip_count < (2 * vector_length_ + max_peel)) {
Aart Bik521b50f2017-09-09 10:44:45 -07002188 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002189 }
Aart Bik521b50f2017-09-09 10:44:45 -07002190 // Don't unroll for large loop body size.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002191 uint32_t instruction_count = block->GetInstructions().CountSize();
Aart Bik521b50f2017-09-09 10:44:45 -07002192 if (instruction_count >= ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE) {
2193 return kNoUnrollingFactor;
2194 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002195 // Find a beneficial unroll factor with the following restrictions:
2196 // - At least one iteration of the transformed loop should be executed.
2197 // - The loop body shouldn't be "too big" (heuristic).
2198 uint32_t uf1 = ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE / instruction_count;
Aart Bik38a3f212017-10-20 17:02:21 -07002199 uint32_t uf2 = (trip_count - max_peel) / vector_length_;
Artem Serovf26bb6c2017-09-01 10:59:03 +01002200 uint32_t unroll_factor =
2201 TruncToPowerOfTwo(std::min({uf1, uf2, ARM64_SIMD_MAXIMUM_UNROLL_FACTOR}));
2202 DCHECK_GE(unroll_factor, 1u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002203 return unroll_factor;
Aart Bik14a68b42017-06-08 14:06:58 -07002204 }
Vladimir Marko33bff252017-11-01 14:35:42 +00002205 case InstructionSet::kX86:
2206 case InstructionSet::kX86_64:
Aart Bik14a68b42017-06-08 14:06:58 -07002207 default:
Aart Bik521b50f2017-09-09 10:44:45 -07002208 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002209 }
2210}
2211
2212//
Aart Bikf8f5a162017-02-06 15:35:29 -08002213// Helpers.
2214//
2215
2216bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002217 // Start with empty phi induction.
2218 iset_->clear();
2219
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002220 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2221 // smart enough to follow strongly connected components (and it's probably not worth
2222 // it to make it so). See b/33775412.
2223 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2224 return false;
2225 }
Aart Bikb29f6842017-07-28 15:58:41 -07002226
2227 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002228 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2229 if (set != nullptr) {
2230 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002231 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002232 // each instruction is removable and, when restrict uses are requested, other than for phi,
2233 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002234 if (!i->IsInBlock()) {
2235 continue;
2236 } else if (!i->IsRemovable()) {
2237 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002238 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002239 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002240 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2241 if (set->find(use.GetUser()) == set->end()) {
2242 return false;
2243 }
2244 }
2245 }
Aart Bike3dedc52016-11-02 17:50:27 -07002246 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002247 }
Aart Bikcc42be02016-10-20 16:14:16 -07002248 return true;
2249 }
2250 return false;
2251}
2252
Aart Bikb29f6842017-07-28 15:58:41 -07002253bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002254 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002255 // Only unclassified phi cycles are candidates for reductions.
2256 if (induction_range_.IsClassified(phi)) {
2257 return false;
2258 }
2259 // Accept operations like x = x + .., provided that the phi and the reduction are
2260 // used exactly once inside the loop, and by each other.
2261 HInputsRef inputs = phi->GetInputs();
2262 if (inputs.size() == 2) {
2263 HInstruction* reduction = inputs[1];
2264 if (HasReductionFormat(reduction, phi)) {
2265 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002266 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002267 bool single_use_inside_loop =
2268 // Reduction update only used by phi.
2269 reduction->GetUses().HasExactlyOneElement() &&
2270 !reduction->HasEnvironmentUses() &&
2271 // Reduction update is only use of phi inside the loop.
2272 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2273 iset_->size() == 1;
2274 iset_->clear(); // leave the way you found it
2275 if (single_use_inside_loop) {
2276 // Link reduction back, and start recording feed value.
2277 reductions_->Put(reduction, phi);
2278 reductions_->Put(phi, phi->InputAt(0));
2279 return true;
2280 }
2281 }
2282 }
2283 return false;
2284}
2285
2286bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2287 // Start with empty phi induction and reductions.
2288 iset_->clear();
2289 reductions_->clear();
2290
2291 // Scan the phis to find the following (the induction structure has already
2292 // been optimized, so we don't need to worry about trivial cases):
2293 // (1) optional reductions in loop,
2294 // (2) the main induction, used in loop control.
2295 HPhi* phi = nullptr;
2296 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2297 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2298 continue;
2299 } else if (phi == nullptr) {
2300 // Found the first candidate for main induction.
2301 phi = it.Current()->AsPhi();
2302 } else {
2303 return false;
2304 }
2305 }
2306
2307 // Then test for a typical loopheader:
2308 // s: SuspendCheck
2309 // c: Condition(phi, bound)
2310 // i: If(c)
2311 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002312 HInstruction* s = block->GetFirstInstruction();
2313 if (s != nullptr && s->IsSuspendCheck()) {
2314 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002315 if (c != nullptr &&
2316 c->IsCondition() &&
2317 c->GetUses().HasExactlyOneElement() && // only used for termination
2318 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002319 HInstruction* i = c->GetNext();
2320 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2321 iset_->insert(c);
2322 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002323 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002324 return true;
2325 }
2326 }
2327 }
2328 }
2329 return false;
2330}
2331
2332bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002333 if (!block->GetPhis().IsEmpty()) {
2334 return false;
2335 }
2336 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2337 HInstruction* instruction = it.Current();
2338 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2339 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002340 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002341 }
2342 return true;
2343}
2344
2345bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2346 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002347 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002348 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2349 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2350 return true;
2351 }
Aart Bikcc42be02016-10-20 16:14:16 -07002352 }
2353 return false;
2354}
2355
Aart Bik482095d2016-10-10 15:39:10 -07002356bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002357 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002358 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002359 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002360 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002361 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2362 HInstruction* user = use.GetUser();
2363 if (iset_->find(user) == iset_->end()) { // not excluded?
2364 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002365 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002366 // If collect_loop_uses is set, simply keep adding those uses to the set.
2367 // Otherwise, reject uses inside the loop that were not already in the set.
2368 if (collect_loop_uses) {
2369 iset_->insert(user);
2370 continue;
2371 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002372 return false;
2373 }
2374 ++*use_count;
2375 }
2376 }
2377 return true;
2378}
2379
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002380bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2381 HInstruction* instruction,
2382 HBasicBlock* block) {
2383 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002384 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002385 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002386 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002387 const HUseList<HInstruction*>& uses = instruction->GetUses();
2388 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2389 HInstruction* user = it->GetUser();
2390 size_t index = it->GetIndex();
2391 ++it; // increment before replacing
2392 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002393 if (kIsDebugBuild) {
2394 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2395 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2396 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2397 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002398 user->ReplaceInput(replacement, index);
2399 induction_range_.Replace(user, instruction, replacement); // update induction
2400 }
2401 }
Aart Bikb29f6842017-07-28 15:58:41 -07002402 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002403 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2404 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2405 HEnvironment* user = it->GetUser();
2406 size_t index = it->GetIndex();
2407 ++it; // increment before replacing
2408 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002409 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002410 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002411 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2412 user->RemoveAsUserOfInput(index);
2413 user->SetRawEnvAt(index, replacement);
2414 replacement->AddEnvUseAt(user, index);
2415 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002416 }
2417 }
Aart Bik807868e2016-11-03 17:51:43 -07002418 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002419 }
Aart Bik807868e2016-11-03 17:51:43 -07002420 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002421}
2422
Aart Bikf8f5a162017-02-06 15:35:29 -08002423bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2424 HInstruction* instruction,
2425 HBasicBlock* block,
2426 bool collect_loop_uses) {
2427 // Assigning the last value is always successful if there are no uses.
2428 // Otherwise, it succeeds in a no early-exit loop by generating the
2429 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002430 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002431 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2432 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002433 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002434}
2435
Aart Bik6b69e0a2017-01-11 10:20:43 -08002436void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2437 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2438 HInstruction* instruction = i.Current();
2439 if (instruction->IsDeadAndRemovable()) {
2440 simplified_ = true;
2441 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2442 }
2443 }
2444}
2445
Aart Bik14a68b42017-06-08 14:06:58 -07002446bool HLoopOptimization::CanRemoveCycle() {
2447 for (HInstruction* i : *iset_) {
2448 // We can never remove instructions that have environment
2449 // uses when we compile 'debuggable'.
2450 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2451 return false;
2452 }
2453 // A deoptimization should never have an environment input removed.
2454 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2455 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2456 return false;
2457 }
2458 }
2459 }
2460 return true;
2461}
2462
Aart Bik281c6812016-08-26 11:31:48 -07002463} // namespace art