blob: 1ce3524bd6e02bd000187d87b30e2d9487b97d6b [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
Artem Serov121f2032017-10-23 19:19:06 +010036// Enables scalar loop unrolling in the loop optimizer.
Artem Serov72411e62017-10-19 16:18:07 +010037static constexpr bool kEnableScalarPeelingUnrolling = false;
Aart Bik521b50f2017-09-09 10:44:45 -070038
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) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000230 DCHECK(a != nullptr && b != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700231 // Look for a matching sign extension.
232 DataType::Type stype = HVecOperation::ToSignedType(type);
233 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700234 *is_unsigned = false;
235 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700236 }
237 // Look for a matching zero extension.
238 DataType::Type utype = HVecOperation::ToUnsignedType(type);
239 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700240 *is_unsigned = true;
241 return true;
242 }
243 return false;
244}
245
246// As above, single operand.
247static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100248 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700249 /*out*/ HInstruction** r,
250 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000251 DCHECK(a != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700252 // Look for a matching sign extension.
253 DataType::Type stype = HVecOperation::ToSignedType(type);
254 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700255 *is_unsigned = false;
256 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700257 }
258 // Look for a matching zero extension.
259 DataType::Type utype = HVecOperation::ToUnsignedType(type);
260 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700261 *is_unsigned = true;
262 return true;
263 }
264 return false;
265}
266
Aart Bikdbbac8f2017-09-01 13:06:08 -0700267// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700268static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100269 DCHECK(DataType::IsIntegralType(other_type));
270 DCHECK(DataType::IsIntegralType(vector_type));
271 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
272 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700273}
274
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000275// Detect up to two added operands a and b and an acccumulated constant c.
276static bool IsAddConst(HInstruction* instruction,
277 /*out*/ HInstruction** a,
278 /*out*/ HInstruction** b,
279 /*out*/ int64_t* c,
280 int32_t depth = 8) { // don't search too deep
Aart Bik5f805002017-05-16 16:42:41 -0700281 int64_t value = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000282 // Enter add/sub while still within reasonable depth.
283 if (depth > 0) {
284 if (instruction->IsAdd()) {
285 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1) &&
286 IsAddConst(instruction->InputAt(1), a, b, c, depth - 1);
287 } else if (instruction->IsSub() &&
288 IsInt64AndGet(instruction->InputAt(1), &value)) {
289 *c -= value;
290 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1);
291 }
292 }
293 // Otherwise, deal with leaf nodes.
Aart Bik5f805002017-05-16 16:42:41 -0700294 if (IsInt64AndGet(instruction, &value)) {
295 *c += value;
296 return true;
Aart Bik5f805002017-05-16 16:42:41 -0700297 } else if (*a == nullptr) {
298 *a = instruction;
299 return true;
300 } else if (*b == nullptr) {
301 *b = instruction;
302 return true;
303 }
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000304 return false; // too many operands
Aart Bik5f805002017-05-16 16:42:41 -0700305}
306
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000307// Detect a + b + c with optional constant c.
308static bool IsAddConst2(HGraph* graph,
309 HInstruction* instruction,
310 /*out*/ HInstruction** a,
311 /*out*/ HInstruction** b,
312 /*out*/ int64_t* c) {
313 if (IsAddConst(instruction, a, b, c) && *a != nullptr) {
314 if (*b == nullptr) {
315 // Constant is usually already present, unless accumulated.
316 *b = graph->GetConstant(instruction->GetType(), (*c));
317 *c = 0;
Aart Bik5f805002017-05-16 16:42:41 -0700318 }
Aart Bik5f805002017-05-16 16:42:41 -0700319 return true;
320 }
321 return false;
322}
323
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000324// Detect a direct a - b or a hidden a - (-c).
325static bool IsSubConst2(HGraph* graph,
326 HInstruction* instruction,
327 /*out*/ HInstruction** a,
328 /*out*/ HInstruction** b) {
329 int64_t c = 0;
330 if (instruction->IsSub()) {
331 *a = instruction->InputAt(0);
332 *b = instruction->InputAt(1);
333 return true;
334 } else if (IsAddConst(instruction, a, b, &c) && *a != nullptr && *b == nullptr) {
335 // Constant for the hidden subtraction.
336 *b = graph->GetConstant(instruction->GetType(), -c);
337 return true;
Aart Bikdf011c32017-09-28 12:53:04 -0700338 }
339 return false;
340}
341
Aart Bikb29f6842017-07-28 15:58:41 -0700342// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700343// x = x_phi + ..
344// x = x_phi - ..
Aart Bikb29f6842017-07-28 15:58:41 -0700345static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
Aart Bik3f08e9b2018-05-01 13:42:03 -0700346 if (reduction->IsAdd()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700347 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
348 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700349 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700350 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700351 }
352 return false;
353}
354
Aart Bikdbbac8f2017-09-01 13:06:08 -0700355// Translates vector operation to reduction kind.
356static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
357 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700358 return HVecReduce::kSum;
Aart Bik0148de42017-09-05 09:25:01 -0700359 }
Aart Bik38a3f212017-10-20 17:02:21 -0700360 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700361 UNREACHABLE();
362}
363
Aart Bikf8f5a162017-02-06 15:35:29 -0800364// Test vector restrictions.
365static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
366 return (restrictions & tested) != 0;
367}
368
Aart Bikf3e61ee2017-04-12 17:09:20 -0700369// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800370static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
371 DCHECK(block != nullptr);
372 DCHECK(instruction != nullptr);
373 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
374 return instruction;
375}
376
Artem Serov21c7e6f2017-07-27 16:04:42 +0100377// Check that instructions from the induction sets are fully removed: have no uses
378// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100379static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100380 for (HInstruction* instr : *iset) {
381 if (instr->GetBlock() != nullptr ||
382 !instr->GetUses().empty() ||
383 !instr->GetEnvUses().empty() ||
384 HasEnvironmentUsedByOthers(instr)) {
385 return false;
386 }
387 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100388 return true;
389}
390
Artem Serov72411e62017-10-19 16:18:07 +0100391// Tries to statically evaluate condition of the specified "HIf" for other condition checks.
392static void TryToEvaluateIfCondition(HIf* instruction, HGraph* graph) {
393 HInstruction* cond = instruction->InputAt(0);
394
395 // If a condition 'cond' is evaluated in an HIf instruction then in the successors of the
396 // IF_BLOCK we statically know the value of the condition 'cond' (TRUE in TRUE_SUCC, FALSE in
397 // FALSE_SUCC). Using that we can replace another evaluation (use) EVAL of the same 'cond'
398 // with TRUE value (FALSE value) if every path from the ENTRY_BLOCK to EVAL_BLOCK contains the
399 // edge HIF_BLOCK->TRUE_SUCC (HIF_BLOCK->FALSE_SUCC).
400 // if (cond) { if(cond) {
401 // if (cond) {} if (1) {}
402 // } else { =======> } else {
403 // if (cond) {} if (0) {}
404 // } }
405 if (!cond->IsConstant()) {
406 HBasicBlock* true_succ = instruction->IfTrueSuccessor();
407 HBasicBlock* false_succ = instruction->IfFalseSuccessor();
408
409 DCHECK_EQ(true_succ->GetPredecessors().size(), 1u);
410 DCHECK_EQ(false_succ->GetPredecessors().size(), 1u);
411
412 const HUseList<HInstruction*>& uses = cond->GetUses();
413 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
414 HInstruction* user = it->GetUser();
415 size_t index = it->GetIndex();
416 HBasicBlock* user_block = user->GetBlock();
417 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
418 ++it;
419 if (true_succ->Dominates(user_block)) {
420 user->ReplaceInput(graph->GetIntConstant(1), index);
421 } else if (false_succ->Dominates(user_block)) {
422 user->ReplaceInput(graph->GetIntConstant(0), index);
423 }
424 }
425 }
426}
427
Aart Bik281c6812016-08-26 11:31:48 -0700428//
Aart Bikb29f6842017-07-28 15:58:41 -0700429// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700430//
431
432HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800433 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700434 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800435 OptimizingCompilerStats* stats,
436 const char* name)
437 : HOptimization(graph, name, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800438 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700439 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700440 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100441 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700442 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700443 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700444 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700445 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800446 simplified_(false),
447 vector_length_(0),
448 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700449 vector_static_peeling_factor_(0),
450 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700451 vector_runtime_test_a_(nullptr),
452 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700453 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100454 vector_permanent_map_(nullptr),
455 vector_mode_(kSequential),
456 vector_preheader_(nullptr),
457 vector_header_(nullptr),
458 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100459 vector_index_(nullptr),
460 arch_loop_helper_(ArchDefaultLoopHelper::Create(compiler_driver_ != nullptr
461 ? compiler_driver_->GetInstructionSet()
462 : InstructionSet::kNone,
463 global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700464}
465
Aart Bik24773202018-04-26 10:28:51 -0700466bool HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800467 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700468 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800469 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik24773202018-04-26 10:28:51 -0700470 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700471 }
472
Vladimir Markoca6fff82017-10-03 14:49:14 +0100473 // Phase-local allocator.
474 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700475 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100476
Aart Bik96202302016-10-04 17:33:56 -0700477 // Perform loop optimizations.
Aart Bik24773202018-04-26 10:28:51 -0700478 bool didLoopOpt = LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800479 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800480 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800481 }
482
Aart Bik96202302016-10-04 17:33:56 -0700483 // Detach.
484 loop_allocator_ = nullptr;
485 last_loop_ = top_loop_ = nullptr;
Aart Bik24773202018-04-26 10:28:51 -0700486
487 return didLoopOpt;
Aart Bik96202302016-10-04 17:33:56 -0700488}
489
Aart Bikb29f6842017-07-28 15:58:41 -0700490//
491// Loop setup and traversal.
492//
493
Aart Bik24773202018-04-26 10:28:51 -0700494bool HLoopOptimization::LocalRun() {
495 bool didLoopOpt = false;
Aart Bik96202302016-10-04 17:33:56 -0700496 // Build the linear order using the phase-local allocator. This step enables building
497 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100498 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
499 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700500
Aart Bik281c6812016-08-26 11:31:48 -0700501 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700502 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700503 if (block->IsLoopHeader()) {
504 AddLoop(block->GetLoopInformation());
505 }
506 }
Aart Bik96202302016-10-04 17:33:56 -0700507
Aart Bik8c4a8542016-10-06 11:36:57 -0700508 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800509 // temporary data structures using the phase-local allocator. All new HIR
510 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700511 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100512 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
513 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700514 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100515 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
516 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800517 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100518 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700519 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800520 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700521 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700522 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800523 vector_refs_ = &refs;
524 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700525 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800526 // Traverse.
Aart Bik24773202018-04-26 10:28:51 -0700527 didLoopOpt = TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800528 // Detach.
529 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700530 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800531 vector_refs_ = nullptr;
532 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700533 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700534 }
Aart Bik24773202018-04-26 10:28:51 -0700535 return didLoopOpt;
Aart Bik281c6812016-08-26 11:31:48 -0700536}
537
538void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
539 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800540 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700541 if (last_loop_ == nullptr) {
542 // First loop.
543 DCHECK(top_loop_ == nullptr);
544 last_loop_ = top_loop_ = node;
545 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
546 // Inner loop.
547 node->outer = last_loop_;
548 DCHECK(last_loop_->inner == nullptr);
549 last_loop_ = last_loop_->inner = node;
550 } else {
551 // Subsequent loop.
552 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
553 last_loop_ = last_loop_->outer;
554 }
555 node->outer = last_loop_->outer;
556 node->previous = last_loop_;
557 DCHECK(last_loop_->next == nullptr);
558 last_loop_ = last_loop_->next = node;
559 }
560}
561
562void HLoopOptimization::RemoveLoop(LoopNode* node) {
563 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700564 DCHECK(node->inner == nullptr);
565 if (node->previous != nullptr) {
566 // Within sequence.
567 node->previous->next = node->next;
568 if (node->next != nullptr) {
569 node->next->previous = node->previous;
570 }
571 } else {
572 // First of sequence.
573 if (node->outer != nullptr) {
574 node->outer->inner = node->next;
575 } else {
576 top_loop_ = node->next;
577 }
578 if (node->next != nullptr) {
579 node->next->outer = node->outer;
580 node->next->previous = nullptr;
581 }
582 }
Aart Bik281c6812016-08-26 11:31:48 -0700583}
584
Aart Bikb29f6842017-07-28 15:58:41 -0700585bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
586 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700587 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700588 // Visit inner loops first. Recompute induction information for this
589 // loop if the induction of any inner loop has changed.
590 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700591 induction_range_.ReVisit(node->loop_info);
Aart Bika8360cd2018-05-02 16:07:51 -0700592 changed = true;
Aart Bik482095d2016-10-10 15:39:10 -0700593 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800594 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800595 // Note that since each simplification consists of eliminating code (without
596 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800597 do {
598 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800599 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800600 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700601 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800602 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800603 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700604 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700605 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700606 }
Aart Bik281c6812016-08-26 11:31:48 -0700607 }
Aart Bikb29f6842017-07-28 15:58:41 -0700608 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700609}
610
Aart Bikf8f5a162017-02-06 15:35:29 -0800611//
612// Optimization.
613//
614
Aart Bik281c6812016-08-26 11:31:48 -0700615void HLoopOptimization::SimplifyInduction(LoopNode* node) {
616 HBasicBlock* header = node->loop_info->GetHeader();
617 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700618 // Scan the phis in the header to find opportunities to simplify an induction
619 // cycle that is only used outside the loop. Replace these uses, if any, with
620 // the last value and remove the induction cycle.
621 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
622 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700623 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
624 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800625 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
626 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700627 // Note that it's ok to have replaced uses after the loop with the last value, without
628 // being able to remove the cycle. Environment uses (which are the reason we may not be
629 // able to remove the cycle) within the loop will still hold the right value. We must
630 // have tried first, however, to replace outside uses.
631 if (CanRemoveCycle()) {
632 simplified_ = true;
633 for (HInstruction* i : *iset_) {
634 RemoveFromCycle(i);
635 }
636 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700637 }
Aart Bik482095d2016-10-10 15:39:10 -0700638 }
639 }
640}
641
642void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800643 // Iterate over all basic blocks in the loop-body.
644 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
645 HBasicBlock* block = it.Current();
646 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800647 RemoveDeadInstructions(block->GetPhis());
648 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800649 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800650 if (block->GetPredecessors().size() == 1 &&
651 block->GetSuccessors().size() == 1 &&
652 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800653 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800654 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800655 } else if (block->GetSuccessors().size() == 2) {
656 // Trivial if block can be bypassed to either branch.
657 HBasicBlock* succ0 = block->GetSuccessors()[0];
658 HBasicBlock* succ1 = block->GetSuccessors()[1];
659 HBasicBlock* meet0 = nullptr;
660 HBasicBlock* meet1 = nullptr;
661 if (succ0 != succ1 &&
662 IsGotoBlock(succ0, &meet0) &&
663 IsGotoBlock(succ1, &meet1) &&
664 meet0 == meet1 && // meets again
665 meet0 != block && // no self-loop
666 meet0->GetPhis().IsEmpty()) { // not used for merging
667 simplified_ = true;
668 succ0->DisconnectAndDelete();
669 if (block->Dominates(meet0)) {
670 block->RemoveDominatedBlock(meet0);
671 succ1->AddDominatedBlock(meet0);
672 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700673 }
Aart Bik482095d2016-10-10 15:39:10 -0700674 }
Aart Bik281c6812016-08-26 11:31:48 -0700675 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800676 }
Aart Bik281c6812016-08-26 11:31:48 -0700677}
678
Artem Serov121f2032017-10-23 19:19:06 +0100679bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700680 HBasicBlock* header = node->loop_info->GetHeader();
681 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700682 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800683 int64_t trip_count = 0;
684 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700685 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700686 }
Aart Bik281c6812016-08-26 11:31:48 -0700687 // Ensure there is only a single loop-body (besides the header).
688 HBasicBlock* body = nullptr;
689 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
690 if (it.Current() != header) {
691 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700692 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700693 }
694 body = it.Current();
695 }
696 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700697 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700698 // Ensure there is only a single exit point.
699 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700700 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700701 }
702 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
703 ? header->GetSuccessors()[1]
704 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700705 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700706 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700707 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700708 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800709 // Detect either an empty loop (no side effects other than plain iteration) or
710 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
711 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700712 HPhi* main_phi = nullptr;
713 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800714 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700715 if (reductions_->empty() && // TODO: possible with some effort
716 (is_empty || trip_count == 1) &&
717 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800718 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800719 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700720 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800721 preheader->MergeInstructionsWith(body);
722 }
723 body->DisconnectAndDelete();
724 exit->RemovePredecessor(header);
725 header->RemoveSuccessor(exit);
726 header->RemoveDominatedBlock(exit);
727 header->DisconnectAndDelete();
728 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800729 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800730 preheader->AddDominatedBlock(exit);
731 exit->SetDominator(preheader);
732 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700733 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800734 }
735 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800736 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700737 if (kEnableVectorization &&
738 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700739 ShouldVectorize(node, body, trip_count) &&
740 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
741 Vectorize(node, body, exit, trip_count);
742 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700743 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700744 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800745 }
Aart Bikb29f6842017-07-28 15:58:41 -0700746 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800747}
748
Artem Serov121f2032017-10-23 19:19:06 +0100749bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
750 return TryOptimizeInnerLoopFinite(node) ||
Artem Serov72411e62017-10-19 16:18:07 +0100751 TryPeelingForLoopInvariantExitsElimination(node) ||
Artem Serov121f2032017-10-23 19:19:06 +0100752 TryUnrollingForBranchPenaltyReduction(node);
753}
754
Artem Serov121f2032017-10-23 19:19:06 +0100755
Artem Serov121f2032017-10-23 19:19:06 +0100756
757//
758// Loop unrolling: generic part methods.
759//
760
Artem Serov72411e62017-10-19 16:18:07 +0100761bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopNode* node) {
Artem Serov121f2032017-10-23 19:19:06 +0100762 // Don't run peeling/unrolling if compiler_driver_ is nullptr (i.e., running under tests)
763 // as InstructionSet is needed.
Artem Serov72411e62017-10-19 16:18:07 +0100764 if (!kEnableScalarPeelingUnrolling || compiler_driver_ == nullptr) {
Artem Serov121f2032017-10-23 19:19:06 +0100765 return false;
766 }
767
Artem Serov72411e62017-10-19 16:18:07 +0100768 HLoopInformation* loop_info = node->loop_info;
Artem Serov121f2032017-10-23 19:19:06 +0100769 int64_t trip_count = 0;
770 // Only unroll loops with a known tripcount.
771 if (!induction_range_.HasKnownTripCount(loop_info, &trip_count)) {
772 return false;
773 }
774
775 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(loop_info, trip_count);
776 if (unrolling_factor == kNoUnrollingFactor) {
777 return false;
778 }
779
780 LoopAnalysisInfo loop_analysis_info(loop_info);
781 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &loop_analysis_info);
782
783 // Check "IsLoopClonable" last as it can be time-consuming.
Artem Serov72411e62017-10-19 16:18:07 +0100784 if (arch_loop_helper_->IsLoopTooBigForScalarPeelingUnrolling(&loop_analysis_info) ||
Artem Serov121f2032017-10-23 19:19:06 +0100785 (loop_analysis_info.GetNumberOfExits() > 1) ||
786 loop_analysis_info.HasInstructionsPreventingScalarUnrolling() ||
787 !PeelUnrollHelper::IsLoopClonable(loop_info)) {
788 return false;
789 }
790
791 // TODO: support other unrolling factors.
792 DCHECK_EQ(unrolling_factor, 2u);
793
794 // Perform unrolling.
Artem Serov72411e62017-10-19 16:18:07 +0100795 PeelUnrollSimpleHelper helper(loop_info);
796 helper.DoUnrolling();
Artem Serov121f2032017-10-23 19:19:06 +0100797
798 // Remove the redundant loop check after unrolling.
Artem Serov72411e62017-10-19 16:18:07 +0100799 HIf* copy_hif =
800 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
Artem Serov121f2032017-10-23 19:19:06 +0100801 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
802 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
803
804 return true;
805}
806
Artem Serov72411e62017-10-19 16:18:07 +0100807bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopNode* node) {
808 // Don't run peeling/unrolling if compiler_driver_ is nullptr (i.e., running under tests)
809 // as InstructionSet is needed.
810 if (!kEnableScalarPeelingUnrolling || compiler_driver_ == nullptr) {
811 return false;
812 }
813
814 HLoopInformation* loop_info = node->loop_info;
815 // Check 'IsLoopClonable' the last as it might be time-consuming.
816 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
817 return false;
818 }
819
820 LoopAnalysisInfo loop_analysis_info(loop_info);
821 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &loop_analysis_info);
822
823 // Check "IsLoopClonable" last as it can be time-consuming.
824 if (arch_loop_helper_->IsLoopTooBigForScalarPeelingUnrolling(&loop_analysis_info) ||
825 loop_analysis_info.HasInstructionsPreventingScalarPeeling() ||
826 !LoopAnalysis::HasLoopAtLeastOneInvariantExit(loop_info) ||
827 !PeelUnrollHelper::IsLoopClonable(loop_info)) {
828 return false;
829 }
830
831 // Perform peeling.
832 PeelUnrollSimpleHelper helper(loop_info);
833 helper.DoPeeling();
834
835 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
836 for (auto entry : *hir_map) {
837 HInstruction* copy = entry.second;
838 if (copy->IsIf()) {
839 TryToEvaluateIfCondition(copy->AsIf(), graph_);
840 }
841 }
842
843 return true;
844}
845
Aart Bikf8f5a162017-02-06 15:35:29 -0800846//
847// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
848// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
849// Intel Press, June, 2004 (http://www.aartbik.com/).
850//
851
Aart Bik14a68b42017-06-08 14:06:58 -0700852bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800853 // Reset vector bookkeeping.
854 vector_length_ = 0;
855 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700856 vector_static_peeling_factor_ = 0;
857 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800858 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800859 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800860
861 // Phis in the loop-body prevent vectorization.
862 if (!block->GetPhis().IsEmpty()) {
863 return false;
864 }
865
866 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
867 // occurrence, which allows passing down attributes down the use tree.
868 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
869 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
870 return false; // failure to vectorize a left-hand-side
871 }
872 }
873
Aart Bik38a3f212017-10-20 17:02:21 -0700874 // Prepare alignment analysis:
875 // (1) find desired alignment (SIMD vector size in bytes).
876 // (2) initialize static loop peeling votes (peeling factor that will
877 // make one particular reference aligned), never to exceed (1).
878 // (3) variable to record how many references share same alignment.
879 // (4) variable to record suitable candidate for dynamic loop peeling.
880 uint32_t desired_alignment = GetVectorSizeInBytes();
881 DCHECK_LE(desired_alignment, 16u);
882 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
883 uint32_t max_num_same_alignment = 0;
884 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800885
886 // Data dependence analysis. Find each pair of references with same type, where
887 // at least one is a write. Each such pair denotes a possible data dependence.
888 // This analysis exploits the property that differently typed arrays cannot be
889 // aliased, as well as the property that references either point to the same
890 // array or to two completely disjoint arrays, i.e., no partial aliasing.
891 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700892 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800893 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700894 uint32_t num_same_alignment = 0;
895 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800896 for (auto j = i; ++j != vector_refs_->end(); ) {
897 if (i->type == j->type && (i->lhs || j->lhs)) {
898 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
899 HInstruction* a = i->base;
900 HInstruction* b = j->base;
901 HInstruction* x = i->offset;
902 HInstruction* y = j->offset;
903 if (a == b) {
904 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
905 // Conservatively assume a loop-carried data dependence otherwise, and reject.
906 if (x != y) {
907 return false;
908 }
Aart Bik38a3f212017-10-20 17:02:21 -0700909 // Count the number of references that have the same alignment (since
910 // base and offset are the same) and where at least one is a write, so
911 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
912 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800913 } else {
914 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
915 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
916 // generating an explicit a != b disambiguation runtime test on the two references.
917 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700918 // To avoid excessive overhead, we only accept one a != b test.
919 if (vector_runtime_test_a_ == nullptr) {
920 // First test found.
921 vector_runtime_test_a_ = a;
922 vector_runtime_test_b_ = b;
923 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
924 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
925 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800926 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800927 }
928 }
929 }
930 }
Aart Bik38a3f212017-10-20 17:02:21 -0700931 // Update information for finding suitable alignment strategy:
932 // (1) update votes for static loop peeling,
933 // (2) update suitable candidate for dynamic loop peeling.
934 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
935 if (alignment.Base() >= desired_alignment) {
936 // If the array/string object has a known, sufficient alignment, use the
937 // initial offset to compute the static loop peeling vote (this always
938 // works, since elements have natural alignment).
939 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
940 uint32_t vote = (offset == 0)
941 ? 0
942 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
943 DCHECK_LT(vote, 16u);
944 ++peeling_votes[vote];
945 } else if (BaseAlignment() >= desired_alignment &&
946 num_same_alignment > max_num_same_alignment) {
947 // Otherwise, if the array/string object has a known, sufficient alignment
948 // for just the base but with an unknown offset, record the candidate with
949 // the most occurrences for dynamic loop peeling (again, the peeling always
950 // works, since elements have natural alignment).
951 max_num_same_alignment = num_same_alignment;
952 peeling_candidate = &(*i);
953 }
954 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -0800955
Aart Bik38a3f212017-10-20 17:02:21 -0700956 // Find a suitable alignment strategy.
957 SetAlignmentStrategy(peeling_votes, peeling_candidate);
958
959 // Does vectorization seem profitable?
960 if (!IsVectorizationProfitable(trip_count)) {
961 return false;
962 }
Aart Bik14a68b42017-06-08 14:06:58 -0700963
Aart Bikf8f5a162017-02-06 15:35:29 -0800964 // Success!
965 return true;
966}
967
968void HLoopOptimization::Vectorize(LoopNode* node,
969 HBasicBlock* block,
970 HBasicBlock* exit,
971 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800972 HBasicBlock* header = node->loop_info->GetHeader();
973 HBasicBlock* preheader = node->loop_info->GetPreHeader();
974
Aart Bik14a68b42017-06-08 14:06:58 -0700975 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +0100976 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
977 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -0700978 uint32_t chunk = vector_length_ * unroll;
979
Aart Bik38a3f212017-10-20 17:02:21 -0700980 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
981
Aart Bik14a68b42017-06-08 14:06:58 -0700982 // A cleanup loop is needed, at least, for any unknown trip count or
983 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -0700984 bool needs_cleanup = trip_count == 0 ||
985 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800986
987 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700988 HPhi* main_phi = nullptr;
989 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800990 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700991 vector_header_ = header;
992 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800993
Aart Bikdbbac8f2017-09-01 13:06:08 -0700994 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100995 DataType::Type induc_type = main_phi->GetType();
996 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
997 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700998
Aart Bik38a3f212017-10-20 17:02:21 -0700999 // Generate the trip count for static or dynamic loop peeling, if needed:
1000 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001001 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001002 if (vector_static_peeling_factor_ != 0) {
1003 // Static loop peeling for SIMD alignment (using the most suitable
1004 // fixed peeling factor found during prior alignment analysis).
1005 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1006 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1007 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1008 // Dynamic loop peeling for SIMD alignment (using the most suitable
1009 // candidate found during prior alignment analysis):
1010 // rem = offset % ALIGN; // adjusted as #elements
1011 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1012 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1013 uint32_t align = GetVectorSizeInBytes() >> shift;
1014 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1015 vector_dynamic_peeling_candidate_->is_string_char_at);
1016 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1017 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1018 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1019 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1020 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1021 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1022 induc_type, graph_->GetConstant(induc_type, align), rem));
1023 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1024 rem, graph_->GetConstant(induc_type, 0)));
1025 ptc = Insert(preheader, new (global_allocator_) HSelect(
1026 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1027 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001028 }
1029
1030 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001031 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001032 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001033 // vtc = stc - (stc - ptc) % chunk;
1034 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001035 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1036 HInstruction* vtc = stc;
1037 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001038 DCHECK(IsPowerOfTwo(chunk));
1039 HInstruction* diff = stc;
1040 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001041 if (trip_count == 0) {
1042 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1043 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1044 }
Aart Bik14a68b42017-06-08 14:06:58 -07001045 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1046 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001047 HInstruction* rem = Insert(
1048 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001049 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001050 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001051 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1052 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001053 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001054
1055 // Generate runtime disambiguation test:
1056 // vtc = a != b ? vtc : 0;
1057 if (vector_runtime_test_a_ != nullptr) {
1058 HInstruction* rt = Insert(
1059 preheader,
1060 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1061 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001062 new (global_allocator_)
1063 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001064 needs_cleanup = true;
1065 }
1066
Aart Bik38a3f212017-10-20 17:02:21 -07001067 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001068 // for ( ; i < ptc; i += 1)
1069 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001070 //
1071 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1072 // moved around during suspend checks, since all analysis was based on
1073 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001074 if (ptc != nullptr) {
1075 vector_mode_ = kSequential;
1076 GenerateNewLoop(node,
1077 block,
1078 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1079 vector_index_,
1080 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001081 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001082 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001083 }
1084
1085 // Generate vector loop, possibly further unrolled:
1086 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001087 // <vectorized-loop-body>
1088 vector_mode_ = kVector;
1089 GenerateNewLoop(node,
1090 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001091 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1092 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001093 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001094 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001095 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001096 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1097
1098 // Generate cleanup loop, if needed:
1099 // for ( ; i < stc; i += 1)
1100 // <loop-body>
1101 if (needs_cleanup) {
1102 vector_mode_ = kSequential;
1103 GenerateNewLoop(node,
1104 block,
1105 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001106 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001107 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001108 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001109 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001110 }
1111
Aart Bik0148de42017-09-05 09:25:01 -07001112 // Link reductions to their final uses.
1113 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1114 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001115 HInstruction* phi = i->first;
1116 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1117 // Deal with regular uses.
1118 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1119 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1120 }
1121 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001122 }
1123 }
1124
Aart Bikf8f5a162017-02-06 15:35:29 -08001125 // Remove the original loop by disconnecting the body block
1126 // and removing all instructions from the header.
1127 block->DisconnectAndDelete();
1128 while (!header->GetFirstInstruction()->IsGoto()) {
1129 header->RemoveInstruction(header->GetFirstInstruction());
1130 }
Aart Bikb29f6842017-07-28 15:58:41 -07001131
Aart Bik14a68b42017-06-08 14:06:58 -07001132 // Update loop hierarchy: the old header now resides in the same outer loop
1133 // as the old preheader. Note that we don't bother putting sequential
1134 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001135 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1136 node->loop_info = vloop;
1137}
1138
1139void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1140 HBasicBlock* block,
1141 HBasicBlock* new_preheader,
1142 HInstruction* lo,
1143 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001144 HInstruction* step,
1145 uint32_t unroll) {
1146 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001147 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001148 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001149 vector_preheader_ = new_preheader,
1150 vector_header_ = vector_preheader_->GetSingleSuccessor();
1151 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001152 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1153 kNoRegNumber,
1154 0,
1155 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001156 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001157 // for (i = lo; i < hi; i += step)
1158 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001159 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1160 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001161 vector_header_->AddInstruction(cond);
1162 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001163 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001164 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001165 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001166 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001167 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001168 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1169 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1170 DCHECK(vectorized_def);
1171 }
1172 // Generate body from the instruction map, but in original program order.
1173 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1174 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1175 auto i = vector_map_->find(it.Current());
1176 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1177 Insert(vector_body_, i->second);
1178 // Deal with instructions that need an environment, such as the scalar intrinsics.
1179 if (i->second->NeedsEnvironment()) {
1180 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1181 }
1182 }
1183 }
Aart Bik0148de42017-09-05 09:25:01 -07001184 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001185 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1186 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001187 }
Aart Bik0148de42017-09-05 09:25:01 -07001188 // Finalize phi inputs for the reductions (if any).
1189 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1190 if (!i->first->IsPhi()) {
1191 DCHECK(i->second->IsPhi());
1192 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1193 }
1194 }
Aart Bikb29f6842017-07-28 15:58:41 -07001195 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001196 phi->AddInput(lo);
1197 phi->AddInput(vector_index_);
1198 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001199}
1200
Aart Bikf8f5a162017-02-06 15:35:29 -08001201bool HLoopOptimization::VectorizeDef(LoopNode* node,
1202 HInstruction* instruction,
1203 bool generate_code) {
1204 // Accept a left-hand-side array base[index] for
1205 // (1) supported vector type,
1206 // (2) loop-invariant base,
1207 // (3) unit stride index,
1208 // (4) vectorizable right-hand-side value.
1209 uint64_t restrictions = kNone;
1210 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001211 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001212 HInstruction* base = instruction->InputAt(0);
1213 HInstruction* index = instruction->InputAt(1);
1214 HInstruction* value = instruction->InputAt(2);
1215 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001216 // For narrow types, explicit type conversion may have been
1217 // optimized way, so set the no hi bits restriction here.
1218 if (DataType::Size(type) <= 2) {
1219 restrictions |= kNoHiBits;
1220 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001221 if (TrySetVectorType(type, &restrictions) &&
1222 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001223 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001224 VectorizeUse(node, value, generate_code, type, restrictions)) {
1225 if (generate_code) {
1226 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001227 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001228 } else {
1229 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1230 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001231 return true;
1232 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001233 return false;
1234 }
Aart Bik0148de42017-09-05 09:25:01 -07001235 // Accept a left-hand-side reduction for
1236 // (1) supported vector type,
1237 // (2) vectorizable right-hand-side value.
1238 auto redit = reductions_->find(instruction);
1239 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001240 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001241 // Recognize SAD idiom or direct reduction.
1242 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1243 (TrySetVectorType(type, &restrictions) &&
1244 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001245 if (generate_code) {
1246 HInstruction* new_red = vector_map_->Get(instruction);
1247 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1248 vector_permanent_map_->Overwrite(redit->second, new_red);
1249 }
1250 return true;
1251 }
1252 return false;
1253 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001254 // Branch back okay.
1255 if (instruction->IsGoto()) {
1256 return true;
1257 }
1258 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1259 // Note that actual uses are inspected during right-hand-side tree traversal.
1260 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1261}
1262
Aart Bikf8f5a162017-02-06 15:35:29 -08001263bool HLoopOptimization::VectorizeUse(LoopNode* node,
1264 HInstruction* instruction,
1265 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001266 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001267 uint64_t restrictions) {
1268 // Accept anything for which code has already been generated.
1269 if (generate_code) {
1270 if (vector_map_->find(instruction) != vector_map_->end()) {
1271 return true;
1272 }
1273 }
1274 // Continue the right-hand-side tree traversal, passing in proper
1275 // types and vector restrictions along the way. During code generation,
1276 // all new nodes are drawn from the global allocator.
1277 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1278 // Accept invariant use, using scalar expansion.
1279 if (generate_code) {
1280 GenerateVecInv(instruction, type);
1281 }
1282 return true;
1283 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001284 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001285 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1286 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001287 return false;
1288 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001289 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001290 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001291 // (2) loop-invariant base,
1292 // (3) unit stride index,
1293 // (4) vectorizable right-hand-side value.
1294 HInstruction* base = instruction->InputAt(0);
1295 HInstruction* index = instruction->InputAt(1);
1296 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001297 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001298 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001299 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001300 if (generate_code) {
1301 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001302 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001303 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001304 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001305 }
1306 return true;
1307 }
Aart Bik0148de42017-09-05 09:25:01 -07001308 } else if (instruction->IsPhi()) {
1309 // Accept particular phi operations.
1310 if (reductions_->find(instruction) != reductions_->end()) {
1311 // Deal with vector restrictions.
1312 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1313 return false;
1314 }
1315 // Accept a reduction.
1316 if (generate_code) {
1317 GenerateVecReductionPhi(instruction->AsPhi());
1318 }
1319 return true;
1320 }
1321 // TODO: accept right-hand-side induction?
1322 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001323 } else if (instruction->IsTypeConversion()) {
1324 // Accept particular type conversions.
1325 HTypeConversion* conversion = instruction->AsTypeConversion();
1326 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001327 DataType::Type from = conversion->GetInputType();
1328 DataType::Type to = conversion->GetResultType();
1329 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001330 uint32_t size_vec = DataType::Size(type);
1331 uint32_t size_from = DataType::Size(from);
1332 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001333 // Accept an integral conversion
1334 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1335 // (1b) widening from at least vector type, and
1336 // (2) vectorizable operand.
1337 if ((size_to < size_from &&
1338 size_to == size_vec &&
1339 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1340 (size_to >= size_from &&
1341 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001342 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001343 if (generate_code) {
1344 if (vector_mode_ == kVector) {
1345 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1346 } else {
1347 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1348 }
1349 }
1350 return true;
1351 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001352 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001353 DCHECK_EQ(to, type);
1354 // Accept int to float conversion for
1355 // (1) supported int,
1356 // (2) vectorizable operand.
1357 if (TrySetVectorType(from, &restrictions) &&
1358 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1359 if (generate_code) {
1360 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1361 }
1362 return true;
1363 }
1364 }
1365 return false;
1366 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1367 // Accept unary operator for vectorizable operand.
1368 HInstruction* opa = instruction->InputAt(0);
1369 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1370 if (generate_code) {
1371 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1372 }
1373 return true;
1374 }
1375 } else if (instruction->IsAdd() || instruction->IsSub() ||
1376 instruction->IsMul() || instruction->IsDiv() ||
1377 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1378 // Deal with vector restrictions.
1379 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1380 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1381 return false;
1382 }
1383 // Accept binary operator for vectorizable operands.
1384 HInstruction* opa = instruction->InputAt(0);
1385 HInstruction* opb = instruction->InputAt(1);
1386 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1387 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1388 if (generate_code) {
1389 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1390 }
1391 return true;
1392 }
1393 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001394 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001395 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1396 return true;
1397 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001398 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001399 HInstruction* opa = instruction->InputAt(0);
1400 HInstruction* opb = instruction->InputAt(1);
1401 HInstruction* r = opa;
1402 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001403 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1404 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1405 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001406 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1407 // Shifts right need extra care to account for higher order bits.
1408 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1409 if (instruction->IsShr() &&
1410 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1411 return false; // reject, unless all operands are sign-extension narrower
1412 } else if (instruction->IsUShr() &&
1413 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1414 return false; // reject, unless all operands are zero-extension narrower
1415 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001416 }
1417 // Accept shift operator for vectorizable/invariant operands.
1418 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001419 DCHECK(r != nullptr);
1420 if (generate_code && vector_mode_ != kVector) { // de-idiom
1421 r = opa;
1422 }
Aart Bik50e20d52017-05-05 14:07:29 -07001423 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001424 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001425 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001426 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001427 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001428 if (0 <= distance && distance < max_distance) {
1429 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001430 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001431 }
1432 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001433 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001434 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001435 } else if (instruction->IsAbs()) {
1436 // Deal with vector restrictions.
1437 HInstruction* opa = instruction->InputAt(0);
1438 HInstruction* r = opa;
1439 bool is_unsigned = false;
1440 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1441 return false;
1442 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1443 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1444 return false; // reject, unless operand is sign-extension narrower
1445 }
1446 // Accept ABS(x) for vectorizable operand.
1447 DCHECK(r != nullptr);
1448 if (generate_code && vector_mode_ != kVector) { // de-idiom
1449 r = opa;
1450 }
1451 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1452 if (generate_code) {
1453 GenerateVecOp(instruction,
1454 vector_map_->Get(r),
1455 nullptr,
1456 HVecOperation::ToProperType(type, is_unsigned));
1457 }
1458 return true;
1459 }
Aart Bik281c6812016-08-26 11:31:48 -07001460 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001461 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001462}
1463
Aart Bik38a3f212017-10-20 17:02:21 -07001464uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1465 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001466 case InstructionSet::kArm:
1467 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001468 return 8; // 64-bit SIMD
1469 default:
1470 return 16; // 128-bit SIMD
1471 }
1472}
1473
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001474bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001475 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1476 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001477 case InstructionSet::kArm:
1478 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001479 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001480 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001481 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001482 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001483 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001484 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001485 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001486 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001487 case DataType::Type::kUint16:
1488 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001489 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001490 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001491 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001492 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001493 return TrySetVectorLength(2);
1494 default:
1495 break;
1496 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001497 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001498 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001499 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001500 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001501 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001502 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001503 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001504 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001505 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001506 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001507 case DataType::Type::kUint16:
1508 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001509 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001510 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001511 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001512 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001513 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001514 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001515 *restrictions |= kNoDiv | kNoMul;
Aart Bikf8f5a162017-02-06 15:35:29 -08001516 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001517 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001518 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001519 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001520 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001521 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001522 return TrySetVectorLength(2);
1523 default:
1524 return false;
1525 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001526 case InstructionSet::kX86:
1527 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001528 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001529 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1530 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001531 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001532 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001533 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001534 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001535 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001536 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001537 case DataType::Type::kUint16:
1538 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001539 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001540 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001541 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001542 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001543 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001544 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001545 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001546 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001547 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001548 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001549 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001550 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001551 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001552 return TrySetVectorLength(2);
1553 default:
1554 break;
1555 } // switch type
1556 }
1557 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001558 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001559 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1560 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001561 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001562 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001563 case DataType::Type::kInt8:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001564 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001565 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001566 case DataType::Type::kUint16:
1567 case DataType::Type::kInt16:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001568 *restrictions |= kNoDiv | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001569 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001570 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001571 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001572 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001573 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001574 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001575 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001576 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001577 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001578 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001579 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001580 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001581 return TrySetVectorLength(2);
1582 default:
1583 break;
1584 } // switch type
1585 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001586 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001587 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001588 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1589 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001590 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001591 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001592 case DataType::Type::kInt8:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001593 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001594 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001595 case DataType::Type::kUint16:
1596 case DataType::Type::kInt16:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001597 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001598 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001599 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001600 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001601 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001602 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001603 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001604 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001605 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001606 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001607 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001608 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001609 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001610 return TrySetVectorLength(2);
1611 default:
1612 break;
1613 } // switch type
1614 }
1615 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001616 default:
1617 return false;
1618 } // switch instruction set
1619}
1620
1621bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1622 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1623 // First time set?
1624 if (vector_length_ == 0) {
1625 vector_length_ = length;
1626 }
1627 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1628 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1629 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1630 return vector_length_ == length;
1631}
1632
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001633void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001634 if (vector_map_->find(org) == vector_map_->end()) {
1635 // In scalar code, just use a self pass-through for scalar invariants
1636 // (viz. expression remains itself).
1637 if (vector_mode_ == kSequential) {
1638 vector_map_->Put(org, org);
1639 return;
1640 }
1641 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001642 HInstruction* vector = nullptr;
1643 auto it = vector_permanent_map_->find(org);
1644 if (it != vector_permanent_map_->end()) {
1645 vector = it->second; // reuse during unrolling
1646 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001647 // Generates ReplicateScalar( (optional_type_conv) org ).
1648 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001649 DataType::Type input_type = input->GetType();
1650 if (type != input_type && (type == DataType::Type::kInt64 ||
1651 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001652 input = Insert(vector_preheader_,
1653 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1654 }
1655 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001656 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001657 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1658 }
1659 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001660 }
1661}
1662
1663void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1664 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001665 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001666 int64_t value = 0;
1667 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001668 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001669 if (org->IsPhi()) {
1670 Insert(vector_body_, subscript); // lacks layout placeholder
1671 }
1672 }
1673 vector_map_->Put(org, subscript);
1674 }
1675}
1676
1677void HLoopOptimization::GenerateVecMem(HInstruction* org,
1678 HInstruction* opa,
1679 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001680 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001681 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001682 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001683 HInstruction* vector = nullptr;
1684 if (vector_mode_ == kVector) {
1685 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001686 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001687 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001688 if (opb != nullptr) {
1689 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001690 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001691 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001692 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001693 vector = new (global_allocator_) HVecLoad(global_allocator_,
1694 base,
1695 opa,
1696 type,
1697 org->GetSideEffects(),
1698 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001699 is_string_char_at,
1700 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001701 }
Aart Bik38a3f212017-10-20 17:02:21 -07001702 // Known (forced/adjusted/original) alignment?
1703 if (vector_dynamic_peeling_candidate_ != nullptr) {
1704 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1705 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1706 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1707 vector->AsVecMemoryOperation()->SetAlignment( // forced
1708 Alignment(GetVectorSizeInBytes(), 0));
1709 }
1710 } else {
1711 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1712 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001713 }
1714 } else {
1715 // Scalar store or load.
1716 DCHECK(vector_mode_ == kSequential);
1717 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001718 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001719 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001720 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001721 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001722 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1723 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001724 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001725 }
1726 }
1727 vector_map_->Put(org, vector);
1728}
1729
Aart Bik0148de42017-09-05 09:25:01 -07001730void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1731 DCHECK(reductions_->find(phi) != reductions_->end());
1732 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1733 HInstruction* vector = nullptr;
1734 if (vector_mode_ == kSequential) {
1735 HPhi* new_phi = new (global_allocator_) HPhi(
1736 global_allocator_, kNoRegNumber, 0, phi->GetType());
1737 vector_header_->AddPhi(new_phi);
1738 vector = new_phi;
1739 } else {
1740 // Link vector reduction back to prior unrolled update, or a first phi.
1741 auto it = vector_permanent_map_->find(phi);
1742 if (it != vector_permanent_map_->end()) {
1743 vector = it->second;
1744 } else {
1745 HPhi* new_phi = new (global_allocator_) HPhi(
1746 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1747 vector_header_->AddPhi(new_phi);
1748 vector = new_phi;
1749 }
1750 }
1751 vector_map_->Put(phi, vector);
1752}
1753
1754void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1755 HInstruction* new_phi = vector_map_->Get(phi);
1756 HInstruction* new_init = reductions_->Get(phi);
1757 HInstruction* new_red = vector_map_->Get(reduction);
1758 // Link unrolled vector loop back to new phi.
1759 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1760 DCHECK(new_phi->IsVecOperation());
1761 }
1762 // Prepare the new initialization.
1763 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001764 // Generate a [initial, 0, .., 0] vector for add or
1765 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001766 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001767 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001768 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001769 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001770 if (kind == HVecReduce::ReductionKind::kSum) {
1771 new_init = Insert(vector_preheader_,
1772 new (global_allocator_) HVecSetScalars(global_allocator_,
1773 &new_init,
1774 type,
1775 vector_length,
1776 1,
1777 kNoDexPc));
1778 } else {
1779 new_init = Insert(vector_preheader_,
1780 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1781 new_init,
1782 type,
1783 vector_length,
1784 kNoDexPc));
1785 }
Aart Bik0148de42017-09-05 09:25:01 -07001786 } else {
1787 new_init = ReduceAndExtractIfNeeded(new_init);
1788 }
1789 // Set the phi inputs.
1790 DCHECK(new_phi->IsPhi());
1791 new_phi->AsPhi()->AddInput(new_init);
1792 new_phi->AsPhi()->AddInput(new_red);
1793 // New feed value for next phi (safe mutation in iteration).
1794 reductions_->find(phi)->second = new_phi;
1795}
1796
1797HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1798 if (instruction->IsPhi()) {
1799 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001800 if (HVecOperation::ReturnsSIMDValue(input)) {
1801 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001802 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001803 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001804 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001805 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001806 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1807 // Generate a vector reduction and scalar extract
1808 // x = REDUCE( [x_1, .., x_n] )
1809 // y = x_1
1810 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001811 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001812 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001813 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1814 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001815 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001816 exit->InsertInstructionAfter(instruction, reduce);
1817 }
1818 }
1819 return instruction;
1820}
1821
Aart Bikf8f5a162017-02-06 15:35:29 -08001822#define GENERATE_VEC(x, y) \
1823 if (vector_mode_ == kVector) { \
1824 vector = (x); \
1825 } else { \
1826 DCHECK(vector_mode_ == kSequential); \
1827 vector = (y); \
1828 } \
1829 break;
1830
1831void HLoopOptimization::GenerateVecOp(HInstruction* org,
1832 HInstruction* opa,
1833 HInstruction* opb,
Aart Bik3f08e9b2018-05-01 13:42:03 -07001834 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001835 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001836 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001837 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001838 switch (org->GetKind()) {
1839 case HInstruction::kNeg:
1840 DCHECK(opb == nullptr);
1841 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001842 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1843 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001844 case HInstruction::kNot:
1845 DCHECK(opb == nullptr);
1846 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001847 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1848 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001849 case HInstruction::kBooleanNot:
1850 DCHECK(opb == nullptr);
1851 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001852 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1853 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001854 case HInstruction::kTypeConversion:
1855 DCHECK(opb == nullptr);
1856 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001857 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1858 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001859 case HInstruction::kAdd:
1860 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001861 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1862 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001863 case HInstruction::kSub:
1864 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001865 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1866 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001867 case HInstruction::kMul:
1868 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001869 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1870 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001871 case HInstruction::kDiv:
1872 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001873 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1874 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001875 case HInstruction::kAnd:
1876 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001877 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1878 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001879 case HInstruction::kOr:
1880 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001881 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1882 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001883 case HInstruction::kXor:
1884 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001885 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1886 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001887 case HInstruction::kShl:
1888 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001889 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1890 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001891 case HInstruction::kShr:
1892 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001893 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1894 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001895 case HInstruction::kUShr:
1896 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001897 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1898 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001899 case HInstruction::kAbs:
1900 DCHECK(opb == nullptr);
1901 GENERATE_VEC(
1902 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1903 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001904 default:
1905 break;
1906 } // switch
1907 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1908 vector_map_->Put(org, vector);
1909}
1910
1911#undef GENERATE_VEC
1912
1913//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001914// Vectorization idioms.
1915//
1916
1917// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001918// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1919// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001920// Provided that the operands are promoted to a wider form to do the arithmetic and
1921// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1922// implementation that operates directly in narrower form (plus one extra bit).
1923// TODO: current version recognizes implicit byte/short/char widening only;
1924// explicit widening from int to long could be added later.
1925bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1926 HInstruction* instruction,
1927 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001928 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001929 uint64_t restrictions) {
1930 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001931 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001932 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001933 if ((instruction->IsShr() ||
1934 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001935 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001936 // Test for (a + b + c) >> 1 for optional constant c.
1937 HInstruction* a = nullptr;
1938 HInstruction* b = nullptr;
1939 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001940 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07001941 // Accept c == 1 (rounded) or c == 0 (not rounded).
1942 bool is_rounded = false;
1943 if (c == 1) {
1944 is_rounded = true;
1945 } else if (c != 0) {
1946 return false;
1947 }
1948 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001949 HInstruction* r = nullptr;
1950 HInstruction* s = nullptr;
1951 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001952 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001953 return false;
1954 }
1955 // Deal with vector restrictions.
1956 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1957 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1958 return false;
1959 }
1960 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1961 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001962 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001963 if (generate_code && vector_mode_ != kVector) { // de-idiom
1964 r = instruction->InputAt(0);
1965 s = instruction->InputAt(1);
1966 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001967 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1968 VectorizeUse(node, s, generate_code, type, restrictions)) {
1969 if (generate_code) {
1970 if (vector_mode_ == kVector) {
1971 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1972 global_allocator_,
1973 vector_map_->Get(r),
1974 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08001975 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07001976 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001977 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001978 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07001979 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001980 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001981 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001982 }
1983 }
1984 return true;
1985 }
1986 }
1987 }
1988 return false;
1989}
1990
Aart Bikdbbac8f2017-09-01 13:06:08 -07001991// Method recognizes the following idiom:
1992// q += ABS(a - b) for signed operands a, b
1993// Provided that the operands have the same type or are promoted to a wider form.
1994// Since this may involve a vector length change, the idiom is handled by going directly
1995// to a sad-accumulate node (rather than relying combining finer grained nodes later).
1996// TODO: unsigned SAD too?
1997bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
1998 HInstruction* instruction,
1999 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002000 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002001 uint64_t restrictions) {
2002 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2003 // are done in the same precision (either int or long).
2004 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002005 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002006 return false;
2007 }
2008 HInstruction* q = instruction->InputAt(0);
2009 HInstruction* v = instruction->InputAt(1);
2010 HInstruction* a = nullptr;
2011 HInstruction* b = nullptr;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002012 if (v->IsAbs() &&
2013 v->GetType() == reduction_type &&
2014 IsSubConst2(graph_, v->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2015 DCHECK(a != nullptr && b != nullptr);
2016 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002017 return false;
2018 }
2019 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2020 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002021 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002022 HInstruction* r = a;
2023 HInstruction* s = b;
2024 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002025 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002026 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2027 sub_type = b->GetType();
2028 }
2029 if (a->IsTypeConversion() &&
2030 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2031 sub_type = a->InputAt(0)->GetType();
2032 }
2033 if (b->IsTypeConversion() &&
2034 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2035 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002036 }
2037 if (reduction_type != sub_type &&
2038 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2039 return false;
2040 }
2041 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002042 if (!TrySetVectorType(sub_type, &restrictions) ||
2043 HasVectorRestrictions(restrictions, kNoSAD) ||
2044 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002045 return false;
2046 }
2047 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2048 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002049 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002050 if (generate_code && vector_mode_ != kVector) { // de-idiom
2051 r = s = v->InputAt(0);
2052 }
2053 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2054 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2055 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2056 if (generate_code) {
2057 if (vector_mode_ == kVector) {
2058 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2059 global_allocator_,
2060 vector_map_->Get(q),
2061 vector_map_->Get(r),
2062 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002063 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002064 GetOtherVL(reduction_type, sub_type, vector_length_),
2065 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002066 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2067 } else {
2068 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2069 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2070 }
2071 }
2072 return true;
2073 }
2074 return false;
2075}
2076
Aart Bikf3e61ee2017-04-12 17:09:20 -07002077//
Aart Bik14a68b42017-06-08 14:06:58 -07002078// Vectorization heuristics.
2079//
2080
Aart Bik38a3f212017-10-20 17:02:21 -07002081Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2082 DataType::Type type,
2083 bool is_string_char_at,
2084 uint32_t peeling) {
2085 // Combine the alignment and hidden offset that is guaranteed by
2086 // the Android runtime with a known starting index adjusted as bytes.
2087 int64_t value = 0;
2088 if (IsInt64AndGet(offset, /*out*/ &value)) {
2089 uint32_t start_offset =
2090 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2091 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2092 }
2093 // Otherwise, the Android runtime guarantees at least natural alignment.
2094 return Alignment(DataType::Size(type), 0);
2095}
2096
2097void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2098 const ArrayReference* peeling_candidate) {
2099 // Current heuristic: pick the best static loop peeling factor, if any,
2100 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2101 uint32_t max_vote = 0;
2102 for (int32_t i = 0; i < 16; i++) {
2103 if (peeling_votes[i] > max_vote) {
2104 max_vote = peeling_votes[i];
2105 vector_static_peeling_factor_ = i;
2106 }
2107 }
2108 if (max_vote == 0) {
2109 vector_dynamic_peeling_candidate_ = peeling_candidate;
2110 }
2111}
2112
2113uint32_t HLoopOptimization::MaxNumberPeeled() {
2114 if (vector_dynamic_peeling_candidate_ != nullptr) {
2115 return vector_length_ - 1u; // worst-case
2116 }
2117 return vector_static_peeling_factor_; // known exactly
2118}
2119
Aart Bik14a68b42017-06-08 14:06:58 -07002120bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002121 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002122 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002123 // TODO: trip count is really unsigned entity, provided the guarding test
2124 // is satisfied; deal with this more carefully later
2125 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002126 if (vector_length_ == 0) {
2127 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002128 } else if (trip_count < 0) {
2129 return false; // guard against non-taken/large
2130 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002131 return false; // insufficient iterations
2132 }
2133 return true;
2134}
2135
Aart Bik14a68b42017-06-08 14:06:58 -07002136//
Aart Bikf8f5a162017-02-06 15:35:29 -08002137// Helpers.
2138//
2139
2140bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002141 // Start with empty phi induction.
2142 iset_->clear();
2143
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002144 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2145 // smart enough to follow strongly connected components (and it's probably not worth
2146 // it to make it so). See b/33775412.
2147 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2148 return false;
2149 }
Aart Bikb29f6842017-07-28 15:58:41 -07002150
2151 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002152 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2153 if (set != nullptr) {
2154 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002155 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002156 // each instruction is removable and, when restrict uses are requested, other than for phi,
2157 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002158 if (!i->IsInBlock()) {
2159 continue;
2160 } else if (!i->IsRemovable()) {
2161 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002162 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002163 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002164 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2165 if (set->find(use.GetUser()) == set->end()) {
2166 return false;
2167 }
2168 }
2169 }
Aart Bike3dedc52016-11-02 17:50:27 -07002170 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002171 }
Aart Bikcc42be02016-10-20 16:14:16 -07002172 return true;
2173 }
2174 return false;
2175}
2176
Aart Bikb29f6842017-07-28 15:58:41 -07002177bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002178 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002179 // Only unclassified phi cycles are candidates for reductions.
2180 if (induction_range_.IsClassified(phi)) {
2181 return false;
2182 }
2183 // Accept operations like x = x + .., provided that the phi and the reduction are
2184 // used exactly once inside the loop, and by each other.
2185 HInputsRef inputs = phi->GetInputs();
2186 if (inputs.size() == 2) {
2187 HInstruction* reduction = inputs[1];
2188 if (HasReductionFormat(reduction, phi)) {
2189 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002190 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002191 bool single_use_inside_loop =
2192 // Reduction update only used by phi.
2193 reduction->GetUses().HasExactlyOneElement() &&
2194 !reduction->HasEnvironmentUses() &&
2195 // Reduction update is only use of phi inside the loop.
2196 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2197 iset_->size() == 1;
2198 iset_->clear(); // leave the way you found it
2199 if (single_use_inside_loop) {
2200 // Link reduction back, and start recording feed value.
2201 reductions_->Put(reduction, phi);
2202 reductions_->Put(phi, phi->InputAt(0));
2203 return true;
2204 }
2205 }
2206 }
2207 return false;
2208}
2209
2210bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2211 // Start with empty phi induction and reductions.
2212 iset_->clear();
2213 reductions_->clear();
2214
2215 // Scan the phis to find the following (the induction structure has already
2216 // been optimized, so we don't need to worry about trivial cases):
2217 // (1) optional reductions in loop,
2218 // (2) the main induction, used in loop control.
2219 HPhi* phi = nullptr;
2220 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2221 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2222 continue;
2223 } else if (phi == nullptr) {
2224 // Found the first candidate for main induction.
2225 phi = it.Current()->AsPhi();
2226 } else {
2227 return false;
2228 }
2229 }
2230
2231 // Then test for a typical loopheader:
2232 // s: SuspendCheck
2233 // c: Condition(phi, bound)
2234 // i: If(c)
2235 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002236 HInstruction* s = block->GetFirstInstruction();
2237 if (s != nullptr && s->IsSuspendCheck()) {
2238 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002239 if (c != nullptr &&
2240 c->IsCondition() &&
2241 c->GetUses().HasExactlyOneElement() && // only used for termination
2242 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002243 HInstruction* i = c->GetNext();
2244 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2245 iset_->insert(c);
2246 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002247 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002248 return true;
2249 }
2250 }
2251 }
2252 }
2253 return false;
2254}
2255
2256bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002257 if (!block->GetPhis().IsEmpty()) {
2258 return false;
2259 }
2260 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2261 HInstruction* instruction = it.Current();
2262 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2263 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002264 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002265 }
2266 return true;
2267}
2268
2269bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2270 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002271 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002272 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2273 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2274 return true;
2275 }
Aart Bikcc42be02016-10-20 16:14:16 -07002276 }
2277 return false;
2278}
2279
Aart Bik482095d2016-10-10 15:39:10 -07002280bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002281 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002282 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002283 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002284 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002285 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2286 HInstruction* user = use.GetUser();
2287 if (iset_->find(user) == iset_->end()) { // not excluded?
2288 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002289 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002290 // If collect_loop_uses is set, simply keep adding those uses to the set.
2291 // Otherwise, reject uses inside the loop that were not already in the set.
2292 if (collect_loop_uses) {
2293 iset_->insert(user);
2294 continue;
2295 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002296 return false;
2297 }
2298 ++*use_count;
2299 }
2300 }
2301 return true;
2302}
2303
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002304bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2305 HInstruction* instruction,
2306 HBasicBlock* block) {
2307 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002308 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002309 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002310 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002311 const HUseList<HInstruction*>& uses = instruction->GetUses();
2312 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2313 HInstruction* user = it->GetUser();
2314 size_t index = it->GetIndex();
2315 ++it; // increment before replacing
2316 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002317 if (kIsDebugBuild) {
2318 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2319 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2320 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2321 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002322 user->ReplaceInput(replacement, index);
2323 induction_range_.Replace(user, instruction, replacement); // update induction
2324 }
2325 }
Aart Bikb29f6842017-07-28 15:58:41 -07002326 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002327 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2328 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2329 HEnvironment* user = it->GetUser();
2330 size_t index = it->GetIndex();
2331 ++it; // increment before replacing
2332 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002333 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002334 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002335 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2336 user->RemoveAsUserOfInput(index);
2337 user->SetRawEnvAt(index, replacement);
2338 replacement->AddEnvUseAt(user, index);
2339 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002340 }
2341 }
Aart Bik807868e2016-11-03 17:51:43 -07002342 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002343 }
Aart Bik807868e2016-11-03 17:51:43 -07002344 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002345}
2346
Aart Bikf8f5a162017-02-06 15:35:29 -08002347bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2348 HInstruction* instruction,
2349 HBasicBlock* block,
2350 bool collect_loop_uses) {
2351 // Assigning the last value is always successful if there are no uses.
2352 // Otherwise, it succeeds in a no early-exit loop by generating the
2353 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002354 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002355 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2356 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002357 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002358}
2359
Aart Bik6b69e0a2017-01-11 10:20:43 -08002360void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2361 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2362 HInstruction* instruction = i.Current();
2363 if (instruction->IsDeadAndRemovable()) {
2364 simplified_ = true;
2365 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2366 }
2367 }
2368}
2369
Aart Bik14a68b42017-06-08 14:06:58 -07002370bool HLoopOptimization::CanRemoveCycle() {
2371 for (HInstruction* i : *iset_) {
2372 // We can never remove instructions that have environment
2373 // uses when we compile 'debuggable'.
2374 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2375 return false;
2376 }
2377 // A deoptimization should never have an environment input removed.
2378 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2379 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2380 return false;
2381 }
2382 }
2383 }
2384 return true;
2385}
2386
Aart Bik281c6812016-08-26 11:31:48 -07002387} // namespace art