blob: 02ee4ec057c602e4d0a6350b7b8fe1d934d5627d [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),
Artem Serov8ba4de12019-12-04 21:10:23 +0000476 predicated_vectorization_mode_(codegen.SupportsPredicatedSIMD()),
Aart Bikf8f5a162017-02-06 15:35:29 -0800477 vector_length_(0),
478 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700479 vector_static_peeling_factor_(0),
480 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700481 vector_runtime_test_a_(nullptr),
482 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700483 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100484 vector_permanent_map_(nullptr),
485 vector_mode_(kSequential),
486 vector_preheader_(nullptr),
487 vector_header_(nullptr),
488 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100489 vector_index_(nullptr),
Artem Serov8ba4de12019-12-04 21:10:23 +0000490 arch_loop_helper_(ArchNoOptsLoopHelper::Create(codegen, global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700491}
492
Aart Bik24773202018-04-26 10:28:51 -0700493bool HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800494 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700495 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800496 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik24773202018-04-26 10:28:51 -0700497 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700498 }
499
Vladimir Markoca6fff82017-10-03 14:49:14 +0100500 // Phase-local allocator.
501 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700502 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100503
Aart Bik96202302016-10-04 17:33:56 -0700504 // Perform loop optimizations.
Aart Bik24773202018-04-26 10:28:51 -0700505 bool didLoopOpt = LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800506 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800507 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800508 }
509
Aart Bik96202302016-10-04 17:33:56 -0700510 // Detach.
511 loop_allocator_ = nullptr;
512 last_loop_ = top_loop_ = nullptr;
Aart Bik24773202018-04-26 10:28:51 -0700513
514 return didLoopOpt;
Aart Bik96202302016-10-04 17:33:56 -0700515}
516
Aart Bikb29f6842017-07-28 15:58:41 -0700517//
518// Loop setup and traversal.
519//
520
Aart Bik24773202018-04-26 10:28:51 -0700521bool HLoopOptimization::LocalRun() {
522 bool didLoopOpt = false;
Aart Bik96202302016-10-04 17:33:56 -0700523 // Build the linear order using the phase-local allocator. This step enables building
524 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100525 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
526 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700527
Aart Bik281c6812016-08-26 11:31:48 -0700528 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700529 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700530 if (block->IsLoopHeader()) {
531 AddLoop(block->GetLoopInformation());
532 }
533 }
Aart Bik96202302016-10-04 17:33:56 -0700534
Aart Bik8c4a8542016-10-06 11:36:57 -0700535 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800536 // temporary data structures using the phase-local allocator. All new HIR
537 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700538 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100539 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
540 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700541 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100542 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
543 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800544 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100545 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700546 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800547 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700548 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700549 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800550 vector_refs_ = &refs;
551 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700552 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800553 // Traverse.
Aart Bik24773202018-04-26 10:28:51 -0700554 didLoopOpt = TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800555 // Detach.
556 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700557 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800558 vector_refs_ = nullptr;
559 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700560 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700561 }
Aart Bik24773202018-04-26 10:28:51 -0700562 return didLoopOpt;
Aart Bik281c6812016-08-26 11:31:48 -0700563}
564
565void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
566 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800567 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700568 if (last_loop_ == nullptr) {
569 // First loop.
570 DCHECK(top_loop_ == nullptr);
571 last_loop_ = top_loop_ = node;
572 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
573 // Inner loop.
574 node->outer = last_loop_;
575 DCHECK(last_loop_->inner == nullptr);
576 last_loop_ = last_loop_->inner = node;
577 } else {
578 // Subsequent loop.
579 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
580 last_loop_ = last_loop_->outer;
581 }
582 node->outer = last_loop_->outer;
583 node->previous = last_loop_;
584 DCHECK(last_loop_->next == nullptr);
585 last_loop_ = last_loop_->next = node;
586 }
587}
588
589void HLoopOptimization::RemoveLoop(LoopNode* node) {
590 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700591 DCHECK(node->inner == nullptr);
592 if (node->previous != nullptr) {
593 // Within sequence.
594 node->previous->next = node->next;
595 if (node->next != nullptr) {
596 node->next->previous = node->previous;
597 }
598 } else {
599 // First of sequence.
600 if (node->outer != nullptr) {
601 node->outer->inner = node->next;
602 } else {
603 top_loop_ = node->next;
604 }
605 if (node->next != nullptr) {
606 node->next->outer = node->outer;
607 node->next->previous = nullptr;
608 }
609 }
Aart Bik281c6812016-08-26 11:31:48 -0700610}
611
Aart Bikb29f6842017-07-28 15:58:41 -0700612bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
613 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700614 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700615 // Visit inner loops first. Recompute induction information for this
616 // loop if the induction of any inner loop has changed.
617 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700618 induction_range_.ReVisit(node->loop_info);
Aart Bika8360cd2018-05-02 16:07:51 -0700619 changed = true;
Aart Bik482095d2016-10-10 15:39:10 -0700620 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800621 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800622 // Note that since each simplification consists of eliminating code (without
623 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800624 do {
625 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800626 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800627 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700628 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800629 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800630 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700631 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700632 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700633 }
Aart Bik281c6812016-08-26 11:31:48 -0700634 }
Aart Bikb29f6842017-07-28 15:58:41 -0700635 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700636}
637
Aart Bikf8f5a162017-02-06 15:35:29 -0800638//
639// Optimization.
640//
641
Aart Bik281c6812016-08-26 11:31:48 -0700642void HLoopOptimization::SimplifyInduction(LoopNode* node) {
643 HBasicBlock* header = node->loop_info->GetHeader();
644 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700645 // Scan the phis in the header to find opportunities to simplify an induction
646 // cycle that is only used outside the loop. Replace these uses, if any, with
647 // the last value and remove the induction cycle.
648 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
649 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700650 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
651 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800652 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
653 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700654 // Note that it's ok to have replaced uses after the loop with the last value, without
655 // being able to remove the cycle. Environment uses (which are the reason we may not be
656 // able to remove the cycle) within the loop will still hold the right value. We must
657 // have tried first, however, to replace outside uses.
658 if (CanRemoveCycle()) {
659 simplified_ = true;
660 for (HInstruction* i : *iset_) {
661 RemoveFromCycle(i);
662 }
663 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700664 }
Aart Bik482095d2016-10-10 15:39:10 -0700665 }
666 }
667}
668
669void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800670 // Iterate over all basic blocks in the loop-body.
671 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
672 HBasicBlock* block = it.Current();
673 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800674 RemoveDeadInstructions(block->GetPhis());
675 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800676 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800677 if (block->GetPredecessors().size() == 1 &&
678 block->GetSuccessors().size() == 1 &&
679 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800680 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800681 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800682 } else if (block->GetSuccessors().size() == 2) {
683 // Trivial if block can be bypassed to either branch.
684 HBasicBlock* succ0 = block->GetSuccessors()[0];
685 HBasicBlock* succ1 = block->GetSuccessors()[1];
686 HBasicBlock* meet0 = nullptr;
687 HBasicBlock* meet1 = nullptr;
688 if (succ0 != succ1 &&
689 IsGotoBlock(succ0, &meet0) &&
690 IsGotoBlock(succ1, &meet1) &&
691 meet0 == meet1 && // meets again
692 meet0 != block && // no self-loop
693 meet0->GetPhis().IsEmpty()) { // not used for merging
694 simplified_ = true;
695 succ0->DisconnectAndDelete();
696 if (block->Dominates(meet0)) {
697 block->RemoveDominatedBlock(meet0);
698 succ1->AddDominatedBlock(meet0);
699 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700700 }
Aart Bik482095d2016-10-10 15:39:10 -0700701 }
Aart Bik281c6812016-08-26 11:31:48 -0700702 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800703 }
Aart Bik281c6812016-08-26 11:31:48 -0700704}
705
Artem Serov121f2032017-10-23 19:19:06 +0100706bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700707 HBasicBlock* header = node->loop_info->GetHeader();
708 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700709 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800710 int64_t trip_count = 0;
711 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700712 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700713 }
Aart Bik281c6812016-08-26 11:31:48 -0700714 // Ensure there is only a single loop-body (besides the header).
715 HBasicBlock* body = nullptr;
716 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
717 if (it.Current() != header) {
718 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700719 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700720 }
721 body = it.Current();
722 }
723 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700724 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700725 // Ensure there is only a single exit point.
726 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700727 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700728 }
729 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
730 ? header->GetSuccessors()[1]
731 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700732 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700733 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700734 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700735 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800736 // Detect either an empty loop (no side effects other than plain iteration) or
737 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
738 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700739 HPhi* main_phi = nullptr;
740 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800741 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700742 if (reductions_->empty() && // TODO: possible with some effort
743 (is_empty || trip_count == 1) &&
744 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800745 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800746 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700747 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800748 preheader->MergeInstructionsWith(body);
749 }
750 body->DisconnectAndDelete();
751 exit->RemovePredecessor(header);
752 header->RemoveSuccessor(exit);
753 header->RemoveDominatedBlock(exit);
754 header->DisconnectAndDelete();
755 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800756 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800757 preheader->AddDominatedBlock(exit);
758 exit->SetDominator(preheader);
759 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700760 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800761 }
762 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800763 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700764 if (kEnableVectorization &&
Artem Serove65ade72019-07-25 21:04:16 +0100765 // Disable vectorization for debuggable graphs: this is a workaround for the bug
766 // in 'GenerateNewLoop' which caused the SuspendCheck environment to be invalid.
767 // TODO: b/138601207, investigate other possible cases with wrong environment values and
768 // possibly switch back vectorization on for debuggable graphs.
769 !graph_->IsDebuggable() &&
Aart Bikb29f6842017-07-28 15:58:41 -0700770 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700771 ShouldVectorize(node, body, trip_count) &&
772 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
773 Vectorize(node, body, exit, trip_count);
774 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700775 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700776 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800777 }
Aart Bikb29f6842017-07-28 15:58:41 -0700778 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800779}
780
Artem Serov121f2032017-10-23 19:19:06 +0100781bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Nicolas Geoffray8f6b99f2021-09-28 17:51:17 +0000782 return TryOptimizeInnerLoopFinite(node) || TryPeelingAndUnrolling(node);
Artem Serov121f2032017-10-23 19:19:06 +0100783}
784
Artem Serov121f2032017-10-23 19:19:06 +0100785
Artem Serov121f2032017-10-23 19:19:06 +0100786
787//
Artem Serov0e329082018-06-12 10:23:27 +0100788// Scalar loop peeling and unrolling: generic part methods.
Artem Serov121f2032017-10-23 19:19:06 +0100789//
790
Artem Serov0e329082018-06-12 10:23:27 +0100791bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
792 bool generate_code) {
793 if (analysis_info->GetNumberOfExits() > 1) {
Artem Serov121f2032017-10-23 19:19:06 +0100794 return false;
795 }
796
Artem Serov0e329082018-06-12 10:23:27 +0100797 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
798 if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
Artem Serov121f2032017-10-23 19:19:06 +0100799 return false;
800 }
801
Artem Serov0e329082018-06-12 10:23:27 +0100802 if (generate_code) {
803 // TODO: support other unrolling factors.
804 DCHECK_EQ(unrolling_factor, 2u);
805
806 // Perform unrolling.
807 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov0f5b2bf2019-10-23 14:07:41 +0100808 LoopClonerSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100809 helper.DoUnrolling();
810
811 // Remove the redundant loop check after unrolling.
812 HIf* copy_hif =
813 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
814 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
815 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
Artem Serov121f2032017-10-23 19:19:06 +0100816 }
Artem Serov121f2032017-10-23 19:19:06 +0100817 return true;
818}
819
Artem Serov0e329082018-06-12 10:23:27 +0100820bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
821 bool generate_code) {
822 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov72411e62017-10-19 16:18:07 +0100823 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
824 return false;
825 }
826
Artem Serov0e329082018-06-12 10:23:27 +0100827 if (analysis_info->GetNumberOfInvariantExits() == 0) {
Artem Serov72411e62017-10-19 16:18:07 +0100828 return false;
829 }
830
Artem Serov0e329082018-06-12 10:23:27 +0100831 if (generate_code) {
832 // Perform peeling.
Artem Serov0f5b2bf2019-10-23 14:07:41 +0100833 LoopClonerSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100834 helper.DoPeeling();
Artem Serov72411e62017-10-19 16:18:07 +0100835
Artem Serov0e329082018-06-12 10:23:27 +0100836 // Statically evaluate loop check after peeling for loop invariant condition.
837 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
838 for (auto entry : *hir_map) {
839 HInstruction* copy = entry.second;
840 if (copy->IsIf()) {
841 TryToEvaluateIfCondition(copy->AsIf(), graph_);
842 }
Artem Serov72411e62017-10-19 16:18:07 +0100843 }
844 }
845
846 return true;
847}
848
Artem Serov18ba1da2018-05-16 19:06:32 +0100849bool HLoopOptimization::TryFullUnrolling(LoopAnalysisInfo* analysis_info, bool generate_code) {
850 // Fully unroll loops with a known and small trip count.
851 int64_t trip_count = analysis_info->GetTripCount();
852 if (!arch_loop_helper_->IsLoopPeelingEnabled() ||
853 trip_count == LoopAnalysisInfo::kUnknownTripCount ||
854 !arch_loop_helper_->IsFullUnrollingBeneficial(analysis_info)) {
855 return false;
856 }
857
858 if (generate_code) {
859 // Peeling of the N first iterations (where N equals to the trip count) will effectively
860 // eliminate the loop: after peeling we will have N sequential iterations copied into the loop
861 // preheader and the original loop. The trip count of this loop will be 0 as the sequential
862 // iterations are executed first and there are exactly N of them. Thus we can statically
863 // evaluate the loop exit condition to 'false' and fully eliminate it.
864 //
865 // Here is an example of full unrolling of a loop with a trip count 2:
866 //
867 // loop_cond_1
868 // loop_body_1 <- First iteration.
869 // |
870 // \ v
871 // ==\ loop_cond_2
872 // ==/ loop_body_2 <- Second iteration.
873 // / |
874 // <- v <-
875 // loop_cond \ loop_cond \ <- This cond is always false.
876 // loop_body _/ loop_body _/
877 //
878 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100879 PeelByCount(loop_info, trip_count, &induction_range_);
Artem Serov18ba1da2018-05-16 19:06:32 +0100880 HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
881 int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
882 loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
883 }
884
885 return true;
886}
887
Nicolas Geoffray8f6b99f2021-09-28 17:51:17 +0000888bool HLoopOptimization::TryPeelingAndUnrolling(LoopNode* node) {
Artem Serov0e329082018-06-12 10:23:27 +0100889 HLoopInformation* loop_info = node->loop_info;
890 int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
891 LoopAnalysisInfo analysis_info(loop_info);
892 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
893
894 if (analysis_info.HasInstructionsPreventingScalarOpts() ||
895 arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
896 return false;
897 }
898
Artem Serov18ba1da2018-05-16 19:06:32 +0100899 if (!TryFullUnrolling(&analysis_info, /*generate_code*/ false) &&
900 !TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
Nicolas Geoffray8f6b99f2021-09-28 17:51:17 +0000901 !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false)) {
Artem Serov0e329082018-06-12 10:23:27 +0100902 return false;
903 }
904
905 // Run 'IsLoopClonable' the last as it might be time-consuming.
Artem Serov0f5b2bf2019-10-23 14:07:41 +0100906 if (!LoopClonerHelper::IsLoopClonable(loop_info)) {
Artem Serov0e329082018-06-12 10:23:27 +0100907 return false;
908 }
909
Artem Serov18ba1da2018-05-16 19:06:32 +0100910 return TryFullUnrolling(&analysis_info) ||
911 TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
Nicolas Geoffray8f6b99f2021-09-28 17:51:17 +0000912 TryUnrollingForBranchPenaltyReduction(&analysis_info);
Artem Serov0e329082018-06-12 10:23:27 +0100913}
914
Aart Bikf8f5a162017-02-06 15:35:29 -0800915//
916// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
917// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
918// Intel Press, June, 2004 (http://www.aartbik.com/).
919//
920
Aart Bik14a68b42017-06-08 14:06:58 -0700921bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800922 // Reset vector bookkeeping.
923 vector_length_ = 0;
924 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700925 vector_static_peeling_factor_ = 0;
926 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800927 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800928 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800929
930 // Phis in the loop-body prevent vectorization.
931 if (!block->GetPhis().IsEmpty()) {
932 return false;
933 }
934
935 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
936 // occurrence, which allows passing down attributes down the use tree.
937 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
938 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
939 return false; // failure to vectorize a left-hand-side
940 }
941 }
942
Aart Bik38a3f212017-10-20 17:02:21 -0700943 // Prepare alignment analysis:
944 // (1) find desired alignment (SIMD vector size in bytes).
945 // (2) initialize static loop peeling votes (peeling factor that will
946 // make one particular reference aligned), never to exceed (1).
947 // (3) variable to record how many references share same alignment.
948 // (4) variable to record suitable candidate for dynamic loop peeling.
Artem Serov55ab7e82020-04-27 21:02:28 +0100949 size_t desired_alignment = GetVectorSizeInBytes();
950 ScopedArenaVector<uint32_t> peeling_votes(desired_alignment, 0u,
951 loop_allocator_->Adapter(kArenaAllocLoopOptimization));
952
Aart Bik38a3f212017-10-20 17:02:21 -0700953 uint32_t max_num_same_alignment = 0;
954 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800955
956 // Data dependence analysis. Find each pair of references with same type, where
957 // at least one is a write. Each such pair denotes a possible data dependence.
958 // This analysis exploits the property that differently typed arrays cannot be
959 // aliased, as well as the property that references either point to the same
960 // array or to two completely disjoint arrays, i.e., no partial aliasing.
961 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700962 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800963 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700964 uint32_t num_same_alignment = 0;
965 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800966 for (auto j = i; ++j != vector_refs_->end(); ) {
967 if (i->type == j->type && (i->lhs || j->lhs)) {
968 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
969 HInstruction* a = i->base;
970 HInstruction* b = j->base;
971 HInstruction* x = i->offset;
972 HInstruction* y = j->offset;
973 if (a == b) {
974 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
975 // Conservatively assume a loop-carried data dependence otherwise, and reject.
976 if (x != y) {
977 return false;
978 }
Aart Bik38a3f212017-10-20 17:02:21 -0700979 // Count the number of references that have the same alignment (since
980 // base and offset are the same) and where at least one is a write, so
981 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
982 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800983 } else {
984 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
985 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
986 // generating an explicit a != b disambiguation runtime test on the two references.
987 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700988 // To avoid excessive overhead, we only accept one a != b test.
989 if (vector_runtime_test_a_ == nullptr) {
990 // First test found.
991 vector_runtime_test_a_ = a;
992 vector_runtime_test_b_ = b;
993 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
994 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
995 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800996 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800997 }
998 }
999 }
1000 }
Aart Bik38a3f212017-10-20 17:02:21 -07001001 // Update information for finding suitable alignment strategy:
1002 // (1) update votes for static loop peeling,
1003 // (2) update suitable candidate for dynamic loop peeling.
1004 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1005 if (alignment.Base() >= desired_alignment) {
1006 // If the array/string object has a known, sufficient alignment, use the
1007 // initial offset to compute the static loop peeling vote (this always
1008 // works, since elements have natural alignment).
1009 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1010 uint32_t vote = (offset == 0)
1011 ? 0
1012 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1013 DCHECK_LT(vote, 16u);
1014 ++peeling_votes[vote];
1015 } else if (BaseAlignment() >= desired_alignment &&
1016 num_same_alignment > max_num_same_alignment) {
1017 // Otherwise, if the array/string object has a known, sufficient alignment
1018 // for just the base but with an unknown offset, record the candidate with
1019 // the most occurrences for dynamic loop peeling (again, the peeling always
1020 // works, since elements have natural alignment).
1021 max_num_same_alignment = num_same_alignment;
1022 peeling_candidate = &(*i);
1023 }
1024 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -08001025
Artem Serov8ba4de12019-12-04 21:10:23 +00001026 if (!IsInPredicatedVectorizationMode()) {
1027 // Find a suitable alignment strategy.
1028 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1029 }
Aart Bik38a3f212017-10-20 17:02:21 -07001030
1031 // Does vectorization seem profitable?
1032 if (!IsVectorizationProfitable(trip_count)) {
1033 return false;
1034 }
Aart Bik14a68b42017-06-08 14:06:58 -07001035
Aart Bikf8f5a162017-02-06 15:35:29 -08001036 // Success!
1037 return true;
1038}
1039
1040void HLoopOptimization::Vectorize(LoopNode* node,
1041 HBasicBlock* block,
1042 HBasicBlock* exit,
1043 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001044 HBasicBlock* header = node->loop_info->GetHeader();
1045 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1046
Aart Bik14a68b42017-06-08 14:06:58 -07001047 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +01001048 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1049 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -07001050 uint32_t chunk = vector_length_ * unroll;
1051
Aart Bik38a3f212017-10-20 17:02:21 -07001052 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1053
Aart Bik14a68b42017-06-08 14:06:58 -07001054 // A cleanup loop is needed, at least, for any unknown trip count or
1055 // for a known trip count with remainder iterations after vectorization.
Artem Serov8ba4de12019-12-04 21:10:23 +00001056 bool needs_cleanup = !IsInPredicatedVectorizationMode() &&
1057 (trip_count == 0 || ((trip_count - vector_static_peeling_factor_) % chunk) != 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001058
1059 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -07001060 HPhi* main_phi = nullptr;
1061 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -08001062 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -07001063 vector_header_ = header;
1064 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -08001065
Aart Bikdbbac8f2017-09-01 13:06:08 -07001066 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001067 DataType::Type induc_type = main_phi->GetType();
1068 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1069 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001070
Aart Bik38a3f212017-10-20 17:02:21 -07001071 // Generate the trip count for static or dynamic loop peeling, if needed:
1072 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001073 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001074 if (vector_static_peeling_factor_ != 0) {
Artem Serov8ba4de12019-12-04 21:10:23 +00001075 DCHECK(!IsInPredicatedVectorizationMode());
Aart Bik38a3f212017-10-20 17:02:21 -07001076 // Static loop peeling for SIMD alignment (using the most suitable
1077 // fixed peeling factor found during prior alignment analysis).
1078 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1079 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1080 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
Artem Serov8ba4de12019-12-04 21:10:23 +00001081 DCHECK(!IsInPredicatedVectorizationMode());
Aart Bik38a3f212017-10-20 17:02:21 -07001082 // Dynamic loop peeling for SIMD alignment (using the most suitable
1083 // candidate found during prior alignment analysis):
1084 // rem = offset % ALIGN; // adjusted as #elements
1085 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1086 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1087 uint32_t align = GetVectorSizeInBytes() >> shift;
1088 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1089 vector_dynamic_peeling_candidate_->is_string_char_at);
1090 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1091 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1092 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1093 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1094 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1095 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1096 induc_type, graph_->GetConstant(induc_type, align), rem));
1097 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1098 rem, graph_->GetConstant(induc_type, 0)));
1099 ptc = Insert(preheader, new (global_allocator_) HSelect(
1100 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1101 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001102 }
1103
1104 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001105 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001106 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001107 // vtc = stc - (stc - ptc) % chunk;
1108 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001109 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1110 HInstruction* vtc = stc;
1111 if (needs_cleanup) {
Artem Serov8ba4de12019-12-04 21:10:23 +00001112 DCHECK(!IsInPredicatedVectorizationMode());
Aart Bik14a68b42017-06-08 14:06:58 -07001113 DCHECK(IsPowerOfTwo(chunk));
1114 HInstruction* diff = stc;
1115 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001116 if (trip_count == 0) {
1117 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1118 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1119 }
Aart Bik14a68b42017-06-08 14:06:58 -07001120 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1121 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001122 HInstruction* rem = Insert(
1123 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001124 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001125 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001126 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1127 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001128 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001129
1130 // Generate runtime disambiguation test:
1131 // vtc = a != b ? vtc : 0;
1132 if (vector_runtime_test_a_ != nullptr) {
1133 HInstruction* rt = Insert(
1134 preheader,
1135 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1136 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001137 new (global_allocator_)
1138 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001139 needs_cleanup = true;
1140 }
1141
Aart Bik38a3f212017-10-20 17:02:21 -07001142 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001143 // for ( ; i < ptc; i += 1)
1144 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001145 //
1146 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1147 // moved around during suspend checks, since all analysis was based on
1148 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001149 if (ptc != nullptr) {
Artem Serov8ba4de12019-12-04 21:10:23 +00001150 DCHECK(!IsInPredicatedVectorizationMode());
Aart Bik14a68b42017-06-08 14:06:58 -07001151 vector_mode_ = kSequential;
1152 GenerateNewLoop(node,
1153 block,
1154 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1155 vector_index_,
1156 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001157 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001158 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001159 }
1160
1161 // Generate vector loop, possibly further unrolled:
1162 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001163 // <vectorized-loop-body>
1164 vector_mode_ = kVector;
1165 GenerateNewLoop(node,
1166 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001167 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1168 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001169 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001170 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001171 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001172 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1173
1174 // Generate cleanup loop, if needed:
1175 // for ( ; i < stc; i += 1)
1176 // <loop-body>
1177 if (needs_cleanup) {
Artem Serov8ba4de12019-12-04 21:10:23 +00001178 DCHECK(!IsInPredicatedVectorizationMode() || vector_runtime_test_a_ != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -08001179 vector_mode_ = kSequential;
1180 GenerateNewLoop(node,
1181 block,
1182 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001183 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001184 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001185 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001186 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001187 }
1188
Aart Bik0148de42017-09-05 09:25:01 -07001189 // Link reductions to their final uses.
1190 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1191 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001192 HInstruction* phi = i->first;
1193 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1194 // Deal with regular uses.
1195 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1196 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1197 }
1198 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001199 }
1200 }
1201
Aart Bikf8f5a162017-02-06 15:35:29 -08001202 // Remove the original loop by disconnecting the body block
1203 // and removing all instructions from the header.
1204 block->DisconnectAndDelete();
1205 while (!header->GetFirstInstruction()->IsGoto()) {
1206 header->RemoveInstruction(header->GetFirstInstruction());
1207 }
Aart Bikb29f6842017-07-28 15:58:41 -07001208
Aart Bik14a68b42017-06-08 14:06:58 -07001209 // Update loop hierarchy: the old header now resides in the same outer loop
1210 // as the old preheader. Note that we don't bother putting sequential
1211 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001212 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1213 node->loop_info = vloop;
1214}
1215
1216void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1217 HBasicBlock* block,
1218 HBasicBlock* new_preheader,
1219 HInstruction* lo,
1220 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001221 HInstruction* step,
1222 uint32_t unroll) {
1223 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001224 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001225 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001226 vector_preheader_ = new_preheader,
1227 vector_header_ = vector_preheader_->GetSingleSuccessor();
1228 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001229 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1230 kNoRegNumber,
1231 0,
1232 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001233 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001234 // for (i = lo; i < hi; i += step)
1235 // <loop-body>
Artem Serov8ba4de12019-12-04 21:10:23 +00001236 HInstruction* cond = nullptr;
1237 HInstruction* set_pred = nullptr;
1238 if (IsInPredicatedVectorizationMode()) {
1239 HVecPredWhile* pred_while =
1240 new (global_allocator_) HVecPredWhile(global_allocator_,
1241 phi,
1242 hi,
1243 HVecPredWhile::CondKind::kLO,
1244 DataType::Type::kInt32,
1245 vector_length_,
1246 0u);
1247
1248 cond = new (global_allocator_) HVecPredCondition(global_allocator_,
1249 pred_while,
1250 HVecPredCondition::PCondKind::kNFirst,
1251 DataType::Type::kInt32,
1252 vector_length_,
1253 0u);
1254
1255 vector_header_->AddPhi(phi);
1256 vector_header_->AddInstruction(pred_while);
1257 vector_header_->AddInstruction(cond);
1258 set_pred = pred_while;
1259 } else {
1260 cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1261 vector_header_->AddPhi(phi);
1262 vector_header_->AddInstruction(cond);
1263 }
1264
Aart Bikf8f5a162017-02-06 15:35:29 -08001265 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001266 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001267 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001268 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001269 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001270 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001271 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1272 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1273 DCHECK(vectorized_def);
1274 }
1275 // Generate body from the instruction map, but in original program order.
1276 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1277 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1278 auto i = vector_map_->find(it.Current());
1279 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1280 Insert(vector_body_, i->second);
Artem Serov8ba4de12019-12-04 21:10:23 +00001281 if (IsInPredicatedVectorizationMode() && i->second->IsVecOperation()) {
1282 HVecOperation* op = i->second->AsVecOperation();
1283 op->SetMergingGoverningPredicate(set_pred);
1284 }
Aart Bik14a68b42017-06-08 14:06:58 -07001285 // Deal with instructions that need an environment, such as the scalar intrinsics.
1286 if (i->second->NeedsEnvironment()) {
1287 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1288 }
1289 }
1290 }
Aart Bik0148de42017-09-05 09:25:01 -07001291 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001292 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1293 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001294 }
Aart Bik0148de42017-09-05 09:25:01 -07001295 // Finalize phi inputs for the reductions (if any).
1296 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1297 if (!i->first->IsPhi()) {
1298 DCHECK(i->second->IsPhi());
1299 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1300 }
1301 }
Aart Bikb29f6842017-07-28 15:58:41 -07001302 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001303 phi->AddInput(lo);
1304 phi->AddInput(vector_index_);
1305 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001306}
1307
Aart Bikf8f5a162017-02-06 15:35:29 -08001308bool HLoopOptimization::VectorizeDef(LoopNode* node,
1309 HInstruction* instruction,
1310 bool generate_code) {
1311 // Accept a left-hand-side array base[index] for
1312 // (1) supported vector type,
1313 // (2) loop-invariant base,
1314 // (3) unit stride index,
1315 // (4) vectorizable right-hand-side value.
1316 uint64_t restrictions = kNone;
Georgia Kouvelibac080b2019-01-31 16:12:16 +00001317 // Don't accept expressions that can throw.
1318 if (instruction->CanThrow()) {
1319 return false;
1320 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001321 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001322 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001323 HInstruction* base = instruction->InputAt(0);
1324 HInstruction* index = instruction->InputAt(1);
1325 HInstruction* value = instruction->InputAt(2);
1326 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001327 // For narrow types, explicit type conversion may have been
1328 // optimized way, so set the no hi bits restriction here.
1329 if (DataType::Size(type) <= 2) {
1330 restrictions |= kNoHiBits;
1331 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001332 if (TrySetVectorType(type, &restrictions) &&
1333 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001334 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001335 VectorizeUse(node, value, generate_code, type, restrictions)) {
1336 if (generate_code) {
1337 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001338 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001339 } else {
1340 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1341 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001342 return true;
1343 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001344 return false;
1345 }
Aart Bik0148de42017-09-05 09:25:01 -07001346 // Accept a left-hand-side reduction for
1347 // (1) supported vector type,
1348 // (2) vectorizable right-hand-side value.
1349 auto redit = reductions_->find(instruction);
1350 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001351 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001352 // Recognize SAD idiom or direct reduction.
1353 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
Artem Serovaaac0e32018-08-07 00:52:22 +01001354 VectorizeDotProdIdiom(node, instruction, generate_code, type, restrictions) ||
Aart Bikdbbac8f2017-09-01 13:06:08 -07001355 (TrySetVectorType(type, &restrictions) &&
1356 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001357 if (generate_code) {
1358 HInstruction* new_red = vector_map_->Get(instruction);
1359 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1360 vector_permanent_map_->Overwrite(redit->second, new_red);
1361 }
1362 return true;
1363 }
1364 return false;
1365 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001366 // Branch back okay.
1367 if (instruction->IsGoto()) {
1368 return true;
1369 }
1370 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1371 // Note that actual uses are inspected during right-hand-side tree traversal.
Georgia Kouvelibac080b2019-01-31 16:12:16 +00001372 return !IsUsedOutsideLoop(node->loop_info, instruction)
1373 && !instruction->DoesAnyWrite();
Aart Bikf8f5a162017-02-06 15:35:29 -08001374}
1375
Aart Bikf8f5a162017-02-06 15:35:29 -08001376bool HLoopOptimization::VectorizeUse(LoopNode* node,
1377 HInstruction* instruction,
1378 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001379 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001380 uint64_t restrictions) {
1381 // Accept anything for which code has already been generated.
1382 if (generate_code) {
1383 if (vector_map_->find(instruction) != vector_map_->end()) {
1384 return true;
1385 }
1386 }
1387 // Continue the right-hand-side tree traversal, passing in proper
1388 // types and vector restrictions along the way. During code generation,
1389 // all new nodes are drawn from the global allocator.
1390 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1391 // Accept invariant use, using scalar expansion.
1392 if (generate_code) {
1393 GenerateVecInv(instruction, type);
1394 }
1395 return true;
1396 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001397 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001398 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
Artem Serov8ba4de12019-12-04 21:10:23 +00001399
1400 if (is_string_char_at && (HasVectorRestrictions(restrictions, kNoStringCharAt) ||
1401 IsInPredicatedVectorizationMode())) {
1402 // TODO: Support CharAt for predicated mode.
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001403 return false;
1404 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001405 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001406 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001407 // (2) loop-invariant base,
1408 // (3) unit stride index,
1409 // (4) vectorizable right-hand-side value.
1410 HInstruction* base = instruction->InputAt(0);
1411 HInstruction* index = instruction->InputAt(1);
1412 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001413 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001414 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001415 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001416 if (generate_code) {
1417 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001418 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001419 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001420 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001421 }
1422 return true;
1423 }
Aart Bik0148de42017-09-05 09:25:01 -07001424 } else if (instruction->IsPhi()) {
1425 // Accept particular phi operations.
1426 if (reductions_->find(instruction) != reductions_->end()) {
1427 // Deal with vector restrictions.
1428 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1429 return false;
1430 }
1431 // Accept a reduction.
1432 if (generate_code) {
1433 GenerateVecReductionPhi(instruction->AsPhi());
1434 }
1435 return true;
1436 }
1437 // TODO: accept right-hand-side induction?
1438 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001439 } else if (instruction->IsTypeConversion()) {
1440 // Accept particular type conversions.
1441 HTypeConversion* conversion = instruction->AsTypeConversion();
1442 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001443 DataType::Type from = conversion->GetInputType();
1444 DataType::Type to = conversion->GetResultType();
1445 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001446 uint32_t size_vec = DataType::Size(type);
1447 uint32_t size_from = DataType::Size(from);
1448 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001449 // Accept an integral conversion
1450 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1451 // (1b) widening from at least vector type, and
1452 // (2) vectorizable operand.
1453 if ((size_to < size_from &&
1454 size_to == size_vec &&
1455 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1456 (size_to >= size_from &&
1457 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001458 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001459 if (generate_code) {
1460 if (vector_mode_ == kVector) {
1461 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1462 } else {
1463 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1464 }
1465 }
1466 return true;
1467 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001468 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001469 DCHECK_EQ(to, type);
1470 // Accept int to float conversion for
1471 // (1) supported int,
1472 // (2) vectorizable operand.
1473 if (TrySetVectorType(from, &restrictions) &&
1474 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1475 if (generate_code) {
1476 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1477 }
1478 return true;
1479 }
1480 }
1481 return false;
1482 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1483 // Accept unary operator for vectorizable operand.
1484 HInstruction* opa = instruction->InputAt(0);
1485 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1486 if (generate_code) {
1487 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1488 }
1489 return true;
1490 }
1491 } else if (instruction->IsAdd() || instruction->IsSub() ||
1492 instruction->IsMul() || instruction->IsDiv() ||
1493 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1494 // Deal with vector restrictions.
1495 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1496 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1497 return false;
1498 }
1499 // Accept binary operator for vectorizable operands.
1500 HInstruction* opa = instruction->InputAt(0);
1501 HInstruction* opb = instruction->InputAt(1);
1502 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1503 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1504 if (generate_code) {
1505 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1506 }
1507 return true;
1508 }
1509 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001510 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001511 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1512 return true;
1513 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001514 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001515 HInstruction* opa = instruction->InputAt(0);
1516 HInstruction* opb = instruction->InputAt(1);
1517 HInstruction* r = opa;
1518 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001519 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1520 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1521 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001522 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1523 // Shifts right need extra care to account for higher order bits.
1524 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1525 if (instruction->IsShr() &&
1526 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1527 return false; // reject, unless all operands are sign-extension narrower
1528 } else if (instruction->IsUShr() &&
1529 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1530 return false; // reject, unless all operands are zero-extension narrower
1531 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001532 }
1533 // Accept shift operator for vectorizable/invariant operands.
1534 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001535 DCHECK(r != nullptr);
1536 if (generate_code && vector_mode_ != kVector) { // de-idiom
1537 r = opa;
1538 }
Aart Bik50e20d52017-05-05 14:07:29 -07001539 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001540 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001541 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001542 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001543 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001544 if (0 <= distance && distance < max_distance) {
1545 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001546 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001547 }
1548 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001549 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001550 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001551 } else if (instruction->IsAbs()) {
1552 // Deal with vector restrictions.
1553 HInstruction* opa = instruction->InputAt(0);
1554 HInstruction* r = opa;
1555 bool is_unsigned = false;
1556 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1557 return false;
1558 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1559 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1560 return false; // reject, unless operand is sign-extension narrower
1561 }
1562 // Accept ABS(x) for vectorizable operand.
1563 DCHECK(r != nullptr);
1564 if (generate_code && vector_mode_ != kVector) { // de-idiom
1565 r = opa;
1566 }
1567 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1568 if (generate_code) {
1569 GenerateVecOp(instruction,
1570 vector_map_->Get(r),
1571 nullptr,
1572 HVecOperation::ToProperType(type, is_unsigned));
1573 }
1574 return true;
1575 }
Aart Bik281c6812016-08-26 11:31:48 -07001576 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001577 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001578}
1579
Aart Bik38a3f212017-10-20 17:02:21 -07001580uint32_t HLoopOptimization::GetVectorSizeInBytes() {
Artem Serovc8150b52019-07-31 18:28:00 +01001581 return simd_register_size_;
Aart Bik38a3f212017-10-20 17:02:21 -07001582}
1583
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001584bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001585 const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
1586 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001587 case InstructionSet::kArm:
1588 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001589 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001590 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001591 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001592 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001593 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001594 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001595 *restrictions |= kNoDiv | kNoReduction | kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001596 return TrySetVectorLength(type, 8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001597 case DataType::Type::kUint16:
1598 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001599 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001600 return TrySetVectorLength(type, 4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001601 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001602 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001603 return TrySetVectorLength(type, 2);
Artem Serov8f7c4102017-06-21 11:21:37 +01001604 default:
1605 break;
1606 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001607 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001608 case InstructionSet::kArm64:
Artem Serov8ba4de12019-12-04 21:10:23 +00001609 if (IsInPredicatedVectorizationMode()) {
1610 // SVE vectorization.
1611 CHECK(features->AsArm64InstructionSetFeatures()->HasSVE());
Artem Serov55ab7e82020-04-27 21:02:28 +01001612 size_t vector_length = simd_register_size_ / DataType::Size(type);
1613 DCHECK_EQ(simd_register_size_ % DataType::Size(type), 0u);
Artem Serov8ba4de12019-12-04 21:10:23 +00001614 switch (type) {
1615 case DataType::Type::kBool:
1616 case DataType::Type::kUint8:
1617 case DataType::Type::kInt8:
1618 *restrictions |= kNoDiv |
1619 kNoSignedHAdd |
1620 kNoUnsignedHAdd |
1621 kNoUnroundedHAdd |
1622 kNoSAD;
Artem Serov55ab7e82020-04-27 21:02:28 +01001623 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001624 case DataType::Type::kUint16:
1625 case DataType::Type::kInt16:
1626 *restrictions |= kNoDiv |
1627 kNoSignedHAdd |
1628 kNoUnsignedHAdd |
1629 kNoUnroundedHAdd |
1630 kNoSAD |
1631 kNoDotProd;
Artem Serov55ab7e82020-04-27 21:02:28 +01001632 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001633 case DataType::Type::kInt32:
1634 *restrictions |= kNoDiv | kNoSAD;
Artem Serov55ab7e82020-04-27 21:02:28 +01001635 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001636 case DataType::Type::kInt64:
1637 *restrictions |= kNoDiv | kNoSAD;
Artem Serov55ab7e82020-04-27 21:02:28 +01001638 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001639 case DataType::Type::kFloat32:
1640 *restrictions |= kNoReduction;
Artem Serov55ab7e82020-04-27 21:02:28 +01001641 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001642 case DataType::Type::kFloat64:
1643 *restrictions |= kNoReduction;
Artem Serov55ab7e82020-04-27 21:02:28 +01001644 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001645 default:
1646 break;
1647 }
1648 return false;
1649 } else {
1650 // Allow vectorization for all ARM devices, because Android assumes that
1651 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
1652 switch (type) {
1653 case DataType::Type::kBool:
1654 case DataType::Type::kUint8:
1655 case DataType::Type::kInt8:
1656 *restrictions |= kNoDiv;
1657 return TrySetVectorLength(type, 16);
1658 case DataType::Type::kUint16:
1659 case DataType::Type::kInt16:
1660 *restrictions |= kNoDiv;
1661 return TrySetVectorLength(type, 8);
1662 case DataType::Type::kInt32:
1663 *restrictions |= kNoDiv;
1664 return TrySetVectorLength(type, 4);
1665 case DataType::Type::kInt64:
1666 *restrictions |= kNoDiv | kNoMul;
1667 return TrySetVectorLength(type, 2);
1668 case DataType::Type::kFloat32:
1669 *restrictions |= kNoReduction;
1670 return TrySetVectorLength(type, 4);
1671 case DataType::Type::kFloat64:
1672 *restrictions |= kNoReduction;
1673 return TrySetVectorLength(type, 2);
1674 default:
1675 break;
1676 }
1677 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001678 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001679 case InstructionSet::kX86:
1680 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001681 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001682 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1683 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001684 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001685 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001686 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001687 *restrictions |= kNoMul |
1688 kNoDiv |
1689 kNoShift |
1690 kNoAbs |
1691 kNoSignedHAdd |
1692 kNoUnroundedHAdd |
1693 kNoSAD |
1694 kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001695 return TrySetVectorLength(type, 16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001696 case DataType::Type::kUint16:
Alex Light43f2f752019-12-04 17:48:45 +00001697 *restrictions |= kNoDiv |
1698 kNoAbs |
1699 kNoSignedHAdd |
1700 kNoUnroundedHAdd |
1701 kNoSAD |
1702 kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001703 return TrySetVectorLength(type, 8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001704 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001705 *restrictions |= kNoDiv |
1706 kNoAbs |
1707 kNoSignedHAdd |
1708 kNoUnroundedHAdd |
Alex Light43f2f752019-12-04 17:48:45 +00001709 kNoSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001710 return TrySetVectorLength(type, 8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001711 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001712 *restrictions |= kNoDiv | kNoSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001713 return TrySetVectorLength(type, 4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001714 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001715 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001716 return TrySetVectorLength(type, 2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001717 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001718 *restrictions |= kNoReduction;
Artem Serovc8150b52019-07-31 18:28:00 +01001719 return TrySetVectorLength(type, 4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001720 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001721 *restrictions |= kNoReduction;
Artem Serovc8150b52019-07-31 18:28:00 +01001722 return TrySetVectorLength(type, 2);
Aart Bikf8f5a162017-02-06 15:35:29 -08001723 default:
1724 break;
1725 } // switch type
1726 }
1727 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001728 default:
1729 return false;
1730 } // switch instruction set
1731}
1732
Artem Serovc8150b52019-07-31 18:28:00 +01001733bool HLoopOptimization::TrySetVectorLengthImpl(uint32_t length) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001734 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1735 // First time set?
1736 if (vector_length_ == 0) {
1737 vector_length_ = length;
1738 }
1739 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1740 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1741 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1742 return vector_length_ == length;
1743}
1744
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001745void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001746 if (vector_map_->find(org) == vector_map_->end()) {
1747 // In scalar code, just use a self pass-through for scalar invariants
1748 // (viz. expression remains itself).
1749 if (vector_mode_ == kSequential) {
1750 vector_map_->Put(org, org);
1751 return;
1752 }
1753 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001754 HInstruction* vector = nullptr;
1755 auto it = vector_permanent_map_->find(org);
1756 if (it != vector_permanent_map_->end()) {
1757 vector = it->second; // reuse during unrolling
1758 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001759 // Generates ReplicateScalar( (optional_type_conv) org ).
1760 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001761 DataType::Type input_type = input->GetType();
1762 if (type != input_type && (type == DataType::Type::kInt64 ||
1763 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001764 input = Insert(vector_preheader_,
1765 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1766 }
1767 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001768 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001769 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
Artem Serov8ba4de12019-12-04 21:10:23 +00001770 if (IsInPredicatedVectorizationMode()) {
1771 HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1772 graph_->GetIntConstant(1),
1773 type,
1774 vector_length_,
1775 0u);
1776 vector_preheader_->InsertInstructionBefore(set_pred, vector);
1777 vector->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
1778 }
Aart Bik0148de42017-09-05 09:25:01 -07001779 }
1780 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001781 }
1782}
1783
1784void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1785 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001786 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001787 int64_t value = 0;
1788 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001789 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001790 if (org->IsPhi()) {
1791 Insert(vector_body_, subscript); // lacks layout placeholder
1792 }
1793 }
1794 vector_map_->Put(org, subscript);
1795 }
1796}
1797
1798void HLoopOptimization::GenerateVecMem(HInstruction* org,
1799 HInstruction* opa,
1800 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001801 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001802 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001803 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001804 HInstruction* vector = nullptr;
1805 if (vector_mode_ == kVector) {
1806 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001807 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001808 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001809 if (opb != nullptr) {
1810 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001811 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001812 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001813 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001814 vector = new (global_allocator_) HVecLoad(global_allocator_,
1815 base,
1816 opa,
1817 type,
1818 org->GetSideEffects(),
1819 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001820 is_string_char_at,
1821 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001822 }
Aart Bik38a3f212017-10-20 17:02:21 -07001823 // Known (forced/adjusted/original) alignment?
1824 if (vector_dynamic_peeling_candidate_ != nullptr) {
1825 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1826 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1827 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1828 vector->AsVecMemoryOperation()->SetAlignment( // forced
1829 Alignment(GetVectorSizeInBytes(), 0));
1830 }
1831 } else {
1832 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1833 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001834 }
1835 } else {
1836 // Scalar store or load.
1837 DCHECK(vector_mode_ == kSequential);
1838 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001839 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001840 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001841 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001842 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001843 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1844 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001845 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001846 }
1847 }
1848 vector_map_->Put(org, vector);
1849}
1850
Aart Bik0148de42017-09-05 09:25:01 -07001851void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1852 DCHECK(reductions_->find(phi) != reductions_->end());
1853 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1854 HInstruction* vector = nullptr;
1855 if (vector_mode_ == kSequential) {
1856 HPhi* new_phi = new (global_allocator_) HPhi(
1857 global_allocator_, kNoRegNumber, 0, phi->GetType());
1858 vector_header_->AddPhi(new_phi);
1859 vector = new_phi;
1860 } else {
1861 // Link vector reduction back to prior unrolled update, or a first phi.
1862 auto it = vector_permanent_map_->find(phi);
1863 if (it != vector_permanent_map_->end()) {
1864 vector = it->second;
1865 } else {
1866 HPhi* new_phi = new (global_allocator_) HPhi(
1867 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1868 vector_header_->AddPhi(new_phi);
1869 vector = new_phi;
1870 }
1871 }
1872 vector_map_->Put(phi, vector);
1873}
1874
1875void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1876 HInstruction* new_phi = vector_map_->Get(phi);
1877 HInstruction* new_init = reductions_->Get(phi);
1878 HInstruction* new_red = vector_map_->Get(reduction);
1879 // Link unrolled vector loop back to new phi.
1880 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1881 DCHECK(new_phi->IsVecOperation());
1882 }
1883 // Prepare the new initialization.
1884 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001885 // Generate a [initial, 0, .., 0] vector for add or
1886 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001887 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001888 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001889 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001890 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001891 if (kind == HVecReduce::ReductionKind::kSum) {
1892 new_init = Insert(vector_preheader_,
1893 new (global_allocator_) HVecSetScalars(global_allocator_,
1894 &new_init,
1895 type,
1896 vector_length,
1897 1,
1898 kNoDexPc));
1899 } else {
1900 new_init = Insert(vector_preheader_,
1901 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1902 new_init,
1903 type,
1904 vector_length,
1905 kNoDexPc));
1906 }
Artem Serov8ba4de12019-12-04 21:10:23 +00001907 if (IsInPredicatedVectorizationMode()) {
1908 HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1909 graph_->GetIntConstant(1),
1910 type,
1911 vector_length,
1912 0u);
1913 vector_preheader_->InsertInstructionBefore(set_pred, new_init);
1914 new_init->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
1915 }
Aart Bik0148de42017-09-05 09:25:01 -07001916 } else {
1917 new_init = ReduceAndExtractIfNeeded(new_init);
1918 }
1919 // Set the phi inputs.
1920 DCHECK(new_phi->IsPhi());
1921 new_phi->AsPhi()->AddInput(new_init);
1922 new_phi->AsPhi()->AddInput(new_red);
1923 // New feed value for next phi (safe mutation in iteration).
1924 reductions_->find(phi)->second = new_phi;
1925}
1926
1927HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1928 if (instruction->IsPhi()) {
1929 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001930 if (HVecOperation::ReturnsSIMDValue(input)) {
1931 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001932 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001933 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001934 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001935 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001936 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1937 // Generate a vector reduction and scalar extract
1938 // x = REDUCE( [x_1, .., x_n] )
1939 // y = x_1
1940 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001941 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001942 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001943 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1944 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001945 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001946 exit->InsertInstructionAfter(instruction, reduce);
Artem Serov8ba4de12019-12-04 21:10:23 +00001947
1948 if (IsInPredicatedVectorizationMode()) {
1949 HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1950 graph_->GetIntConstant(1),
1951 type,
1952 vector_length,
1953 0u);
1954 exit->InsertInstructionBefore(set_pred, reduce);
1955 reduce->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
1956 instruction->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
1957 }
Aart Bik0148de42017-09-05 09:25:01 -07001958 }
1959 }
1960 return instruction;
1961}
1962
Aart Bikf8f5a162017-02-06 15:35:29 -08001963#define GENERATE_VEC(x, y) \
1964 if (vector_mode_ == kVector) { \
1965 vector = (x); \
1966 } else { \
1967 DCHECK(vector_mode_ == kSequential); \
1968 vector = (y); \
1969 } \
1970 break;
1971
1972void HLoopOptimization::GenerateVecOp(HInstruction* org,
1973 HInstruction* opa,
1974 HInstruction* opb,
Aart Bik3f08e9b2018-05-01 13:42:03 -07001975 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001976 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001977 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001978 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001979 switch (org->GetKind()) {
1980 case HInstruction::kNeg:
1981 DCHECK(opb == nullptr);
1982 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001983 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1984 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001985 case HInstruction::kNot:
1986 DCHECK(opb == nullptr);
1987 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001988 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1989 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001990 case HInstruction::kBooleanNot:
1991 DCHECK(opb == nullptr);
1992 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001993 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1994 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001995 case HInstruction::kTypeConversion:
1996 DCHECK(opb == nullptr);
1997 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001998 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1999 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002000 case HInstruction::kAdd:
2001 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002002 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2003 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002004 case HInstruction::kSub:
2005 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002006 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2007 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002008 case HInstruction::kMul:
2009 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002010 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2011 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002012 case HInstruction::kDiv:
2013 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002014 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2015 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002016 case HInstruction::kAnd:
2017 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002018 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2019 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002020 case HInstruction::kOr:
2021 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002022 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2023 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002024 case HInstruction::kXor:
2025 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002026 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2027 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002028 case HInstruction::kShl:
2029 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002030 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2031 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002032 case HInstruction::kShr:
2033 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002034 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2035 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002036 case HInstruction::kUShr:
2037 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002038 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2039 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08002040 case HInstruction::kAbs:
2041 DCHECK(opb == nullptr);
2042 GENERATE_VEC(
2043 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
2044 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002045 default:
2046 break;
2047 } // switch
2048 CHECK(vector != nullptr) << "Unsupported SIMD operator";
2049 vector_map_->Put(org, vector);
2050}
2051
2052#undef GENERATE_VEC
2053
2054//
Aart Bikf3e61ee2017-04-12 17:09:20 -07002055// Vectorization idioms.
2056//
2057
2058// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07002059// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2060// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07002061// Provided that the operands are promoted to a wider form to do the arithmetic and
2062// then cast back to narrower form, the idioms can be mapped into efficient SIMD
2063// implementation that operates directly in narrower form (plus one extra bit).
2064// TODO: current version recognizes implicit byte/short/char widening only;
2065// explicit widening from int to long could be added later.
2066bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2067 HInstruction* instruction,
2068 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002069 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07002070 uint64_t restrictions) {
2071 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07002072 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07002073 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07002074 if ((instruction->IsShr() ||
2075 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07002076 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07002077 // Test for (a + b + c) >> 1 for optional constant c.
2078 HInstruction* a = nullptr;
2079 HInstruction* b = nullptr;
2080 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002081 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07002082 // Accept c == 1 (rounded) or c == 0 (not rounded).
2083 bool is_rounded = false;
2084 if (c == 1) {
2085 is_rounded = true;
2086 } else if (c != 0) {
2087 return false;
2088 }
2089 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07002090 HInstruction* r = nullptr;
2091 HInstruction* s = nullptr;
2092 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002093 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002094 return false;
2095 }
2096 // Deal with vector restrictions.
Artem Serov8ba4de12019-12-04 21:10:23 +00002097 if ((is_unsigned && HasVectorRestrictions(restrictions, kNoUnsignedHAdd)) ||
2098 (!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
Aart Bikf3e61ee2017-04-12 17:09:20 -07002099 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2100 return false;
2101 }
2102 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2103 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002104 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002105 if (generate_code && vector_mode_ != kVector) { // de-idiom
2106 r = instruction->InputAt(0);
2107 s = instruction->InputAt(1);
2108 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002109 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2110 VectorizeUse(node, s, generate_code, type, restrictions)) {
2111 if (generate_code) {
2112 if (vector_mode_ == kVector) {
2113 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2114 global_allocator_,
2115 vector_map_->Get(r),
2116 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002117 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002118 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002119 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002120 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002121 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002122 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002123 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002124 }
2125 }
2126 return true;
2127 }
2128 }
2129 }
2130 return false;
2131}
2132
Aart Bikdbbac8f2017-09-01 13:06:08 -07002133// Method recognizes the following idiom:
2134// q += ABS(a - b) for signed operands a, b
2135// Provided that the operands have the same type or are promoted to a wider form.
2136// Since this may involve a vector length change, the idiom is handled by going directly
2137// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2138// TODO: unsigned SAD too?
2139bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2140 HInstruction* instruction,
2141 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002142 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002143 uint64_t restrictions) {
2144 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2145 // are done in the same precision (either int or long).
2146 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002147 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002148 return false;
2149 }
Artem Serove521eb02020-02-27 18:51:24 +00002150 HInstruction* acc = instruction->InputAt(0);
2151 HInstruction* abs = instruction->InputAt(1);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002152 HInstruction* a = nullptr;
2153 HInstruction* b = nullptr;
Artem Serove521eb02020-02-27 18:51:24 +00002154 if (abs->IsAbs() &&
2155 abs->GetType() == reduction_type &&
2156 IsSubConst2(graph_, abs->InputAt(0), /*out*/ &a, /*out*/ &b)) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002157 DCHECK(a != nullptr && b != nullptr);
2158 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002159 return false;
2160 }
2161 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2162 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002163 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002164 HInstruction* r = a;
2165 HInstruction* s = b;
2166 bool is_unsigned = false;
Artem Serovaaac0e32018-08-07 00:52:22 +01002167 DataType::Type sub_type = GetNarrowerType(a, b);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002168 if (reduction_type != sub_type &&
2169 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2170 return false;
2171 }
2172 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002173 if (!TrySetVectorType(sub_type, &restrictions) ||
2174 HasVectorRestrictions(restrictions, kNoSAD) ||
2175 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002176 return false;
2177 }
2178 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2179 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002180 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002181 if (generate_code && vector_mode_ != kVector) { // de-idiom
Artem Serove521eb02020-02-27 18:51:24 +00002182 r = s = abs->InputAt(0);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002183 }
Artem Serove521eb02020-02-27 18:51:24 +00002184 if (VectorizeUse(node, acc, generate_code, sub_type, restrictions) &&
Aart Bikdbbac8f2017-09-01 13:06:08 -07002185 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2186 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2187 if (generate_code) {
2188 if (vector_mode_ == kVector) {
2189 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2190 global_allocator_,
Artem Serove521eb02020-02-27 18:51:24 +00002191 vector_map_->Get(acc),
Aart Bikdbbac8f2017-09-01 13:06:08 -07002192 vector_map_->Get(r),
2193 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002194 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002195 GetOtherVL(reduction_type, sub_type, vector_length_),
2196 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002197 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2198 } else {
Artem Serove521eb02020-02-27 18:51:24 +00002199 // "GenerateVecOp()" must not be called more than once for each original loop body
2200 // instruction. As the SAD idiom processes both "current" instruction ("instruction")
2201 // and its ABS input in one go, we must check that for the scalar case the ABS instruction
2202 // has not yet been processed.
2203 if (vector_map_->find(abs) == vector_map_->end()) {
2204 GenerateVecOp(abs, vector_map_->Get(r), nullptr, reduction_type);
2205 }
2206 GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(abs), reduction_type);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002207 }
2208 }
2209 return true;
2210 }
2211 return false;
2212}
2213
Artem Serovaaac0e32018-08-07 00:52:22 +01002214// Method recognises the following dot product idiom:
2215// q += a * b for operands a, b whose type is narrower than the reduction one.
2216// Provided that the operands have the same type or are promoted to a wider form.
2217// Since this may involve a vector length change, the idiom is handled by going directly
2218// to a dot product node (rather than relying combining finer grained nodes later).
2219bool HLoopOptimization::VectorizeDotProdIdiom(LoopNode* node,
2220 HInstruction* instruction,
2221 bool generate_code,
2222 DataType::Type reduction_type,
2223 uint64_t restrictions) {
Alex Light43f2f752019-12-04 17:48:45 +00002224 if (!instruction->IsAdd() || reduction_type != DataType::Type::kInt32) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002225 return false;
2226 }
2227
Artem Serove521eb02020-02-27 18:51:24 +00002228 HInstruction* const acc = instruction->InputAt(0);
2229 HInstruction* const mul = instruction->InputAt(1);
2230 if (!mul->IsMul() || mul->GetType() != reduction_type) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002231 return false;
2232 }
2233
Artem Serove521eb02020-02-27 18:51:24 +00002234 HInstruction* const mul_left = mul->InputAt(0);
2235 HInstruction* const mul_right = mul->InputAt(1);
2236 HInstruction* r = mul_left;
2237 HInstruction* s = mul_right;
2238 DataType::Type op_type = GetNarrowerType(mul_left, mul_right);
Artem Serovaaac0e32018-08-07 00:52:22 +01002239 bool is_unsigned = false;
2240
Artem Serove521eb02020-02-27 18:51:24 +00002241 if (!IsNarrowerOperands(mul_left, mul_right, op_type, &r, &s, &is_unsigned)) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002242 return false;
2243 }
2244 op_type = HVecOperation::ToProperType(op_type, is_unsigned);
2245
2246 if (!TrySetVectorType(op_type, &restrictions) ||
2247 HasVectorRestrictions(restrictions, kNoDotProd)) {
2248 return false;
2249 }
2250
2251 DCHECK(r != nullptr && s != nullptr);
2252 // Accept dot product idiom for vectorizable operands. Vectorized code uses the shorthand
2253 // idiomatic operation. Sequential code uses the original scalar expressions.
2254 if (generate_code && vector_mode_ != kVector) { // de-idiom
Artem Serove521eb02020-02-27 18:51:24 +00002255 r = mul_left;
2256 s = mul_right;
Artem Serovaaac0e32018-08-07 00:52:22 +01002257 }
Artem Serove521eb02020-02-27 18:51:24 +00002258 if (VectorizeUse(node, acc, generate_code, op_type, restrictions) &&
Artem Serovaaac0e32018-08-07 00:52:22 +01002259 VectorizeUse(node, r, generate_code, op_type, restrictions) &&
2260 VectorizeUse(node, s, generate_code, op_type, restrictions)) {
2261 if (generate_code) {
2262 if (vector_mode_ == kVector) {
2263 vector_map_->Put(instruction, new (global_allocator_) HVecDotProd(
2264 global_allocator_,
Artem Serove521eb02020-02-27 18:51:24 +00002265 vector_map_->Get(acc),
Artem Serovaaac0e32018-08-07 00:52:22 +01002266 vector_map_->Get(r),
2267 vector_map_->Get(s),
2268 reduction_type,
2269 is_unsigned,
2270 GetOtherVL(reduction_type, op_type, vector_length_),
2271 kNoDexPc));
2272 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2273 } else {
Artem Serove521eb02020-02-27 18:51:24 +00002274 // "GenerateVecOp()" must not be called more than once for each original loop body
2275 // instruction. As the DotProd idiom processes both "current" instruction ("instruction")
2276 // and its MUL input in one go, we must check that for the scalar case the MUL instruction
2277 // has not yet been processed.
2278 if (vector_map_->find(mul) == vector_map_->end()) {
2279 GenerateVecOp(mul, vector_map_->Get(r), vector_map_->Get(s), reduction_type);
2280 }
2281 GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(mul), reduction_type);
Artem Serovaaac0e32018-08-07 00:52:22 +01002282 }
2283 }
2284 return true;
2285 }
2286 return false;
2287}
2288
Aart Bikf3e61ee2017-04-12 17:09:20 -07002289//
Aart Bik14a68b42017-06-08 14:06:58 -07002290// Vectorization heuristics.
2291//
2292
Aart Bik38a3f212017-10-20 17:02:21 -07002293Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2294 DataType::Type type,
2295 bool is_string_char_at,
2296 uint32_t peeling) {
2297 // Combine the alignment and hidden offset that is guaranteed by
2298 // the Android runtime with a known starting index adjusted as bytes.
2299 int64_t value = 0;
2300 if (IsInt64AndGet(offset, /*out*/ &value)) {
2301 uint32_t start_offset =
2302 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2303 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2304 }
2305 // Otherwise, the Android runtime guarantees at least natural alignment.
2306 return Alignment(DataType::Size(type), 0);
2307}
2308
Artem Serov55ab7e82020-04-27 21:02:28 +01002309void HLoopOptimization::SetAlignmentStrategy(const ScopedArenaVector<uint32_t>& peeling_votes,
Aart Bik38a3f212017-10-20 17:02:21 -07002310 const ArrayReference* peeling_candidate) {
2311 // Current heuristic: pick the best static loop peeling factor, if any,
2312 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2313 uint32_t max_vote = 0;
Artem Serov55ab7e82020-04-27 21:02:28 +01002314 for (size_t i = 0; i < peeling_votes.size(); i++) {
Aart Bik38a3f212017-10-20 17:02:21 -07002315 if (peeling_votes[i] > max_vote) {
2316 max_vote = peeling_votes[i];
2317 vector_static_peeling_factor_ = i;
2318 }
2319 }
2320 if (max_vote == 0) {
2321 vector_dynamic_peeling_candidate_ = peeling_candidate;
2322 }
2323}
2324
2325uint32_t HLoopOptimization::MaxNumberPeeled() {
2326 if (vector_dynamic_peeling_candidate_ != nullptr) {
2327 return vector_length_ - 1u; // worst-case
2328 }
2329 return vector_static_peeling_factor_; // known exactly
2330}
2331
Aart Bik14a68b42017-06-08 14:06:58 -07002332bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002333 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002334 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002335 // TODO: trip count is really unsigned entity, provided the guarding test
2336 // is satisfied; deal with this more carefully later
2337 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002338 if (vector_length_ == 0) {
2339 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002340 } else if (trip_count < 0) {
2341 return false; // guard against non-taken/large
2342 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002343 return false; // insufficient iterations
2344 }
2345 return true;
2346}
2347
Aart Bik14a68b42017-06-08 14:06:58 -07002348//
Aart Bikf8f5a162017-02-06 15:35:29 -08002349// Helpers.
2350//
2351
2352bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002353 // Start with empty phi induction.
2354 iset_->clear();
2355
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002356 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2357 // smart enough to follow strongly connected components (and it's probably not worth
2358 // it to make it so). See b/33775412.
2359 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2360 return false;
2361 }
Aart Bikb29f6842017-07-28 15:58:41 -07002362
2363 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002364 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2365 if (set != nullptr) {
2366 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002367 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002368 // each instruction is removable and, when restrict uses are requested, other than for phi,
2369 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002370 if (!i->IsInBlock()) {
2371 continue;
2372 } else if (!i->IsRemovable()) {
2373 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002374 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002375 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002376 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2377 if (set->find(use.GetUser()) == set->end()) {
2378 return false;
2379 }
2380 }
2381 }
Aart Bike3dedc52016-11-02 17:50:27 -07002382 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002383 }
Aart Bikcc42be02016-10-20 16:14:16 -07002384 return true;
2385 }
2386 return false;
2387}
2388
Aart Bikb29f6842017-07-28 15:58:41 -07002389bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002390 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002391 // Only unclassified phi cycles are candidates for reductions.
2392 if (induction_range_.IsClassified(phi)) {
2393 return false;
2394 }
2395 // Accept operations like x = x + .., provided that the phi and the reduction are
2396 // used exactly once inside the loop, and by each other.
2397 HInputsRef inputs = phi->GetInputs();
2398 if (inputs.size() == 2) {
2399 HInstruction* reduction = inputs[1];
2400 if (HasReductionFormat(reduction, phi)) {
2401 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002402 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002403 bool single_use_inside_loop =
2404 // Reduction update only used by phi.
2405 reduction->GetUses().HasExactlyOneElement() &&
2406 !reduction->HasEnvironmentUses() &&
2407 // Reduction update is only use of phi inside the loop.
2408 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2409 iset_->size() == 1;
2410 iset_->clear(); // leave the way you found it
2411 if (single_use_inside_loop) {
2412 // Link reduction back, and start recording feed value.
2413 reductions_->Put(reduction, phi);
2414 reductions_->Put(phi, phi->InputAt(0));
2415 return true;
2416 }
2417 }
2418 }
2419 return false;
2420}
2421
2422bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2423 // Start with empty phi induction and reductions.
2424 iset_->clear();
2425 reductions_->clear();
2426
2427 // Scan the phis to find the following (the induction structure has already
2428 // been optimized, so we don't need to worry about trivial cases):
2429 // (1) optional reductions in loop,
2430 // (2) the main induction, used in loop control.
2431 HPhi* phi = nullptr;
2432 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2433 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2434 continue;
2435 } else if (phi == nullptr) {
2436 // Found the first candidate for main induction.
2437 phi = it.Current()->AsPhi();
2438 } else {
2439 return false;
2440 }
2441 }
2442
2443 // Then test for a typical loopheader:
2444 // s: SuspendCheck
2445 // c: Condition(phi, bound)
2446 // i: If(c)
2447 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002448 HInstruction* s = block->GetFirstInstruction();
2449 if (s != nullptr && s->IsSuspendCheck()) {
2450 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002451 if (c != nullptr &&
2452 c->IsCondition() &&
2453 c->GetUses().HasExactlyOneElement() && // only used for termination
2454 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002455 HInstruction* i = c->GetNext();
2456 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2457 iset_->insert(c);
2458 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002459 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002460 return true;
2461 }
2462 }
2463 }
2464 }
2465 return false;
2466}
2467
2468bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002469 if (!block->GetPhis().IsEmpty()) {
2470 return false;
2471 }
2472 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2473 HInstruction* instruction = it.Current();
2474 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2475 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002476 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002477 }
2478 return true;
2479}
2480
2481bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2482 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002483 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002484 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2485 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2486 return true;
2487 }
Aart Bikcc42be02016-10-20 16:14:16 -07002488 }
2489 return false;
2490}
2491
Aart Bik482095d2016-10-10 15:39:10 -07002492bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002493 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002494 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002495 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002496 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002497 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2498 HInstruction* user = use.GetUser();
2499 if (iset_->find(user) == iset_->end()) { // not excluded?
2500 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002501 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002502 // If collect_loop_uses is set, simply keep adding those uses to the set.
2503 // Otherwise, reject uses inside the loop that were not already in the set.
2504 if (collect_loop_uses) {
2505 iset_->insert(user);
2506 continue;
2507 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002508 return false;
2509 }
2510 ++*use_count;
2511 }
2512 }
2513 return true;
2514}
2515
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002516bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2517 HInstruction* instruction,
2518 HBasicBlock* block) {
2519 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002520 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002521 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002522 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002523 const HUseList<HInstruction*>& uses = instruction->GetUses();
2524 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2525 HInstruction* user = it->GetUser();
2526 size_t index = it->GetIndex();
2527 ++it; // increment before replacing
2528 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002529 if (kIsDebugBuild) {
2530 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2531 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2532 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2533 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002534 user->ReplaceInput(replacement, index);
2535 induction_range_.Replace(user, instruction, replacement); // update induction
2536 }
2537 }
Aart Bikb29f6842017-07-28 15:58:41 -07002538 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002539 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2540 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2541 HEnvironment* user = it->GetUser();
2542 size_t index = it->GetIndex();
2543 ++it; // increment before replacing
2544 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002545 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002546 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002547 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2548 user->RemoveAsUserOfInput(index);
2549 user->SetRawEnvAt(index, replacement);
2550 replacement->AddEnvUseAt(user, index);
2551 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002552 }
2553 }
Aart Bik807868e2016-11-03 17:51:43 -07002554 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002555 }
Aart Bik807868e2016-11-03 17:51:43 -07002556 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002557}
2558
Aart Bikf8f5a162017-02-06 15:35:29 -08002559bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2560 HInstruction* instruction,
2561 HBasicBlock* block,
2562 bool collect_loop_uses) {
2563 // Assigning the last value is always successful if there are no uses.
2564 // Otherwise, it succeeds in a no early-exit loop by generating the
2565 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002566 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002567 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2568 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002569 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002570}
2571
Aart Bik6b69e0a2017-01-11 10:20:43 -08002572void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2573 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2574 HInstruction* instruction = i.Current();
2575 if (instruction->IsDeadAndRemovable()) {
2576 simplified_ = true;
2577 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2578 }
2579 }
2580}
2581
Aart Bik14a68b42017-06-08 14:06:58 -07002582bool HLoopOptimization::CanRemoveCycle() {
2583 for (HInstruction* i : *iset_) {
2584 // We can never remove instructions that have environment
2585 // uses when we compile 'debuggable'.
2586 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2587 return false;
2588 }
2589 // A deoptimization should never have an environment input removed.
2590 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2591 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2592 return false;
2593 }
2594 }
2595 }
2596 return true;
2597}
2598
Aart Bik281c6812016-08-26 11:31:48 -07002599} // namespace art