blob: 4c9b01c97e3ff087bec6447a0b671fffb513022d [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/x86/instruction_set_features_x86.h"
23#include "arch/x86_64/instruction_set_features_x86_64.h"
Artem Serovc8150b52019-07-31 18:28:00 +010024#include "code_generator.h"
Vladimir Markoa0431112018-06-25 09:32:54 +010025#include "driver/compiler_options.h"
Aart Bik96202302016-10-04 17:33:56 -070026#include "linear_order.h"
Aart Bik38a3f212017-10-20 17:02:21 -070027#include "mirror/array-inl.h"
28#include "mirror/string.h"
Aart Bik281c6812016-08-26 11:31:48 -070029
Vladimir Marko0a516052019-10-14 13:00:44 +000030namespace art {
Aart Bik281c6812016-08-26 11:31:48 -070031
Aart Bikf8f5a162017-02-06 15:35:29 -080032// Enables vectorization (SIMDization) in the loop optimizer.
33static constexpr bool kEnableVectorization = true;
34
Aart Bik38a3f212017-10-20 17:02:21 -070035//
36// Static helpers.
37//
38
39// Base alignment for arrays/strings guaranteed by the Android runtime.
40static uint32_t BaseAlignment() {
41 return kObjectAlignment;
42}
43
44// Hidden offset for arrays/strings guaranteed by the Android runtime.
45static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
46 return is_string_char_at
47 ? mirror::String::ValueOffset().Uint32Value()
48 : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
49}
50
Aart Bik9abf8942016-10-14 09:49:42 -070051// Remove the instruction from the graph. A bit more elaborate than the usual
52// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070053static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070054 instruction->RemoveAsUserOfAllInputs();
55 instruction->RemoveEnvironmentUsers();
56 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010057 RemoveEnvironmentUses(instruction);
58 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070059}
60
Aart Bik807868e2016-11-03 17:51:43 -070061// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070062static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
63 if (block->GetPredecessors().size() == 1 &&
64 block->GetSuccessors().size() == 1 &&
65 block->IsSingleGoto()) {
66 *succ = block->GetSingleSuccessor();
67 return true;
68 }
69 return false;
70}
71
Aart Bik807868e2016-11-03 17:51:43 -070072// Detect an early exit loop.
73static bool IsEarlyExit(HLoopInformation* loop_info) {
74 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
75 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
76 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
77 if (!loop_info->Contains(*successor)) {
78 return true;
79 }
80 }
81 }
82 return false;
83}
84
Aart Bik68ca7022017-09-26 16:44:23 -070085// Forward declaration.
86static bool IsZeroExtensionAndGet(HInstruction* instruction,
87 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070088 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -070089
Aart Bikdf011c32017-09-28 12:53:04 -070090// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -070091// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070092static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010093 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070094 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070095 // Accept any already wider constant that would be handled properly by sign
96 // extension when represented in the *width* of the given narrower data type
Aart Bik4d1a9d42017-10-19 14:40:55 -070097 // (the fact that Uint8/Uint16 normally zero extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -070098 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -070099 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700100 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100101 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100102 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700103 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700104 *operand = instruction;
105 return true;
106 }
107 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100108 case DataType::Type::kUint16:
109 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700110 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700111 *operand = instruction;
112 return true;
113 }
114 return false;
115 default:
116 return false;
117 }
118 }
Aart Bikdf011c32017-09-28 12:53:04 -0700119 // An implicit widening conversion of any signed expression sign-extends.
120 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700121 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100122 case DataType::Type::kInt8:
123 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700124 *operand = instruction;
125 return true;
126 default:
127 return false;
128 }
129 }
Aart Bikdf011c32017-09-28 12:53:04 -0700130 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700131 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700132 HInstruction* conv = instruction->InputAt(0);
133 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700134 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700135 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700136 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700137 if (type == from && (from == DataType::Type::kInt8 ||
138 from == DataType::Type::kInt16 ||
139 from == DataType::Type::kInt32)) {
140 *operand = conv;
141 return true;
142 }
143 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700144 case DataType::Type::kInt16:
145 return type == DataType::Type::kUint16 &&
146 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700147 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700148 default:
149 return false;
150 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700151 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700152 return false;
153}
154
Aart Bikdf011c32017-09-28 12:53:04 -0700155// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700156// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700157static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100158 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700159 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700160 // Accept any already wider constant that would be handled properly by zero
161 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700162 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700163 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700164 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700165 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100166 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100167 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700168 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700169 *operand = instruction;
170 return true;
171 }
172 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100173 case DataType::Type::kUint16:
174 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700175 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700176 *operand = instruction;
177 return true;
178 }
179 return false;
180 default:
181 return false;
182 }
183 }
Aart Bikdf011c32017-09-28 12:53:04 -0700184 // An implicit widening conversion of any unsigned expression zero-extends.
185 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100186 switch (type) {
187 case DataType::Type::kUint8:
188 case DataType::Type::kUint16:
189 *operand = instruction;
190 return true;
191 default:
192 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700193 }
194 }
Aart Bikdf011c32017-09-28 12:53:04 -0700195 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700196 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700197 HInstruction* conv = instruction->InputAt(0);
198 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700199 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700200 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700201 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700202 if (type == from && from == DataType::Type::kUint16) {
203 *operand = conv;
204 return true;
205 }
206 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700207 case DataType::Type::kUint16:
208 return type == DataType::Type::kInt16 &&
209 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700210 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700211 default:
212 return false;
213 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700214 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700215 return false;
216}
217
Aart Bik304c8a52017-05-23 11:01:13 -0700218// Detect situations with same-extension narrower operands.
219// Returns true on success and sets is_unsigned accordingly.
220static bool IsNarrowerOperands(HInstruction* a,
221 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100222 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700223 /*out*/ HInstruction** r,
224 /*out*/ HInstruction** s,
225 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000226 DCHECK(a != nullptr && b != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700227 // Look for a matching sign extension.
228 DataType::Type stype = HVecOperation::ToSignedType(type);
229 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700230 *is_unsigned = false;
231 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700232 }
233 // Look for a matching zero extension.
234 DataType::Type utype = HVecOperation::ToUnsignedType(type);
235 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700236 *is_unsigned = true;
237 return true;
238 }
239 return false;
240}
241
242// As above, single operand.
243static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100244 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700245 /*out*/ HInstruction** r,
246 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000247 DCHECK(a != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700248 // Look for a matching sign extension.
249 DataType::Type stype = HVecOperation::ToSignedType(type);
250 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700251 *is_unsigned = false;
252 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700253 }
254 // Look for a matching zero extension.
255 DataType::Type utype = HVecOperation::ToUnsignedType(type);
256 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700257 *is_unsigned = true;
258 return true;
259 }
260 return false;
261}
262
Aart Bikdbbac8f2017-09-01 13:06:08 -0700263// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700264static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100265 DCHECK(DataType::IsIntegralType(other_type));
266 DCHECK(DataType::IsIntegralType(vector_type));
267 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
268 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700269}
270
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000271// Detect up to two added operands a and b and an acccumulated constant c.
272static bool IsAddConst(HInstruction* instruction,
273 /*out*/ HInstruction** a,
274 /*out*/ HInstruction** b,
275 /*out*/ int64_t* c,
276 int32_t depth = 8) { // don't search too deep
Aart Bik5f805002017-05-16 16:42:41 -0700277 int64_t value = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000278 // Enter add/sub while still within reasonable depth.
279 if (depth > 0) {
280 if (instruction->IsAdd()) {
281 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1) &&
282 IsAddConst(instruction->InputAt(1), a, b, c, depth - 1);
283 } else if (instruction->IsSub() &&
284 IsInt64AndGet(instruction->InputAt(1), &value)) {
285 *c -= value;
286 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1);
287 }
288 }
289 // Otherwise, deal with leaf nodes.
Aart Bik5f805002017-05-16 16:42:41 -0700290 if (IsInt64AndGet(instruction, &value)) {
291 *c += value;
292 return true;
Aart Bik5f805002017-05-16 16:42:41 -0700293 } else if (*a == nullptr) {
294 *a = instruction;
295 return true;
296 } else if (*b == nullptr) {
297 *b = instruction;
298 return true;
299 }
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000300 return false; // too many operands
Aart Bik5f805002017-05-16 16:42:41 -0700301}
302
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000303// Detect a + b + c with optional constant c.
304static bool IsAddConst2(HGraph* graph,
305 HInstruction* instruction,
306 /*out*/ HInstruction** a,
307 /*out*/ HInstruction** b,
308 /*out*/ int64_t* c) {
Artem Serovb47b9782019-12-04 21:02:09 +0000309 // We want an actual add/sub and not the trivial case where {b: 0, c: 0}.
310 if (IsAddOrSub(instruction) && IsAddConst(instruction, a, b, c) && *a != nullptr) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000311 if (*b == nullptr) {
312 // Constant is usually already present, unless accumulated.
313 *b = graph->GetConstant(instruction->GetType(), (*c));
314 *c = 0;
Aart Bik5f805002017-05-16 16:42:41 -0700315 }
Aart Bik5f805002017-05-16 16:42:41 -0700316 return true;
317 }
318 return false;
319}
320
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000321// Detect a direct a - b or a hidden a - (-c).
322static bool IsSubConst2(HGraph* graph,
323 HInstruction* instruction,
324 /*out*/ HInstruction** a,
325 /*out*/ HInstruction** b) {
326 int64_t c = 0;
327 if (instruction->IsSub()) {
328 *a = instruction->InputAt(0);
329 *b = instruction->InputAt(1);
330 return true;
331 } else if (IsAddConst(instruction, a, b, &c) && *a != nullptr && *b == nullptr) {
332 // Constant for the hidden subtraction.
333 *b = graph->GetConstant(instruction->GetType(), -c);
334 return true;
Aart Bikdf011c32017-09-28 12:53:04 -0700335 }
336 return false;
337}
338
Aart Bikb29f6842017-07-28 15:58:41 -0700339// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700340// x = x_phi + ..
341// x = x_phi - ..
Aart Bikb29f6842017-07-28 15:58:41 -0700342static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
Aart Bik3f08e9b2018-05-01 13:42:03 -0700343 if (reduction->IsAdd()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700344 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
345 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700346 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700347 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700348 }
349 return false;
350}
351
Aart Bikdbbac8f2017-09-01 13:06:08 -0700352// Translates vector operation to reduction kind.
353static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
Shalini Salomi Bodapati81d15be2019-05-30 11:00:42 +0530354 if (reduction->IsVecAdd() ||
Artem Serovaaac0e32018-08-07 00:52:22 +0100355 reduction->IsVecSub() ||
356 reduction->IsVecSADAccumulate() ||
357 reduction->IsVecDotProd()) {
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
Artem Serov18ba1da2018-05-16 19:06:32 +0100428// Peel the first 'count' iterations of the loop.
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100429static void PeelByCount(HLoopInformation* loop_info,
430 int count,
431 InductionVarRange* induction_range) {
Artem Serov18ba1da2018-05-16 19:06:32 +0100432 for (int i = 0; i < count; i++) {
433 // Perform peeling.
Artem Serov0f5b2bf2019-10-23 14:07:41 +0100434 LoopClonerSimpleHelper helper(loop_info, induction_range);
Artem Serov18ba1da2018-05-16 19:06:32 +0100435 helper.DoPeeling();
436 }
437}
438
Artem Serovaaac0e32018-08-07 00:52:22 +0100439// Returns the narrower type out of instructions a and b types.
440static DataType::Type GetNarrowerType(HInstruction* a, HInstruction* b) {
441 DataType::Type type = a->GetType();
442 if (DataType::Size(b->GetType()) < DataType::Size(type)) {
443 type = b->GetType();
444 }
445 if (a->IsTypeConversion() &&
446 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(type)) {
447 type = a->InputAt(0)->GetType();
448 }
449 if (b->IsTypeConversion() &&
450 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(type)) {
451 type = b->InputAt(0)->GetType();
452 }
453 return type;
454}
455
Aart Bik281c6812016-08-26 11:31:48 -0700456//
Aart Bikb29f6842017-07-28 15:58:41 -0700457// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700458//
459
460HLoopOptimization::HLoopOptimization(HGraph* graph,
Artem Serovc8150b52019-07-31 18:28:00 +0100461 const CodeGenerator& codegen,
Aart Bikb92cc332017-09-06 15:53:17 -0700462 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800463 OptimizingCompilerStats* stats,
464 const char* name)
465 : HOptimization(graph, name, stats),
Artem Serovc8150b52019-07-31 18:28:00 +0100466 compiler_options_(&codegen.GetCompilerOptions()),
467 simd_register_size_(codegen.GetSIMDRegisterWidth()),
Aart Bik281c6812016-08-26 11:31:48 -0700468 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700469 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100470 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700471 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700472 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700473 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700474 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800475 simplified_(false),
476 vector_length_(0),
477 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700478 vector_static_peeling_factor_(0),
479 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700480 vector_runtime_test_a_(nullptr),
481 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700482 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100483 vector_permanent_map_(nullptr),
484 vector_mode_(kSequential),
485 vector_preheader_(nullptr),
486 vector_header_(nullptr),
487 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100488 vector_index_(nullptr),
Vladimir Markoa0431112018-06-25 09:32:54 +0100489 arch_loop_helper_(ArchNoOptsLoopHelper::Create(compiler_options_ != nullptr
490 ? compiler_options_->GetInstructionSet()
Artem Serov121f2032017-10-23 19:19:06 +0100491 : InstructionSet::kNone,
492 global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700493}
494
Aart Bik24773202018-04-26 10:28:51 -0700495bool HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800496 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700497 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800498 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik24773202018-04-26 10:28:51 -0700499 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700500 }
501
Vladimir Markoca6fff82017-10-03 14:49:14 +0100502 // Phase-local allocator.
503 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700504 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100505
Aart Bik96202302016-10-04 17:33:56 -0700506 // Perform loop optimizations.
Aart Bik24773202018-04-26 10:28:51 -0700507 bool didLoopOpt = LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800508 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800509 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800510 }
511
Aart Bik96202302016-10-04 17:33:56 -0700512 // Detach.
513 loop_allocator_ = nullptr;
514 last_loop_ = top_loop_ = nullptr;
Aart Bik24773202018-04-26 10:28:51 -0700515
516 return didLoopOpt;
Aart Bik96202302016-10-04 17:33:56 -0700517}
518
Aart Bikb29f6842017-07-28 15:58:41 -0700519//
520// Loop setup and traversal.
521//
522
Aart Bik24773202018-04-26 10:28:51 -0700523bool HLoopOptimization::LocalRun() {
524 bool didLoopOpt = false;
Aart Bik96202302016-10-04 17:33:56 -0700525 // Build the linear order using the phase-local allocator. This step enables building
526 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100527 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
528 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700529
Aart Bik281c6812016-08-26 11:31:48 -0700530 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700531 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700532 if (block->IsLoopHeader()) {
533 AddLoop(block->GetLoopInformation());
534 }
535 }
Aart Bik96202302016-10-04 17:33:56 -0700536
Aart Bik8c4a8542016-10-06 11:36:57 -0700537 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800538 // temporary data structures using the phase-local allocator. All new HIR
539 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700540 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100541 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
542 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700543 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100544 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
545 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800546 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100547 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700548 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800549 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700550 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700551 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800552 vector_refs_ = &refs;
553 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700554 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800555 // Traverse.
Aart Bik24773202018-04-26 10:28:51 -0700556 didLoopOpt = TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800557 // Detach.
558 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700559 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800560 vector_refs_ = nullptr;
561 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700562 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700563 }
Aart Bik24773202018-04-26 10:28:51 -0700564 return didLoopOpt;
Aart Bik281c6812016-08-26 11:31:48 -0700565}
566
567void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
568 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800569 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700570 if (last_loop_ == nullptr) {
571 // First loop.
572 DCHECK(top_loop_ == nullptr);
573 last_loop_ = top_loop_ = node;
574 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
575 // Inner loop.
576 node->outer = last_loop_;
577 DCHECK(last_loop_->inner == nullptr);
578 last_loop_ = last_loop_->inner = node;
579 } else {
580 // Subsequent loop.
581 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
582 last_loop_ = last_loop_->outer;
583 }
584 node->outer = last_loop_->outer;
585 node->previous = last_loop_;
586 DCHECK(last_loop_->next == nullptr);
587 last_loop_ = last_loop_->next = node;
588 }
589}
590
591void HLoopOptimization::RemoveLoop(LoopNode* node) {
592 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700593 DCHECK(node->inner == nullptr);
594 if (node->previous != nullptr) {
595 // Within sequence.
596 node->previous->next = node->next;
597 if (node->next != nullptr) {
598 node->next->previous = node->previous;
599 }
600 } else {
601 // First of sequence.
602 if (node->outer != nullptr) {
603 node->outer->inner = node->next;
604 } else {
605 top_loop_ = node->next;
606 }
607 if (node->next != nullptr) {
608 node->next->outer = node->outer;
609 node->next->previous = nullptr;
610 }
611 }
Aart Bik281c6812016-08-26 11:31:48 -0700612}
613
Aart Bikb29f6842017-07-28 15:58:41 -0700614bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
615 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700616 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700617 // Visit inner loops first. Recompute induction information for this
618 // loop if the induction of any inner loop has changed.
619 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700620 induction_range_.ReVisit(node->loop_info);
Aart Bika8360cd2018-05-02 16:07:51 -0700621 changed = true;
Aart Bik482095d2016-10-10 15:39:10 -0700622 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800623 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800624 // Note that since each simplification consists of eliminating code (without
625 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800626 do {
627 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800628 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800629 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700630 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800631 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800632 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700633 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700634 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700635 }
Aart Bik281c6812016-08-26 11:31:48 -0700636 }
Aart Bikb29f6842017-07-28 15:58:41 -0700637 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700638}
639
Aart Bikf8f5a162017-02-06 15:35:29 -0800640//
641// Optimization.
642//
643
Aart Bik281c6812016-08-26 11:31:48 -0700644void HLoopOptimization::SimplifyInduction(LoopNode* node) {
645 HBasicBlock* header = node->loop_info->GetHeader();
646 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700647 // Scan the phis in the header to find opportunities to simplify an induction
648 // cycle that is only used outside the loop. Replace these uses, if any, with
649 // the last value and remove the induction cycle.
650 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
651 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700652 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
653 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800654 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
655 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700656 // Note that it's ok to have replaced uses after the loop with the last value, without
657 // being able to remove the cycle. Environment uses (which are the reason we may not be
658 // able to remove the cycle) within the loop will still hold the right value. We must
659 // have tried first, however, to replace outside uses.
660 if (CanRemoveCycle()) {
661 simplified_ = true;
662 for (HInstruction* i : *iset_) {
663 RemoveFromCycle(i);
664 }
665 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700666 }
Aart Bik482095d2016-10-10 15:39:10 -0700667 }
668 }
669}
670
671void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800672 // Iterate over all basic blocks in the loop-body.
673 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
674 HBasicBlock* block = it.Current();
675 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800676 RemoveDeadInstructions(block->GetPhis());
677 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800678 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800679 if (block->GetPredecessors().size() == 1 &&
680 block->GetSuccessors().size() == 1 &&
681 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800682 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800683 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800684 } else if (block->GetSuccessors().size() == 2) {
685 // Trivial if block can be bypassed to either branch.
686 HBasicBlock* succ0 = block->GetSuccessors()[0];
687 HBasicBlock* succ1 = block->GetSuccessors()[1];
688 HBasicBlock* meet0 = nullptr;
689 HBasicBlock* meet1 = nullptr;
690 if (succ0 != succ1 &&
691 IsGotoBlock(succ0, &meet0) &&
692 IsGotoBlock(succ1, &meet1) &&
693 meet0 == meet1 && // meets again
694 meet0 != block && // no self-loop
695 meet0->GetPhis().IsEmpty()) { // not used for merging
696 simplified_ = true;
697 succ0->DisconnectAndDelete();
698 if (block->Dominates(meet0)) {
699 block->RemoveDominatedBlock(meet0);
700 succ1->AddDominatedBlock(meet0);
701 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700702 }
Aart Bik482095d2016-10-10 15:39:10 -0700703 }
Aart Bik281c6812016-08-26 11:31:48 -0700704 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800705 }
Aart Bik281c6812016-08-26 11:31:48 -0700706}
707
Artem Serov121f2032017-10-23 19:19:06 +0100708bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700709 HBasicBlock* header = node->loop_info->GetHeader();
710 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700711 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800712 int64_t trip_count = 0;
713 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700714 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700715 }
Aart Bik281c6812016-08-26 11:31:48 -0700716 // Ensure there is only a single loop-body (besides the header).
717 HBasicBlock* body = nullptr;
718 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
719 if (it.Current() != header) {
720 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700721 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700722 }
723 body = it.Current();
724 }
725 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700726 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700727 // Ensure there is only a single exit point.
728 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700729 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700730 }
731 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
732 ? header->GetSuccessors()[1]
733 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700734 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700735 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700736 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700737 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800738 // Detect either an empty loop (no side effects other than plain iteration) or
739 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
740 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700741 HPhi* main_phi = nullptr;
742 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800743 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700744 if (reductions_->empty() && // TODO: possible with some effort
745 (is_empty || trip_count == 1) &&
746 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800747 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800748 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700749 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800750 preheader->MergeInstructionsWith(body);
751 }
752 body->DisconnectAndDelete();
753 exit->RemovePredecessor(header);
754 header->RemoveSuccessor(exit);
755 header->RemoveDominatedBlock(exit);
756 header->DisconnectAndDelete();
757 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800758 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800759 preheader->AddDominatedBlock(exit);
760 exit->SetDominator(preheader);
761 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700762 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800763 }
764 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800765 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700766 if (kEnableVectorization &&
Artem Serove65ade72019-07-25 21:04:16 +0100767 // Disable vectorization for debuggable graphs: this is a workaround for the bug
768 // in 'GenerateNewLoop' which caused the SuspendCheck environment to be invalid.
769 // TODO: b/138601207, investigate other possible cases with wrong environment values and
770 // possibly switch back vectorization on for debuggable graphs.
771 !graph_->IsDebuggable() &&
Aart Bikb29f6842017-07-28 15:58:41 -0700772 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700773 ShouldVectorize(node, body, trip_count) &&
774 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
775 Vectorize(node, body, exit, trip_count);
776 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700777 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700778 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800779 }
Aart Bikb29f6842017-07-28 15:58:41 -0700780 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800781}
782
Artem Serov121f2032017-10-23 19:19:06 +0100783bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Artem Serov0e329082018-06-12 10:23:27 +0100784 return TryOptimizeInnerLoopFinite(node) || TryPeelingAndUnrolling(node);
Artem Serov121f2032017-10-23 19:19:06 +0100785}
786
Artem Serov121f2032017-10-23 19:19:06 +0100787
Artem Serov121f2032017-10-23 19:19:06 +0100788
789//
Artem Serov0e329082018-06-12 10:23:27 +0100790// Scalar loop peeling and unrolling: generic part methods.
Artem Serov121f2032017-10-23 19:19:06 +0100791//
792
Artem Serov0e329082018-06-12 10:23:27 +0100793bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
794 bool generate_code) {
795 if (analysis_info->GetNumberOfExits() > 1) {
Artem Serov121f2032017-10-23 19:19:06 +0100796 return false;
797 }
798
Artem Serov0e329082018-06-12 10:23:27 +0100799 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
800 if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
Artem Serov121f2032017-10-23 19:19:06 +0100801 return false;
802 }
803
Artem Serov0e329082018-06-12 10:23:27 +0100804 if (generate_code) {
805 // TODO: support other unrolling factors.
806 DCHECK_EQ(unrolling_factor, 2u);
807
808 // Perform unrolling.
809 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov0f5b2bf2019-10-23 14:07:41 +0100810 LoopClonerSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100811 helper.DoUnrolling();
812
813 // Remove the redundant loop check after unrolling.
814 HIf* copy_hif =
815 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
816 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
817 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
Artem Serov121f2032017-10-23 19:19:06 +0100818 }
Artem Serov121f2032017-10-23 19:19:06 +0100819 return true;
820}
821
Artem Serov0e329082018-06-12 10:23:27 +0100822bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
823 bool generate_code) {
824 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov72411e62017-10-19 16:18:07 +0100825 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
826 return false;
827 }
828
Artem Serov0e329082018-06-12 10:23:27 +0100829 if (analysis_info->GetNumberOfInvariantExits() == 0) {
Artem Serov72411e62017-10-19 16:18:07 +0100830 return false;
831 }
832
Artem Serov0e329082018-06-12 10:23:27 +0100833 if (generate_code) {
834 // Perform peeling.
Artem Serov0f5b2bf2019-10-23 14:07:41 +0100835 LoopClonerSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100836 helper.DoPeeling();
Artem Serov72411e62017-10-19 16:18:07 +0100837
Artem Serov0e329082018-06-12 10:23:27 +0100838 // Statically evaluate loop check after peeling for loop invariant condition.
839 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
840 for (auto entry : *hir_map) {
841 HInstruction* copy = entry.second;
842 if (copy->IsIf()) {
843 TryToEvaluateIfCondition(copy->AsIf(), graph_);
844 }
Artem Serov72411e62017-10-19 16:18:07 +0100845 }
846 }
847
848 return true;
849}
850
Artem Serov18ba1da2018-05-16 19:06:32 +0100851bool HLoopOptimization::TryFullUnrolling(LoopAnalysisInfo* analysis_info, bool generate_code) {
852 // Fully unroll loops with a known and small trip count.
853 int64_t trip_count = analysis_info->GetTripCount();
854 if (!arch_loop_helper_->IsLoopPeelingEnabled() ||
855 trip_count == LoopAnalysisInfo::kUnknownTripCount ||
856 !arch_loop_helper_->IsFullUnrollingBeneficial(analysis_info)) {
857 return false;
858 }
859
860 if (generate_code) {
861 // Peeling of the N first iterations (where N equals to the trip count) will effectively
862 // eliminate the loop: after peeling we will have N sequential iterations copied into the loop
863 // preheader and the original loop. The trip count of this loop will be 0 as the sequential
864 // iterations are executed first and there are exactly N of them. Thus we can statically
865 // evaluate the loop exit condition to 'false' and fully eliminate it.
866 //
867 // Here is an example of full unrolling of a loop with a trip count 2:
868 //
869 // loop_cond_1
870 // loop_body_1 <- First iteration.
871 // |
872 // \ v
873 // ==\ loop_cond_2
874 // ==/ loop_body_2 <- Second iteration.
875 // / |
876 // <- v <-
877 // loop_cond \ loop_cond \ <- This cond is always false.
878 // loop_body _/ loop_body _/
879 //
880 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100881 PeelByCount(loop_info, trip_count, &induction_range_);
Artem Serov18ba1da2018-05-16 19:06:32 +0100882 HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
883 int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
884 loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
885 }
886
887 return true;
888}
889
Artem Serov0e329082018-06-12 10:23:27 +0100890bool HLoopOptimization::TryPeelingAndUnrolling(LoopNode* node) {
Artem Serov0e329082018-06-12 10:23:27 +0100891 HLoopInformation* loop_info = node->loop_info;
892 int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
893 LoopAnalysisInfo analysis_info(loop_info);
894 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
895
896 if (analysis_info.HasInstructionsPreventingScalarOpts() ||
897 arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
898 return false;
899 }
900
Artem Serov18ba1da2018-05-16 19:06:32 +0100901 if (!TryFullUnrolling(&analysis_info, /*generate_code*/ false) &&
902 !TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
Artem Serov0e329082018-06-12 10:23:27 +0100903 !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false)) {
904 return false;
905 }
906
907 // Run 'IsLoopClonable' the last as it might be time-consuming.
Artem Serov0f5b2bf2019-10-23 14:07:41 +0100908 if (!LoopClonerHelper::IsLoopClonable(loop_info)) {
Artem Serov0e329082018-06-12 10:23:27 +0100909 return false;
910 }
911
Artem Serov18ba1da2018-05-16 19:06:32 +0100912 return TryFullUnrolling(&analysis_info) ||
913 TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
Artem Serov0e329082018-06-12 10:23:27 +0100914 TryUnrollingForBranchPenaltyReduction(&analysis_info);
915}
916
Aart Bikf8f5a162017-02-06 15:35:29 -0800917//
918// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
919// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
920// Intel Press, June, 2004 (http://www.aartbik.com/).
921//
922
Aart Bik14a68b42017-06-08 14:06:58 -0700923bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800924 // Reset vector bookkeeping.
925 vector_length_ = 0;
926 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700927 vector_static_peeling_factor_ = 0;
928 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800929 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800930 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800931
932 // Phis in the loop-body prevent vectorization.
933 if (!block->GetPhis().IsEmpty()) {
934 return false;
935 }
936
937 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
938 // occurrence, which allows passing down attributes down the use tree.
939 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
940 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
941 return false; // failure to vectorize a left-hand-side
942 }
943 }
944
Aart Bik38a3f212017-10-20 17:02:21 -0700945 // Prepare alignment analysis:
946 // (1) find desired alignment (SIMD vector size in bytes).
947 // (2) initialize static loop peeling votes (peeling factor that will
948 // make one particular reference aligned), never to exceed (1).
949 // (3) variable to record how many references share same alignment.
950 // (4) variable to record suitable candidate for dynamic loop peeling.
951 uint32_t desired_alignment = GetVectorSizeInBytes();
952 DCHECK_LE(desired_alignment, 16u);
953 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
954 uint32_t max_num_same_alignment = 0;
955 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800956
957 // Data dependence analysis. Find each pair of references with same type, where
958 // at least one is a write. Each such pair denotes a possible data dependence.
959 // This analysis exploits the property that differently typed arrays cannot be
960 // aliased, as well as the property that references either point to the same
961 // array or to two completely disjoint arrays, i.e., no partial aliasing.
962 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700963 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800964 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700965 uint32_t num_same_alignment = 0;
966 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800967 for (auto j = i; ++j != vector_refs_->end(); ) {
968 if (i->type == j->type && (i->lhs || j->lhs)) {
969 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
970 HInstruction* a = i->base;
971 HInstruction* b = j->base;
972 HInstruction* x = i->offset;
973 HInstruction* y = j->offset;
974 if (a == b) {
975 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
976 // Conservatively assume a loop-carried data dependence otherwise, and reject.
977 if (x != y) {
978 return false;
979 }
Aart Bik38a3f212017-10-20 17:02:21 -0700980 // Count the number of references that have the same alignment (since
981 // base and offset are the same) and where at least one is a write, so
982 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
983 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800984 } else {
985 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
986 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
987 // generating an explicit a != b disambiguation runtime test on the two references.
988 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700989 // To avoid excessive overhead, we only accept one a != b test.
990 if (vector_runtime_test_a_ == nullptr) {
991 // First test found.
992 vector_runtime_test_a_ = a;
993 vector_runtime_test_b_ = b;
994 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
995 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
996 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800997 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800998 }
999 }
1000 }
1001 }
Aart Bik38a3f212017-10-20 17:02:21 -07001002 // Update information for finding suitable alignment strategy:
1003 // (1) update votes for static loop peeling,
1004 // (2) update suitable candidate for dynamic loop peeling.
1005 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1006 if (alignment.Base() >= desired_alignment) {
1007 // If the array/string object has a known, sufficient alignment, use the
1008 // initial offset to compute the static loop peeling vote (this always
1009 // works, since elements have natural alignment).
1010 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1011 uint32_t vote = (offset == 0)
1012 ? 0
1013 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1014 DCHECK_LT(vote, 16u);
1015 ++peeling_votes[vote];
1016 } else if (BaseAlignment() >= desired_alignment &&
1017 num_same_alignment > max_num_same_alignment) {
1018 // Otherwise, if the array/string object has a known, sufficient alignment
1019 // for just the base but with an unknown offset, record the candidate with
1020 // the most occurrences for dynamic loop peeling (again, the peeling always
1021 // works, since elements have natural alignment).
1022 max_num_same_alignment = num_same_alignment;
1023 peeling_candidate = &(*i);
1024 }
1025 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -08001026
Aart Bik38a3f212017-10-20 17:02:21 -07001027 // Find a suitable alignment strategy.
1028 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1029
1030 // Does vectorization seem profitable?
1031 if (!IsVectorizationProfitable(trip_count)) {
1032 return false;
1033 }
Aart Bik14a68b42017-06-08 14:06:58 -07001034
Aart Bikf8f5a162017-02-06 15:35:29 -08001035 // Success!
1036 return true;
1037}
1038
1039void HLoopOptimization::Vectorize(LoopNode* node,
1040 HBasicBlock* block,
1041 HBasicBlock* exit,
1042 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001043 HBasicBlock* header = node->loop_info->GetHeader();
1044 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1045
Aart Bik14a68b42017-06-08 14:06:58 -07001046 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +01001047 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1048 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -07001049 uint32_t chunk = vector_length_ * unroll;
1050
Aart Bik38a3f212017-10-20 17:02:21 -07001051 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1052
Aart Bik14a68b42017-06-08 14:06:58 -07001053 // A cleanup loop is needed, at least, for any unknown trip count or
1054 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -07001055 bool needs_cleanup = trip_count == 0 ||
1056 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001057
1058 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -07001059 HPhi* main_phi = nullptr;
1060 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -08001061 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -07001062 vector_header_ = header;
1063 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -08001064
Aart Bikdbbac8f2017-09-01 13:06:08 -07001065 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001066 DataType::Type induc_type = main_phi->GetType();
1067 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1068 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001069
Aart Bik38a3f212017-10-20 17:02:21 -07001070 // Generate the trip count for static or dynamic loop peeling, if needed:
1071 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001072 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001073 if (vector_static_peeling_factor_ != 0) {
1074 // Static loop peeling for SIMD alignment (using the most suitable
1075 // fixed peeling factor found during prior alignment analysis).
1076 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1077 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1078 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1079 // Dynamic loop peeling for SIMD alignment (using the most suitable
1080 // candidate found during prior alignment analysis):
1081 // rem = offset % ALIGN; // adjusted as #elements
1082 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1083 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1084 uint32_t align = GetVectorSizeInBytes() >> shift;
1085 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1086 vector_dynamic_peeling_candidate_->is_string_char_at);
1087 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1088 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1089 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1090 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1091 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1092 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1093 induc_type, graph_->GetConstant(induc_type, align), rem));
1094 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1095 rem, graph_->GetConstant(induc_type, 0)));
1096 ptc = Insert(preheader, new (global_allocator_) HSelect(
1097 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1098 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001099 }
1100
1101 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001102 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001103 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001104 // vtc = stc - (stc - ptc) % chunk;
1105 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001106 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1107 HInstruction* vtc = stc;
1108 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001109 DCHECK(IsPowerOfTwo(chunk));
1110 HInstruction* diff = stc;
1111 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001112 if (trip_count == 0) {
1113 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1114 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1115 }
Aart Bik14a68b42017-06-08 14:06:58 -07001116 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1117 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001118 HInstruction* rem = Insert(
1119 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001120 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001121 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001122 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1123 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001124 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001125
1126 // Generate runtime disambiguation test:
1127 // vtc = a != b ? vtc : 0;
1128 if (vector_runtime_test_a_ != nullptr) {
1129 HInstruction* rt = Insert(
1130 preheader,
1131 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1132 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001133 new (global_allocator_)
1134 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001135 needs_cleanup = true;
1136 }
1137
Aart Bik38a3f212017-10-20 17:02:21 -07001138 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001139 // for ( ; i < ptc; i += 1)
1140 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001141 //
1142 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1143 // moved around during suspend checks, since all analysis was based on
1144 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001145 if (ptc != nullptr) {
1146 vector_mode_ = kSequential;
1147 GenerateNewLoop(node,
1148 block,
1149 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1150 vector_index_,
1151 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001152 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001153 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001154 }
1155
1156 // Generate vector loop, possibly further unrolled:
1157 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001158 // <vectorized-loop-body>
1159 vector_mode_ = kVector;
1160 GenerateNewLoop(node,
1161 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001162 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1163 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001164 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001165 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001166 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001167 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1168
1169 // Generate cleanup loop, if needed:
1170 // for ( ; i < stc; i += 1)
1171 // <loop-body>
1172 if (needs_cleanup) {
1173 vector_mode_ = kSequential;
1174 GenerateNewLoop(node,
1175 block,
1176 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001177 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001178 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001179 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001180 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001181 }
1182
Aart Bik0148de42017-09-05 09:25:01 -07001183 // Link reductions to their final uses.
1184 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1185 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001186 HInstruction* phi = i->first;
1187 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1188 // Deal with regular uses.
1189 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1190 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1191 }
1192 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001193 }
1194 }
1195
Aart Bikf8f5a162017-02-06 15:35:29 -08001196 // Remove the original loop by disconnecting the body block
1197 // and removing all instructions from the header.
1198 block->DisconnectAndDelete();
1199 while (!header->GetFirstInstruction()->IsGoto()) {
1200 header->RemoveInstruction(header->GetFirstInstruction());
1201 }
Aart Bikb29f6842017-07-28 15:58:41 -07001202
Aart Bik14a68b42017-06-08 14:06:58 -07001203 // Update loop hierarchy: the old header now resides in the same outer loop
1204 // as the old preheader. Note that we don't bother putting sequential
1205 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001206 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1207 node->loop_info = vloop;
1208}
1209
1210void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1211 HBasicBlock* block,
1212 HBasicBlock* new_preheader,
1213 HInstruction* lo,
1214 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001215 HInstruction* step,
1216 uint32_t unroll) {
1217 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001218 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001219 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001220 vector_preheader_ = new_preheader,
1221 vector_header_ = vector_preheader_->GetSingleSuccessor();
1222 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001223 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1224 kNoRegNumber,
1225 0,
1226 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001227 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001228 // for (i = lo; i < hi; i += step)
1229 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001230 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1231 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001232 vector_header_->AddInstruction(cond);
1233 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001234 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001235 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001236 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001237 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001238 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001239 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1240 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1241 DCHECK(vectorized_def);
1242 }
1243 // Generate body from the instruction map, but in original program order.
1244 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1245 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1246 auto i = vector_map_->find(it.Current());
1247 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1248 Insert(vector_body_, i->second);
1249 // Deal with instructions that need an environment, such as the scalar intrinsics.
1250 if (i->second->NeedsEnvironment()) {
1251 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1252 }
1253 }
1254 }
Aart Bik0148de42017-09-05 09:25:01 -07001255 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001256 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1257 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001258 }
Aart Bik0148de42017-09-05 09:25:01 -07001259 // Finalize phi inputs for the reductions (if any).
1260 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1261 if (!i->first->IsPhi()) {
1262 DCHECK(i->second->IsPhi());
1263 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1264 }
1265 }
Aart Bikb29f6842017-07-28 15:58:41 -07001266 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001267 phi->AddInput(lo);
1268 phi->AddInput(vector_index_);
1269 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001270}
1271
Aart Bikf8f5a162017-02-06 15:35:29 -08001272bool HLoopOptimization::VectorizeDef(LoopNode* node,
1273 HInstruction* instruction,
1274 bool generate_code) {
1275 // Accept a left-hand-side array base[index] for
1276 // (1) supported vector type,
1277 // (2) loop-invariant base,
1278 // (3) unit stride index,
1279 // (4) vectorizable right-hand-side value.
1280 uint64_t restrictions = kNone;
Georgia Kouvelibac080b2019-01-31 16:12:16 +00001281 // Don't accept expressions that can throw.
1282 if (instruction->CanThrow()) {
1283 return false;
1284 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001285 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001286 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001287 HInstruction* base = instruction->InputAt(0);
1288 HInstruction* index = instruction->InputAt(1);
1289 HInstruction* value = instruction->InputAt(2);
1290 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001291 // For narrow types, explicit type conversion may have been
1292 // optimized way, so set the no hi bits restriction here.
1293 if (DataType::Size(type) <= 2) {
1294 restrictions |= kNoHiBits;
1295 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001296 if (TrySetVectorType(type, &restrictions) &&
1297 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001298 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001299 VectorizeUse(node, value, generate_code, type, restrictions)) {
1300 if (generate_code) {
1301 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001302 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001303 } else {
1304 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1305 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001306 return true;
1307 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001308 return false;
1309 }
Aart Bik0148de42017-09-05 09:25:01 -07001310 // Accept a left-hand-side reduction for
1311 // (1) supported vector type,
1312 // (2) vectorizable right-hand-side value.
1313 auto redit = reductions_->find(instruction);
1314 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001315 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001316 // Recognize SAD idiom or direct reduction.
1317 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
Artem Serovaaac0e32018-08-07 00:52:22 +01001318 VectorizeDotProdIdiom(node, instruction, generate_code, type, restrictions) ||
Aart Bikdbbac8f2017-09-01 13:06:08 -07001319 (TrySetVectorType(type, &restrictions) &&
1320 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001321 if (generate_code) {
1322 HInstruction* new_red = vector_map_->Get(instruction);
1323 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1324 vector_permanent_map_->Overwrite(redit->second, new_red);
1325 }
1326 return true;
1327 }
1328 return false;
1329 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001330 // Branch back okay.
1331 if (instruction->IsGoto()) {
1332 return true;
1333 }
1334 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1335 // Note that actual uses are inspected during right-hand-side tree traversal.
Georgia Kouvelibac080b2019-01-31 16:12:16 +00001336 return !IsUsedOutsideLoop(node->loop_info, instruction)
1337 && !instruction->DoesAnyWrite();
Aart Bikf8f5a162017-02-06 15:35:29 -08001338}
1339
Aart Bikf8f5a162017-02-06 15:35:29 -08001340bool HLoopOptimization::VectorizeUse(LoopNode* node,
1341 HInstruction* instruction,
1342 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001343 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001344 uint64_t restrictions) {
1345 // Accept anything for which code has already been generated.
1346 if (generate_code) {
1347 if (vector_map_->find(instruction) != vector_map_->end()) {
1348 return true;
1349 }
1350 }
1351 // Continue the right-hand-side tree traversal, passing in proper
1352 // types and vector restrictions along the way. During code generation,
1353 // all new nodes are drawn from the global allocator.
1354 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1355 // Accept invariant use, using scalar expansion.
1356 if (generate_code) {
1357 GenerateVecInv(instruction, type);
1358 }
1359 return true;
1360 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001361 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001362 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1363 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001364 return false;
1365 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001366 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001367 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001368 // (2) loop-invariant base,
1369 // (3) unit stride index,
1370 // (4) vectorizable right-hand-side value.
1371 HInstruction* base = instruction->InputAt(0);
1372 HInstruction* index = instruction->InputAt(1);
1373 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001374 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001375 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001376 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001377 if (generate_code) {
1378 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001379 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001380 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001381 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001382 }
1383 return true;
1384 }
Aart Bik0148de42017-09-05 09:25:01 -07001385 } else if (instruction->IsPhi()) {
1386 // Accept particular phi operations.
1387 if (reductions_->find(instruction) != reductions_->end()) {
1388 // Deal with vector restrictions.
1389 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1390 return false;
1391 }
1392 // Accept a reduction.
1393 if (generate_code) {
1394 GenerateVecReductionPhi(instruction->AsPhi());
1395 }
1396 return true;
1397 }
1398 // TODO: accept right-hand-side induction?
1399 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001400 } else if (instruction->IsTypeConversion()) {
1401 // Accept particular type conversions.
1402 HTypeConversion* conversion = instruction->AsTypeConversion();
1403 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001404 DataType::Type from = conversion->GetInputType();
1405 DataType::Type to = conversion->GetResultType();
1406 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001407 uint32_t size_vec = DataType::Size(type);
1408 uint32_t size_from = DataType::Size(from);
1409 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001410 // Accept an integral conversion
1411 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1412 // (1b) widening from at least vector type, and
1413 // (2) vectorizable operand.
1414 if ((size_to < size_from &&
1415 size_to == size_vec &&
1416 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1417 (size_to >= size_from &&
1418 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001419 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001420 if (generate_code) {
1421 if (vector_mode_ == kVector) {
1422 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1423 } else {
1424 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1425 }
1426 }
1427 return true;
1428 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001429 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001430 DCHECK_EQ(to, type);
1431 // Accept int to float conversion for
1432 // (1) supported int,
1433 // (2) vectorizable operand.
1434 if (TrySetVectorType(from, &restrictions) &&
1435 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1436 if (generate_code) {
1437 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1438 }
1439 return true;
1440 }
1441 }
1442 return false;
1443 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1444 // Accept unary operator for vectorizable operand.
1445 HInstruction* opa = instruction->InputAt(0);
1446 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1447 if (generate_code) {
1448 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1449 }
1450 return true;
1451 }
1452 } else if (instruction->IsAdd() || instruction->IsSub() ||
1453 instruction->IsMul() || instruction->IsDiv() ||
1454 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1455 // Deal with vector restrictions.
1456 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1457 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1458 return false;
1459 }
1460 // Accept binary operator for vectorizable operands.
1461 HInstruction* opa = instruction->InputAt(0);
1462 HInstruction* opb = instruction->InputAt(1);
1463 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1464 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1465 if (generate_code) {
1466 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1467 }
1468 return true;
1469 }
1470 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001471 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001472 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1473 return true;
1474 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001475 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001476 HInstruction* opa = instruction->InputAt(0);
1477 HInstruction* opb = instruction->InputAt(1);
1478 HInstruction* r = opa;
1479 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001480 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1481 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1482 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001483 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1484 // Shifts right need extra care to account for higher order bits.
1485 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1486 if (instruction->IsShr() &&
1487 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1488 return false; // reject, unless all operands are sign-extension narrower
1489 } else if (instruction->IsUShr() &&
1490 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1491 return false; // reject, unless all operands are zero-extension narrower
1492 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001493 }
1494 // Accept shift operator for vectorizable/invariant operands.
1495 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001496 DCHECK(r != nullptr);
1497 if (generate_code && vector_mode_ != kVector) { // de-idiom
1498 r = opa;
1499 }
Aart Bik50e20d52017-05-05 14:07:29 -07001500 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001501 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001502 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001503 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001504 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001505 if (0 <= distance && distance < max_distance) {
1506 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001507 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001508 }
1509 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001510 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001511 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001512 } else if (instruction->IsAbs()) {
1513 // Deal with vector restrictions.
1514 HInstruction* opa = instruction->InputAt(0);
1515 HInstruction* r = opa;
1516 bool is_unsigned = false;
1517 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1518 return false;
1519 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1520 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1521 return false; // reject, unless operand is sign-extension narrower
1522 }
1523 // Accept ABS(x) for vectorizable operand.
1524 DCHECK(r != nullptr);
1525 if (generate_code && vector_mode_ != kVector) { // de-idiom
1526 r = opa;
1527 }
1528 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1529 if (generate_code) {
1530 GenerateVecOp(instruction,
1531 vector_map_->Get(r),
1532 nullptr,
1533 HVecOperation::ToProperType(type, is_unsigned));
1534 }
1535 return true;
1536 }
Aart Bik281c6812016-08-26 11:31:48 -07001537 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001538 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001539}
1540
Aart Bik38a3f212017-10-20 17:02:21 -07001541uint32_t HLoopOptimization::GetVectorSizeInBytes() {
Artem Serovc8150b52019-07-31 18:28:00 +01001542 if (kIsDebugBuild) {
1543 InstructionSet isa = compiler_options_->GetInstructionSet();
1544 // TODO: Remove this check when there are no implicit assumptions on the SIMD reg size.
1545 DCHECK_EQ(simd_register_size_, (isa == InstructionSet::kArm || isa == InstructionSet::kThumb2)
1546 ? 8u
1547 : 16u);
Aart Bik38a3f212017-10-20 17:02:21 -07001548 }
Artem Serovc8150b52019-07-31 18:28:00 +01001549
1550 return simd_register_size_;
Aart Bik38a3f212017-10-20 17:02:21 -07001551}
1552
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001553bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001554 const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
1555 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001556 case InstructionSet::kArm:
1557 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001558 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001559 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001560 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:
Artem Serovaaac0e32018-08-07 00:52:22 +01001564 *restrictions |= kNoDiv | kNoReduction | kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001565 return TrySetVectorLength(type, 8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001566 case DataType::Type::kUint16:
1567 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001568 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001569 return TrySetVectorLength(type, 4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001570 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001571 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001572 return TrySetVectorLength(type, 2);
Artem Serov8f7c4102017-06-21 11:21:37 +01001573 default:
1574 break;
1575 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001576 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001577 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001578 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001579 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001580 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001581 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001582 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001583 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001584 *restrictions |= kNoDiv;
Artem Serovc8150b52019-07-31 18:28:00 +01001585 return TrySetVectorLength(type, 16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001586 case DataType::Type::kUint16:
1587 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001588 *restrictions |= kNoDiv;
Artem Serovc8150b52019-07-31 18:28:00 +01001589 return TrySetVectorLength(type, 8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001590 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001591 *restrictions |= kNoDiv;
Artem Serovc8150b52019-07-31 18:28:00 +01001592 return TrySetVectorLength(type, 4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001593 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001594 *restrictions |= kNoDiv | kNoMul;
Artem Serovc8150b52019-07-31 18:28:00 +01001595 return TrySetVectorLength(type, 2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001596 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001597 *restrictions |= kNoReduction;
Artem Serovc8150b52019-07-31 18:28:00 +01001598 return TrySetVectorLength(type, 4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001599 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001600 *restrictions |= kNoReduction;
Artem Serovc8150b52019-07-31 18:28:00 +01001601 return TrySetVectorLength(type, 2);
Aart Bikf8f5a162017-02-06 15:35:29 -08001602 default:
1603 return false;
1604 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001605 case InstructionSet::kX86:
1606 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001607 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001608 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1609 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001610 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001611 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001612 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001613 *restrictions |= kNoMul |
1614 kNoDiv |
1615 kNoShift |
1616 kNoAbs |
1617 kNoSignedHAdd |
1618 kNoUnroundedHAdd |
1619 kNoSAD |
1620 kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001621 return TrySetVectorLength(type, 16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001622 case DataType::Type::kUint16:
Alex Light43f2f752019-12-04 17:48:45 +00001623 *restrictions |= kNoDiv |
1624 kNoAbs |
1625 kNoSignedHAdd |
1626 kNoUnroundedHAdd |
1627 kNoSAD |
1628 kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001629 return TrySetVectorLength(type, 8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001630 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001631 *restrictions |= kNoDiv |
1632 kNoAbs |
1633 kNoSignedHAdd |
1634 kNoUnroundedHAdd |
Alex Light43f2f752019-12-04 17:48:45 +00001635 kNoSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001636 return TrySetVectorLength(type, 8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001637 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001638 *restrictions |= kNoDiv | kNoSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001639 return TrySetVectorLength(type, 4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001640 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001641 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001642 return TrySetVectorLength(type, 2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001643 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001644 *restrictions |= kNoReduction;
Artem Serovc8150b52019-07-31 18:28:00 +01001645 return TrySetVectorLength(type, 4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001646 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001647 *restrictions |= kNoReduction;
Artem Serovc8150b52019-07-31 18:28:00 +01001648 return TrySetVectorLength(type, 2);
Aart Bikf8f5a162017-02-06 15:35:29 -08001649 default:
1650 break;
1651 } // switch type
1652 }
1653 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001654 default:
1655 return false;
1656 } // switch instruction set
1657}
1658
Artem Serovc8150b52019-07-31 18:28:00 +01001659bool HLoopOptimization::TrySetVectorLengthImpl(uint32_t length) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001660 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1661 // First time set?
1662 if (vector_length_ == 0) {
1663 vector_length_ = length;
1664 }
1665 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1666 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1667 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1668 return vector_length_ == length;
1669}
1670
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001671void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001672 if (vector_map_->find(org) == vector_map_->end()) {
1673 // In scalar code, just use a self pass-through for scalar invariants
1674 // (viz. expression remains itself).
1675 if (vector_mode_ == kSequential) {
1676 vector_map_->Put(org, org);
1677 return;
1678 }
1679 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001680 HInstruction* vector = nullptr;
1681 auto it = vector_permanent_map_->find(org);
1682 if (it != vector_permanent_map_->end()) {
1683 vector = it->second; // reuse during unrolling
1684 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001685 // Generates ReplicateScalar( (optional_type_conv) org ).
1686 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001687 DataType::Type input_type = input->GetType();
1688 if (type != input_type && (type == DataType::Type::kInt64 ||
1689 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001690 input = Insert(vector_preheader_,
1691 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1692 }
1693 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001694 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001695 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1696 }
1697 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001698 }
1699}
1700
1701void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1702 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001703 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001704 int64_t value = 0;
1705 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001706 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001707 if (org->IsPhi()) {
1708 Insert(vector_body_, subscript); // lacks layout placeholder
1709 }
1710 }
1711 vector_map_->Put(org, subscript);
1712 }
1713}
1714
1715void HLoopOptimization::GenerateVecMem(HInstruction* org,
1716 HInstruction* opa,
1717 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001718 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001719 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001720 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001721 HInstruction* vector = nullptr;
1722 if (vector_mode_ == kVector) {
1723 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001724 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001725 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001726 if (opb != nullptr) {
1727 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001728 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001729 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001730 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001731 vector = new (global_allocator_) HVecLoad(global_allocator_,
1732 base,
1733 opa,
1734 type,
1735 org->GetSideEffects(),
1736 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001737 is_string_char_at,
1738 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001739 }
Aart Bik38a3f212017-10-20 17:02:21 -07001740 // Known (forced/adjusted/original) alignment?
1741 if (vector_dynamic_peeling_candidate_ != nullptr) {
1742 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1743 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1744 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1745 vector->AsVecMemoryOperation()->SetAlignment( // forced
1746 Alignment(GetVectorSizeInBytes(), 0));
1747 }
1748 } else {
1749 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1750 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001751 }
1752 } else {
1753 // Scalar store or load.
1754 DCHECK(vector_mode_ == kSequential);
1755 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001756 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001757 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001758 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001759 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001760 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1761 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001762 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001763 }
1764 }
1765 vector_map_->Put(org, vector);
1766}
1767
Aart Bik0148de42017-09-05 09:25:01 -07001768void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1769 DCHECK(reductions_->find(phi) != reductions_->end());
1770 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1771 HInstruction* vector = nullptr;
1772 if (vector_mode_ == kSequential) {
1773 HPhi* new_phi = new (global_allocator_) HPhi(
1774 global_allocator_, kNoRegNumber, 0, phi->GetType());
1775 vector_header_->AddPhi(new_phi);
1776 vector = new_phi;
1777 } else {
1778 // Link vector reduction back to prior unrolled update, or a first phi.
1779 auto it = vector_permanent_map_->find(phi);
1780 if (it != vector_permanent_map_->end()) {
1781 vector = it->second;
1782 } else {
1783 HPhi* new_phi = new (global_allocator_) HPhi(
1784 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1785 vector_header_->AddPhi(new_phi);
1786 vector = new_phi;
1787 }
1788 }
1789 vector_map_->Put(phi, vector);
1790}
1791
1792void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1793 HInstruction* new_phi = vector_map_->Get(phi);
1794 HInstruction* new_init = reductions_->Get(phi);
1795 HInstruction* new_red = vector_map_->Get(reduction);
1796 // Link unrolled vector loop back to new phi.
1797 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1798 DCHECK(new_phi->IsVecOperation());
1799 }
1800 // Prepare the new initialization.
1801 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001802 // Generate a [initial, 0, .., 0] vector for add or
1803 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001804 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001805 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001806 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001807 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001808 if (kind == HVecReduce::ReductionKind::kSum) {
1809 new_init = Insert(vector_preheader_,
1810 new (global_allocator_) HVecSetScalars(global_allocator_,
1811 &new_init,
1812 type,
1813 vector_length,
1814 1,
1815 kNoDexPc));
1816 } else {
1817 new_init = Insert(vector_preheader_,
1818 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1819 new_init,
1820 type,
1821 vector_length,
1822 kNoDexPc));
1823 }
Aart Bik0148de42017-09-05 09:25:01 -07001824 } else {
1825 new_init = ReduceAndExtractIfNeeded(new_init);
1826 }
1827 // Set the phi inputs.
1828 DCHECK(new_phi->IsPhi());
1829 new_phi->AsPhi()->AddInput(new_init);
1830 new_phi->AsPhi()->AddInput(new_red);
1831 // New feed value for next phi (safe mutation in iteration).
1832 reductions_->find(phi)->second = new_phi;
1833}
1834
1835HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1836 if (instruction->IsPhi()) {
1837 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001838 if (HVecOperation::ReturnsSIMDValue(input)) {
1839 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001840 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001841 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001842 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001843 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001844 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1845 // Generate a vector reduction and scalar extract
1846 // x = REDUCE( [x_1, .., x_n] )
1847 // y = x_1
1848 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001849 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001850 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001851 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1852 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001853 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001854 exit->InsertInstructionAfter(instruction, reduce);
1855 }
1856 }
1857 return instruction;
1858}
1859
Aart Bikf8f5a162017-02-06 15:35:29 -08001860#define GENERATE_VEC(x, y) \
1861 if (vector_mode_ == kVector) { \
1862 vector = (x); \
1863 } else { \
1864 DCHECK(vector_mode_ == kSequential); \
1865 vector = (y); \
1866 } \
1867 break;
1868
1869void HLoopOptimization::GenerateVecOp(HInstruction* org,
1870 HInstruction* opa,
1871 HInstruction* opb,
Aart Bik3f08e9b2018-05-01 13:42:03 -07001872 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001873 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001874 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001875 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001876 switch (org->GetKind()) {
1877 case HInstruction::kNeg:
1878 DCHECK(opb == nullptr);
1879 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001880 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1881 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001882 case HInstruction::kNot:
1883 DCHECK(opb == nullptr);
1884 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001885 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1886 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001887 case HInstruction::kBooleanNot:
1888 DCHECK(opb == nullptr);
1889 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001890 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1891 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001892 case HInstruction::kTypeConversion:
1893 DCHECK(opb == nullptr);
1894 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001895 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1896 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001897 case HInstruction::kAdd:
1898 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001899 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1900 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001901 case HInstruction::kSub:
1902 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001903 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1904 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001905 case HInstruction::kMul:
1906 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001907 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1908 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001909 case HInstruction::kDiv:
1910 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001911 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1912 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001913 case HInstruction::kAnd:
1914 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001915 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1916 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001917 case HInstruction::kOr:
1918 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001919 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1920 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001921 case HInstruction::kXor:
1922 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001923 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1924 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001925 case HInstruction::kShl:
1926 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001927 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1928 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001929 case HInstruction::kShr:
1930 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001931 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1932 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001933 case HInstruction::kUShr:
1934 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001935 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1936 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001937 case HInstruction::kAbs:
1938 DCHECK(opb == nullptr);
1939 GENERATE_VEC(
1940 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1941 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001942 default:
1943 break;
1944 } // switch
1945 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1946 vector_map_->Put(org, vector);
1947}
1948
1949#undef GENERATE_VEC
1950
1951//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001952// Vectorization idioms.
1953//
1954
1955// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001956// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1957// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001958// Provided that the operands are promoted to a wider form to do the arithmetic and
1959// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1960// implementation that operates directly in narrower form (plus one extra bit).
1961// TODO: current version recognizes implicit byte/short/char widening only;
1962// explicit widening from int to long could be added later.
1963bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1964 HInstruction* instruction,
1965 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001966 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001967 uint64_t restrictions) {
1968 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001969 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001970 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001971 if ((instruction->IsShr() ||
1972 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001973 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001974 // Test for (a + b + c) >> 1 for optional constant c.
1975 HInstruction* a = nullptr;
1976 HInstruction* b = nullptr;
1977 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001978 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07001979 // Accept c == 1 (rounded) or c == 0 (not rounded).
1980 bool is_rounded = false;
1981 if (c == 1) {
1982 is_rounded = true;
1983 } else if (c != 0) {
1984 return false;
1985 }
1986 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001987 HInstruction* r = nullptr;
1988 HInstruction* s = nullptr;
1989 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001990 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001991 return false;
1992 }
1993 // Deal with vector restrictions.
1994 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1995 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1996 return false;
1997 }
1998 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1999 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002000 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002001 if (generate_code && vector_mode_ != kVector) { // de-idiom
2002 r = instruction->InputAt(0);
2003 s = instruction->InputAt(1);
2004 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002005 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2006 VectorizeUse(node, s, generate_code, type, restrictions)) {
2007 if (generate_code) {
2008 if (vector_mode_ == kVector) {
2009 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2010 global_allocator_,
2011 vector_map_->Get(r),
2012 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002013 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002014 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002015 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002016 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002017 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002018 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002019 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002020 }
2021 }
2022 return true;
2023 }
2024 }
2025 }
2026 return false;
2027}
2028
Aart Bikdbbac8f2017-09-01 13:06:08 -07002029// Method recognizes the following idiom:
2030// q += ABS(a - b) for signed operands a, b
2031// Provided that the operands have the same type or are promoted to a wider form.
2032// Since this may involve a vector length change, the idiom is handled by going directly
2033// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2034// TODO: unsigned SAD too?
2035bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2036 HInstruction* instruction,
2037 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002038 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002039 uint64_t restrictions) {
2040 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2041 // are done in the same precision (either int or long).
2042 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002043 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002044 return false;
2045 }
Artem Serove521eb02020-02-27 18:51:24 +00002046 HInstruction* acc = instruction->InputAt(0);
2047 HInstruction* abs = instruction->InputAt(1);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002048 HInstruction* a = nullptr;
2049 HInstruction* b = nullptr;
Artem Serove521eb02020-02-27 18:51:24 +00002050 if (abs->IsAbs() &&
2051 abs->GetType() == reduction_type &&
2052 IsSubConst2(graph_, abs->InputAt(0), /*out*/ &a, /*out*/ &b)) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002053 DCHECK(a != nullptr && b != nullptr);
2054 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002055 return false;
2056 }
2057 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2058 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002059 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002060 HInstruction* r = a;
2061 HInstruction* s = b;
2062 bool is_unsigned = false;
Artem Serovaaac0e32018-08-07 00:52:22 +01002063 DataType::Type sub_type = GetNarrowerType(a, b);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002064 if (reduction_type != sub_type &&
2065 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2066 return false;
2067 }
2068 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002069 if (!TrySetVectorType(sub_type, &restrictions) ||
2070 HasVectorRestrictions(restrictions, kNoSAD) ||
2071 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002072 return false;
2073 }
2074 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2075 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002076 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002077 if (generate_code && vector_mode_ != kVector) { // de-idiom
Artem Serove521eb02020-02-27 18:51:24 +00002078 r = s = abs->InputAt(0);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002079 }
Artem Serove521eb02020-02-27 18:51:24 +00002080 if (VectorizeUse(node, acc, generate_code, sub_type, restrictions) &&
Aart Bikdbbac8f2017-09-01 13:06:08 -07002081 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2082 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2083 if (generate_code) {
2084 if (vector_mode_ == kVector) {
2085 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2086 global_allocator_,
Artem Serove521eb02020-02-27 18:51:24 +00002087 vector_map_->Get(acc),
Aart Bikdbbac8f2017-09-01 13:06:08 -07002088 vector_map_->Get(r),
2089 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002090 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002091 GetOtherVL(reduction_type, sub_type, vector_length_),
2092 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002093 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2094 } else {
Artem Serove521eb02020-02-27 18:51:24 +00002095 // "GenerateVecOp()" must not be called more than once for each original loop body
2096 // instruction. As the SAD idiom processes both "current" instruction ("instruction")
2097 // and its ABS input in one go, we must check that for the scalar case the ABS instruction
2098 // has not yet been processed.
2099 if (vector_map_->find(abs) == vector_map_->end()) {
2100 GenerateVecOp(abs, vector_map_->Get(r), nullptr, reduction_type);
2101 }
2102 GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(abs), reduction_type);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002103 }
2104 }
2105 return true;
2106 }
2107 return false;
2108}
2109
Artem Serovaaac0e32018-08-07 00:52:22 +01002110// Method recognises the following dot product idiom:
2111// q += a * b for operands a, b whose type is narrower than the reduction one.
2112// Provided that the operands have the same type or are promoted to a wider form.
2113// Since this may involve a vector length change, the idiom is handled by going directly
2114// to a dot product node (rather than relying combining finer grained nodes later).
2115bool HLoopOptimization::VectorizeDotProdIdiom(LoopNode* node,
2116 HInstruction* instruction,
2117 bool generate_code,
2118 DataType::Type reduction_type,
2119 uint64_t restrictions) {
Alex Light43f2f752019-12-04 17:48:45 +00002120 if (!instruction->IsAdd() || reduction_type != DataType::Type::kInt32) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002121 return false;
2122 }
2123
Artem Serove521eb02020-02-27 18:51:24 +00002124 HInstruction* const acc = instruction->InputAt(0);
2125 HInstruction* const mul = instruction->InputAt(1);
2126 if (!mul->IsMul() || mul->GetType() != reduction_type) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002127 return false;
2128 }
2129
Artem Serove521eb02020-02-27 18:51:24 +00002130 HInstruction* const mul_left = mul->InputAt(0);
2131 HInstruction* const mul_right = mul->InputAt(1);
2132 HInstruction* r = mul_left;
2133 HInstruction* s = mul_right;
2134 DataType::Type op_type = GetNarrowerType(mul_left, mul_right);
Artem Serovaaac0e32018-08-07 00:52:22 +01002135 bool is_unsigned = false;
2136
Artem Serove521eb02020-02-27 18:51:24 +00002137 if (!IsNarrowerOperands(mul_left, mul_right, op_type, &r, &s, &is_unsigned)) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002138 return false;
2139 }
2140 op_type = HVecOperation::ToProperType(op_type, is_unsigned);
2141
2142 if (!TrySetVectorType(op_type, &restrictions) ||
2143 HasVectorRestrictions(restrictions, kNoDotProd)) {
2144 return false;
2145 }
2146
2147 DCHECK(r != nullptr && s != nullptr);
2148 // Accept dot product idiom for vectorizable operands. Vectorized code uses the shorthand
2149 // idiomatic operation. Sequential code uses the original scalar expressions.
2150 if (generate_code && vector_mode_ != kVector) { // de-idiom
Artem Serove521eb02020-02-27 18:51:24 +00002151 r = mul_left;
2152 s = mul_right;
Artem Serovaaac0e32018-08-07 00:52:22 +01002153 }
Artem Serove521eb02020-02-27 18:51:24 +00002154 if (VectorizeUse(node, acc, generate_code, op_type, restrictions) &&
Artem Serovaaac0e32018-08-07 00:52:22 +01002155 VectorizeUse(node, r, generate_code, op_type, restrictions) &&
2156 VectorizeUse(node, s, generate_code, op_type, restrictions)) {
2157 if (generate_code) {
2158 if (vector_mode_ == kVector) {
2159 vector_map_->Put(instruction, new (global_allocator_) HVecDotProd(
2160 global_allocator_,
Artem Serove521eb02020-02-27 18:51:24 +00002161 vector_map_->Get(acc),
Artem Serovaaac0e32018-08-07 00:52:22 +01002162 vector_map_->Get(r),
2163 vector_map_->Get(s),
2164 reduction_type,
2165 is_unsigned,
2166 GetOtherVL(reduction_type, op_type, vector_length_),
2167 kNoDexPc));
2168 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2169 } else {
Artem Serove521eb02020-02-27 18:51:24 +00002170 // "GenerateVecOp()" must not be called more than once for each original loop body
2171 // instruction. As the DotProd idiom processes both "current" instruction ("instruction")
2172 // and its MUL input in one go, we must check that for the scalar case the MUL instruction
2173 // has not yet been processed.
2174 if (vector_map_->find(mul) == vector_map_->end()) {
2175 GenerateVecOp(mul, vector_map_->Get(r), vector_map_->Get(s), reduction_type);
2176 }
2177 GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(mul), reduction_type);
Artem Serovaaac0e32018-08-07 00:52:22 +01002178 }
2179 }
2180 return true;
2181 }
2182 return false;
2183}
2184
Aart Bikf3e61ee2017-04-12 17:09:20 -07002185//
Aart Bik14a68b42017-06-08 14:06:58 -07002186// Vectorization heuristics.
2187//
2188
Aart Bik38a3f212017-10-20 17:02:21 -07002189Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2190 DataType::Type type,
2191 bool is_string_char_at,
2192 uint32_t peeling) {
2193 // Combine the alignment and hidden offset that is guaranteed by
2194 // the Android runtime with a known starting index adjusted as bytes.
2195 int64_t value = 0;
2196 if (IsInt64AndGet(offset, /*out*/ &value)) {
2197 uint32_t start_offset =
2198 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2199 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2200 }
2201 // Otherwise, the Android runtime guarantees at least natural alignment.
2202 return Alignment(DataType::Size(type), 0);
2203}
2204
2205void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2206 const ArrayReference* peeling_candidate) {
2207 // Current heuristic: pick the best static loop peeling factor, if any,
2208 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2209 uint32_t max_vote = 0;
2210 for (int32_t i = 0; i < 16; i++) {
2211 if (peeling_votes[i] > max_vote) {
2212 max_vote = peeling_votes[i];
2213 vector_static_peeling_factor_ = i;
2214 }
2215 }
2216 if (max_vote == 0) {
2217 vector_dynamic_peeling_candidate_ = peeling_candidate;
2218 }
2219}
2220
2221uint32_t HLoopOptimization::MaxNumberPeeled() {
2222 if (vector_dynamic_peeling_candidate_ != nullptr) {
2223 return vector_length_ - 1u; // worst-case
2224 }
2225 return vector_static_peeling_factor_; // known exactly
2226}
2227
Aart Bik14a68b42017-06-08 14:06:58 -07002228bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002229 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002230 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002231 // TODO: trip count is really unsigned entity, provided the guarding test
2232 // is satisfied; deal with this more carefully later
2233 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002234 if (vector_length_ == 0) {
2235 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002236 } else if (trip_count < 0) {
2237 return false; // guard against non-taken/large
2238 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002239 return false; // insufficient iterations
2240 }
2241 return true;
2242}
2243
Aart Bik14a68b42017-06-08 14:06:58 -07002244//
Aart Bikf8f5a162017-02-06 15:35:29 -08002245// Helpers.
2246//
2247
2248bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002249 // Start with empty phi induction.
2250 iset_->clear();
2251
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002252 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2253 // smart enough to follow strongly connected components (and it's probably not worth
2254 // it to make it so). See b/33775412.
2255 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2256 return false;
2257 }
Aart Bikb29f6842017-07-28 15:58:41 -07002258
2259 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002260 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2261 if (set != nullptr) {
2262 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002263 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002264 // each instruction is removable and, when restrict uses are requested, other than for phi,
2265 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002266 if (!i->IsInBlock()) {
2267 continue;
2268 } else if (!i->IsRemovable()) {
2269 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002270 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002271 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002272 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2273 if (set->find(use.GetUser()) == set->end()) {
2274 return false;
2275 }
2276 }
2277 }
Aart Bike3dedc52016-11-02 17:50:27 -07002278 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002279 }
Aart Bikcc42be02016-10-20 16:14:16 -07002280 return true;
2281 }
2282 return false;
2283}
2284
Aart Bikb29f6842017-07-28 15:58:41 -07002285bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002286 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002287 // Only unclassified phi cycles are candidates for reductions.
2288 if (induction_range_.IsClassified(phi)) {
2289 return false;
2290 }
2291 // Accept operations like x = x + .., provided that the phi and the reduction are
2292 // used exactly once inside the loop, and by each other.
2293 HInputsRef inputs = phi->GetInputs();
2294 if (inputs.size() == 2) {
2295 HInstruction* reduction = inputs[1];
2296 if (HasReductionFormat(reduction, phi)) {
2297 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002298 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002299 bool single_use_inside_loop =
2300 // Reduction update only used by phi.
2301 reduction->GetUses().HasExactlyOneElement() &&
2302 !reduction->HasEnvironmentUses() &&
2303 // Reduction update is only use of phi inside the loop.
2304 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2305 iset_->size() == 1;
2306 iset_->clear(); // leave the way you found it
2307 if (single_use_inside_loop) {
2308 // Link reduction back, and start recording feed value.
2309 reductions_->Put(reduction, phi);
2310 reductions_->Put(phi, phi->InputAt(0));
2311 return true;
2312 }
2313 }
2314 }
2315 return false;
2316}
2317
2318bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2319 // Start with empty phi induction and reductions.
2320 iset_->clear();
2321 reductions_->clear();
2322
2323 // Scan the phis to find the following (the induction structure has already
2324 // been optimized, so we don't need to worry about trivial cases):
2325 // (1) optional reductions in loop,
2326 // (2) the main induction, used in loop control.
2327 HPhi* phi = nullptr;
2328 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2329 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2330 continue;
2331 } else if (phi == nullptr) {
2332 // Found the first candidate for main induction.
2333 phi = it.Current()->AsPhi();
2334 } else {
2335 return false;
2336 }
2337 }
2338
2339 // Then test for a typical loopheader:
2340 // s: SuspendCheck
2341 // c: Condition(phi, bound)
2342 // i: If(c)
2343 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002344 HInstruction* s = block->GetFirstInstruction();
2345 if (s != nullptr && s->IsSuspendCheck()) {
2346 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002347 if (c != nullptr &&
2348 c->IsCondition() &&
2349 c->GetUses().HasExactlyOneElement() && // only used for termination
2350 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002351 HInstruction* i = c->GetNext();
2352 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2353 iset_->insert(c);
2354 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002355 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002356 return true;
2357 }
2358 }
2359 }
2360 }
2361 return false;
2362}
2363
2364bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002365 if (!block->GetPhis().IsEmpty()) {
2366 return false;
2367 }
2368 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2369 HInstruction* instruction = it.Current();
2370 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2371 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002372 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002373 }
2374 return true;
2375}
2376
2377bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2378 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002379 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002380 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2381 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2382 return true;
2383 }
Aart Bikcc42be02016-10-20 16:14:16 -07002384 }
2385 return false;
2386}
2387
Aart Bik482095d2016-10-10 15:39:10 -07002388bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002389 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002390 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002391 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002392 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002393 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2394 HInstruction* user = use.GetUser();
2395 if (iset_->find(user) == iset_->end()) { // not excluded?
2396 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002397 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002398 // If collect_loop_uses is set, simply keep adding those uses to the set.
2399 // Otherwise, reject uses inside the loop that were not already in the set.
2400 if (collect_loop_uses) {
2401 iset_->insert(user);
2402 continue;
2403 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002404 return false;
2405 }
2406 ++*use_count;
2407 }
2408 }
2409 return true;
2410}
2411
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002412bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2413 HInstruction* instruction,
2414 HBasicBlock* block) {
2415 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002416 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002417 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002418 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002419 const HUseList<HInstruction*>& uses = instruction->GetUses();
2420 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2421 HInstruction* user = it->GetUser();
2422 size_t index = it->GetIndex();
2423 ++it; // increment before replacing
2424 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002425 if (kIsDebugBuild) {
2426 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2427 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2428 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2429 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002430 user->ReplaceInput(replacement, index);
2431 induction_range_.Replace(user, instruction, replacement); // update induction
2432 }
2433 }
Aart Bikb29f6842017-07-28 15:58:41 -07002434 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002435 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2436 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2437 HEnvironment* user = it->GetUser();
2438 size_t index = it->GetIndex();
2439 ++it; // increment before replacing
2440 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002441 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002442 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002443 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2444 user->RemoveAsUserOfInput(index);
2445 user->SetRawEnvAt(index, replacement);
2446 replacement->AddEnvUseAt(user, index);
2447 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002448 }
2449 }
Aart Bik807868e2016-11-03 17:51:43 -07002450 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002451 }
Aart Bik807868e2016-11-03 17:51:43 -07002452 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002453}
2454
Aart Bikf8f5a162017-02-06 15:35:29 -08002455bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2456 HInstruction* instruction,
2457 HBasicBlock* block,
2458 bool collect_loop_uses) {
2459 // Assigning the last value is always successful if there are no uses.
2460 // Otherwise, it succeeds in a no early-exit loop by generating the
2461 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002462 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002463 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2464 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002465 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002466}
2467
Aart Bik6b69e0a2017-01-11 10:20:43 -08002468void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2469 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2470 HInstruction* instruction = i.Current();
2471 if (instruction->IsDeadAndRemovable()) {
2472 simplified_ = true;
2473 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2474 }
2475 }
2476}
2477
Aart Bik14a68b42017-06-08 14:06:58 -07002478bool HLoopOptimization::CanRemoveCycle() {
2479 for (HInstruction* i : *iset_) {
2480 // We can never remove instructions that have environment
2481 // uses when we compile 'debuggable'.
2482 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2483 return false;
2484 }
2485 // A deoptimization should never have an environment input removed.
2486 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2487 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2488 return false;
2489 }
2490 }
2491 }
2492 return true;
2493}
2494
Aart Bik281c6812016-08-26 11:31:48 -07002495} // namespace art