blob: cd054822cd5972b8ca2f070ef80d9e368b49acd7 [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//
Stelios Ioannou3de02fb2021-07-09 17:06:03 +0100639// This optimization applies to loops with plain simple operations
640// (I.e. no calls to java code or runtime) with a known small trip_count * instr_count
641// value.
642//
643bool HLoopOptimization::TryToRemoveSuspendCheckFromLoopHeader(LoopAnalysisInfo* analysis_info,
644 bool generate_code) {
645 if (!graph_->SuspendChecksAreAllowedToBeRemoved()) {
646 return false;
647 }
648
649 int64_t trip_count = analysis_info->GetTripCount();
650
651 if (trip_count == LoopAnalysisInfo::kUnknownTripCount) {
652 return false;
653 }
654
655 int64_t instruction_count = analysis_info->GetNumberOfInstructions();
656 int64_t total_instruction_count = trip_count * instruction_count;
657
658 // The inclusion of the HasInstructionsPreventingScalarOpts() prevents this
659 // optimization from being applied to loops that have calls.
660 bool can_optimize =
661 total_instruction_count <= HLoopOptimization::kMaxTotalInstRemoveSuspendCheck &&
662 !analysis_info->HasInstructionsPreventingScalarOpts();
663
664 if (!can_optimize) {
665 return false;
666 }
667
668 if (generate_code) {
669 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
670 HBasicBlock* header = loop_info->GetHeader();
671 HInstruction* instruction = header->GetLoopInformation()->GetSuspendCheck();
672 header->RemoveInstruction(instruction);
673 loop_info->SetSuspendCheck(nullptr);
674 }
675
676 return true;
677}
678
679//
Aart Bikf8f5a162017-02-06 15:35:29 -0800680// Optimization.
681//
682
Aart Bik281c6812016-08-26 11:31:48 -0700683void HLoopOptimization::SimplifyInduction(LoopNode* node) {
684 HBasicBlock* header = node->loop_info->GetHeader();
685 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700686 // Scan the phis in the header to find opportunities to simplify an induction
687 // cycle that is only used outside the loop. Replace these uses, if any, with
688 // the last value and remove the induction cycle.
689 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
690 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700691 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
692 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800693 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
694 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700695 // Note that it's ok to have replaced uses after the loop with the last value, without
696 // being able to remove the cycle. Environment uses (which are the reason we may not be
697 // able to remove the cycle) within the loop will still hold the right value. We must
698 // have tried first, however, to replace outside uses.
699 if (CanRemoveCycle()) {
700 simplified_ = true;
701 for (HInstruction* i : *iset_) {
702 RemoveFromCycle(i);
703 }
704 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700705 }
Aart Bik482095d2016-10-10 15:39:10 -0700706 }
707 }
708}
709
710void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800711 // Iterate over all basic blocks in the loop-body.
712 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
713 HBasicBlock* block = it.Current();
714 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800715 RemoveDeadInstructions(block->GetPhis());
716 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800717 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800718 if (block->GetPredecessors().size() == 1 &&
719 block->GetSuccessors().size() == 1 &&
720 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800721 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800722 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800723 } else if (block->GetSuccessors().size() == 2) {
724 // Trivial if block can be bypassed to either branch.
725 HBasicBlock* succ0 = block->GetSuccessors()[0];
726 HBasicBlock* succ1 = block->GetSuccessors()[1];
727 HBasicBlock* meet0 = nullptr;
728 HBasicBlock* meet1 = nullptr;
729 if (succ0 != succ1 &&
730 IsGotoBlock(succ0, &meet0) &&
731 IsGotoBlock(succ1, &meet1) &&
732 meet0 == meet1 && // meets again
733 meet0 != block && // no self-loop
734 meet0->GetPhis().IsEmpty()) { // not used for merging
735 simplified_ = true;
736 succ0->DisconnectAndDelete();
737 if (block->Dominates(meet0)) {
738 block->RemoveDominatedBlock(meet0);
739 succ1->AddDominatedBlock(meet0);
740 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700741 }
Aart Bik482095d2016-10-10 15:39:10 -0700742 }
Aart Bik281c6812016-08-26 11:31:48 -0700743 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800744 }
Aart Bik281c6812016-08-26 11:31:48 -0700745}
746
Artem Serov121f2032017-10-23 19:19:06 +0100747bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700748 HBasicBlock* header = node->loop_info->GetHeader();
749 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700750 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800751 int64_t trip_count = 0;
752 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700753 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700754 }
Aart Bik281c6812016-08-26 11:31:48 -0700755 // Ensure there is only a single loop-body (besides the header).
756 HBasicBlock* body = nullptr;
757 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
758 if (it.Current() != header) {
759 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700760 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700761 }
762 body = it.Current();
763 }
764 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700765 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700766 // Ensure there is only a single exit point.
767 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700768 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700769 }
770 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
771 ? header->GetSuccessors()[1]
772 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700773 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700774 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700775 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700776 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800777 // Detect either an empty loop (no side effects other than plain iteration) or
778 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
779 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700780 HPhi* main_phi = nullptr;
781 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800782 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700783 if (reductions_->empty() && // TODO: possible with some effort
784 (is_empty || trip_count == 1) &&
785 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800786 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800787 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700788 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800789 preheader->MergeInstructionsWith(body);
790 }
791 body->DisconnectAndDelete();
792 exit->RemovePredecessor(header);
793 header->RemoveSuccessor(exit);
794 header->RemoveDominatedBlock(exit);
795 header->DisconnectAndDelete();
796 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800797 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800798 preheader->AddDominatedBlock(exit);
799 exit->SetDominator(preheader);
800 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700801 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800802 }
803 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800804 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700805 if (kEnableVectorization &&
Artem Serove65ade72019-07-25 21:04:16 +0100806 // Disable vectorization for debuggable graphs: this is a workaround for the bug
807 // in 'GenerateNewLoop' which caused the SuspendCheck environment to be invalid.
808 // TODO: b/138601207, investigate other possible cases with wrong environment values and
809 // possibly switch back vectorization on for debuggable graphs.
810 !graph_->IsDebuggable() &&
Aart Bikb29f6842017-07-28 15:58:41 -0700811 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700812 ShouldVectorize(node, body, trip_count) &&
813 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
814 Vectorize(node, body, exit, trip_count);
815 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700816 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700817 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800818 }
Aart Bikb29f6842017-07-28 15:58:41 -0700819 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800820}
821
Artem Serov121f2032017-10-23 19:19:06 +0100822bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Stelios Ioannou3de02fb2021-07-09 17:06:03 +0100823 return TryOptimizeInnerLoopFinite(node) || TryLoopScalarOpts(node);
Artem Serov121f2032017-10-23 19:19:06 +0100824}
825
Artem Serov121f2032017-10-23 19:19:06 +0100826
Artem Serov121f2032017-10-23 19:19:06 +0100827
828//
Artem Serov0e329082018-06-12 10:23:27 +0100829// Scalar loop peeling and unrolling: generic part methods.
Artem Serov121f2032017-10-23 19:19:06 +0100830//
831
Artem Serov0e329082018-06-12 10:23:27 +0100832bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
833 bool generate_code) {
834 if (analysis_info->GetNumberOfExits() > 1) {
Artem Serov121f2032017-10-23 19:19:06 +0100835 return false;
836 }
837
Artem Serov0e329082018-06-12 10:23:27 +0100838 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
839 if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
Artem Serov121f2032017-10-23 19:19:06 +0100840 return false;
841 }
842
Artem Serov0e329082018-06-12 10:23:27 +0100843 if (generate_code) {
844 // TODO: support other unrolling factors.
845 DCHECK_EQ(unrolling_factor, 2u);
846
847 // Perform unrolling.
848 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov0f5b2bf2019-10-23 14:07:41 +0100849 LoopClonerSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100850 helper.DoUnrolling();
851
852 // Remove the redundant loop check after unrolling.
853 HIf* copy_hif =
854 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
855 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
856 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
Artem Serov121f2032017-10-23 19:19:06 +0100857 }
Artem Serov121f2032017-10-23 19:19:06 +0100858 return true;
859}
860
Artem Serov0e329082018-06-12 10:23:27 +0100861bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
862 bool generate_code) {
863 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov72411e62017-10-19 16:18:07 +0100864 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
865 return false;
866 }
867
Artem Serov0e329082018-06-12 10:23:27 +0100868 if (analysis_info->GetNumberOfInvariantExits() == 0) {
Artem Serov72411e62017-10-19 16:18:07 +0100869 return false;
870 }
871
Artem Serov0e329082018-06-12 10:23:27 +0100872 if (generate_code) {
873 // Perform peeling.
Artem Serov0f5b2bf2019-10-23 14:07:41 +0100874 LoopClonerSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100875 helper.DoPeeling();
Artem Serov72411e62017-10-19 16:18:07 +0100876
Artem Serov0e329082018-06-12 10:23:27 +0100877 // Statically evaluate loop check after peeling for loop invariant condition.
878 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
879 for (auto entry : *hir_map) {
880 HInstruction* copy = entry.second;
881 if (copy->IsIf()) {
882 TryToEvaluateIfCondition(copy->AsIf(), graph_);
883 }
Artem Serov72411e62017-10-19 16:18:07 +0100884 }
885 }
886
887 return true;
888}
889
Artem Serov18ba1da2018-05-16 19:06:32 +0100890bool HLoopOptimization::TryFullUnrolling(LoopAnalysisInfo* analysis_info, bool generate_code) {
891 // Fully unroll loops with a known and small trip count.
892 int64_t trip_count = analysis_info->GetTripCount();
893 if (!arch_loop_helper_->IsLoopPeelingEnabled() ||
894 trip_count == LoopAnalysisInfo::kUnknownTripCount ||
895 !arch_loop_helper_->IsFullUnrollingBeneficial(analysis_info)) {
896 return false;
897 }
898
899 if (generate_code) {
900 // Peeling of the N first iterations (where N equals to the trip count) will effectively
901 // eliminate the loop: after peeling we will have N sequential iterations copied into the loop
902 // preheader and the original loop. The trip count of this loop will be 0 as the sequential
903 // iterations are executed first and there are exactly N of them. Thus we can statically
904 // evaluate the loop exit condition to 'false' and fully eliminate it.
905 //
906 // Here is an example of full unrolling of a loop with a trip count 2:
907 //
908 // loop_cond_1
909 // loop_body_1 <- First iteration.
910 // |
911 // \ v
912 // ==\ loop_cond_2
913 // ==/ loop_body_2 <- Second iteration.
914 // / |
915 // <- v <-
916 // loop_cond \ loop_cond \ <- This cond is always false.
917 // loop_body _/ loop_body _/
918 //
919 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100920 PeelByCount(loop_info, trip_count, &induction_range_);
Artem Serov18ba1da2018-05-16 19:06:32 +0100921 HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
922 int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
923 loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
924 }
925
926 return true;
927}
928
Stelios Ioannou3de02fb2021-07-09 17:06:03 +0100929bool HLoopOptimization::TryLoopScalarOpts(LoopNode* node) {
Artem Serov0e329082018-06-12 10:23:27 +0100930 HLoopInformation* loop_info = node->loop_info;
931 int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
932 LoopAnalysisInfo analysis_info(loop_info);
933 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
934
935 if (analysis_info.HasInstructionsPreventingScalarOpts() ||
936 arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
937 return false;
938 }
939
Artem Serov18ba1da2018-05-16 19:06:32 +0100940 if (!TryFullUnrolling(&analysis_info, /*generate_code*/ false) &&
941 !TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
Stelios Ioannou3de02fb2021-07-09 17:06:03 +0100942 !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false) &&
943 !TryToRemoveSuspendCheckFromLoopHeader(&analysis_info, /*generate_code*/ false)) {
Artem Serov0e329082018-06-12 10:23:27 +0100944 return false;
945 }
946
Stelios Ioannou3de02fb2021-07-09 17:06:03 +0100947 // Try the suspend check removal even for non-clonable loops. Also this
948 // optimization doesn't interfere with other scalar loop optimizations so it can
949 // be done prior to them.
950 bool removed_suspend_check = TryToRemoveSuspendCheckFromLoopHeader(&analysis_info);
951
Artem Serov0e329082018-06-12 10:23:27 +0100952 // Run 'IsLoopClonable' the last as it might be time-consuming.
Artem Serov0f5b2bf2019-10-23 14:07:41 +0100953 if (!LoopClonerHelper::IsLoopClonable(loop_info)) {
Artem Serov0e329082018-06-12 10:23:27 +0100954 return false;
955 }
956
Artem Serov18ba1da2018-05-16 19:06:32 +0100957 return TryFullUnrolling(&analysis_info) ||
958 TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
Stelios Ioannou3de02fb2021-07-09 17:06:03 +0100959 TryUnrollingForBranchPenaltyReduction(&analysis_info) || removed_suspend_check;
Artem Serov0e329082018-06-12 10:23:27 +0100960}
961
Aart Bikf8f5a162017-02-06 15:35:29 -0800962//
963// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
964// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
965// Intel Press, June, 2004 (http://www.aartbik.com/).
966//
967
Aart Bik14a68b42017-06-08 14:06:58 -0700968bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800969 // Reset vector bookkeeping.
970 vector_length_ = 0;
971 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700972 vector_static_peeling_factor_ = 0;
973 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800974 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800975 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800976
977 // Phis in the loop-body prevent vectorization.
978 if (!block->GetPhis().IsEmpty()) {
979 return false;
980 }
981
982 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
983 // occurrence, which allows passing down attributes down the use tree.
984 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
985 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
986 return false; // failure to vectorize a left-hand-side
987 }
988 }
989
Aart Bik38a3f212017-10-20 17:02:21 -0700990 // Prepare alignment analysis:
991 // (1) find desired alignment (SIMD vector size in bytes).
992 // (2) initialize static loop peeling votes (peeling factor that will
993 // make one particular reference aligned), never to exceed (1).
994 // (3) variable to record how many references share same alignment.
995 // (4) variable to record suitable candidate for dynamic loop peeling.
Artem Serov55ab7e82020-04-27 21:02:28 +0100996 size_t desired_alignment = GetVectorSizeInBytes();
997 ScopedArenaVector<uint32_t> peeling_votes(desired_alignment, 0u,
998 loop_allocator_->Adapter(kArenaAllocLoopOptimization));
999
Aart Bik38a3f212017-10-20 17:02:21 -07001000 uint32_t max_num_same_alignment = 0;
1001 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -08001002
1003 // Data dependence analysis. Find each pair of references with same type, where
1004 // at least one is a write. Each such pair denotes a possible data dependence.
1005 // This analysis exploits the property that differently typed arrays cannot be
1006 // aliased, as well as the property that references either point to the same
1007 // array or to two completely disjoint arrays, i.e., no partial aliasing.
1008 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -07001009 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -08001010 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -07001011 uint32_t num_same_alignment = 0;
1012 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -08001013 for (auto j = i; ++j != vector_refs_->end(); ) {
1014 if (i->type == j->type && (i->lhs || j->lhs)) {
1015 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
1016 HInstruction* a = i->base;
1017 HInstruction* b = j->base;
1018 HInstruction* x = i->offset;
1019 HInstruction* y = j->offset;
1020 if (a == b) {
1021 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
1022 // Conservatively assume a loop-carried data dependence otherwise, and reject.
1023 if (x != y) {
1024 return false;
1025 }
Aart Bik38a3f212017-10-20 17:02:21 -07001026 // Count the number of references that have the same alignment (since
1027 // base and offset are the same) and where at least one is a write, so
1028 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
1029 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -08001030 } else {
1031 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
1032 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
1033 // generating an explicit a != b disambiguation runtime test on the two references.
1034 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -07001035 // To avoid excessive overhead, we only accept one a != b test.
1036 if (vector_runtime_test_a_ == nullptr) {
1037 // First test found.
1038 vector_runtime_test_a_ = a;
1039 vector_runtime_test_b_ = b;
1040 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
1041 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
1042 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -08001043 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001044 }
1045 }
1046 }
1047 }
Aart Bik38a3f212017-10-20 17:02:21 -07001048 // Update information for finding suitable alignment strategy:
1049 // (1) update votes for static loop peeling,
1050 // (2) update suitable candidate for dynamic loop peeling.
1051 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1052 if (alignment.Base() >= desired_alignment) {
1053 // If the array/string object has a known, sufficient alignment, use the
1054 // initial offset to compute the static loop peeling vote (this always
1055 // works, since elements have natural alignment).
1056 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1057 uint32_t vote = (offset == 0)
1058 ? 0
1059 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1060 DCHECK_LT(vote, 16u);
1061 ++peeling_votes[vote];
1062 } else if (BaseAlignment() >= desired_alignment &&
1063 num_same_alignment > max_num_same_alignment) {
1064 // Otherwise, if the array/string object has a known, sufficient alignment
1065 // for just the base but with an unknown offset, record the candidate with
1066 // the most occurrences for dynamic loop peeling (again, the peeling always
1067 // works, since elements have natural alignment).
1068 max_num_same_alignment = num_same_alignment;
1069 peeling_candidate = &(*i);
1070 }
1071 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -08001072
Artem Serov8ba4de12019-12-04 21:10:23 +00001073 if (!IsInPredicatedVectorizationMode()) {
1074 // Find a suitable alignment strategy.
1075 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1076 }
Aart Bik38a3f212017-10-20 17:02:21 -07001077
1078 // Does vectorization seem profitable?
1079 if (!IsVectorizationProfitable(trip_count)) {
1080 return false;
1081 }
Aart Bik14a68b42017-06-08 14:06:58 -07001082
Aart Bikf8f5a162017-02-06 15:35:29 -08001083 // Success!
1084 return true;
1085}
1086
1087void HLoopOptimization::Vectorize(LoopNode* node,
1088 HBasicBlock* block,
1089 HBasicBlock* exit,
1090 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001091 HBasicBlock* header = node->loop_info->GetHeader();
1092 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1093
Aart Bik14a68b42017-06-08 14:06:58 -07001094 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +01001095 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1096 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -07001097 uint32_t chunk = vector_length_ * unroll;
1098
Aart Bik38a3f212017-10-20 17:02:21 -07001099 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1100
Aart Bik14a68b42017-06-08 14:06:58 -07001101 // A cleanup loop is needed, at least, for any unknown trip count or
1102 // for a known trip count with remainder iterations after vectorization.
Artem Serov8ba4de12019-12-04 21:10:23 +00001103 bool needs_cleanup = !IsInPredicatedVectorizationMode() &&
1104 (trip_count == 0 || ((trip_count - vector_static_peeling_factor_) % chunk) != 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001105
1106 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -07001107 HPhi* main_phi = nullptr;
1108 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -08001109 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -07001110 vector_header_ = header;
1111 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -08001112
Aart Bikdbbac8f2017-09-01 13:06:08 -07001113 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001114 DataType::Type induc_type = main_phi->GetType();
1115 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1116 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001117
Aart Bik38a3f212017-10-20 17:02:21 -07001118 // Generate the trip count for static or dynamic loop peeling, if needed:
1119 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001120 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001121 if (vector_static_peeling_factor_ != 0) {
Artem Serov8ba4de12019-12-04 21:10:23 +00001122 DCHECK(!IsInPredicatedVectorizationMode());
Aart Bik38a3f212017-10-20 17:02:21 -07001123 // Static loop peeling for SIMD alignment (using the most suitable
1124 // fixed peeling factor found during prior alignment analysis).
1125 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1126 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1127 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
Artem Serov8ba4de12019-12-04 21:10:23 +00001128 DCHECK(!IsInPredicatedVectorizationMode());
Aart Bik38a3f212017-10-20 17:02:21 -07001129 // Dynamic loop peeling for SIMD alignment (using the most suitable
1130 // candidate found during prior alignment analysis):
1131 // rem = offset % ALIGN; // adjusted as #elements
1132 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1133 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1134 uint32_t align = GetVectorSizeInBytes() >> shift;
1135 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1136 vector_dynamic_peeling_candidate_->is_string_char_at);
1137 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1138 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1139 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1140 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1141 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1142 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1143 induc_type, graph_->GetConstant(induc_type, align), rem));
1144 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1145 rem, graph_->GetConstant(induc_type, 0)));
1146 ptc = Insert(preheader, new (global_allocator_) HSelect(
1147 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1148 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001149 }
1150
1151 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001152 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001153 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001154 // vtc = stc - (stc - ptc) % chunk;
1155 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001156 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1157 HInstruction* vtc = stc;
1158 if (needs_cleanup) {
Artem Serov8ba4de12019-12-04 21:10:23 +00001159 DCHECK(!IsInPredicatedVectorizationMode());
Aart Bik14a68b42017-06-08 14:06:58 -07001160 DCHECK(IsPowerOfTwo(chunk));
1161 HInstruction* diff = stc;
1162 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001163 if (trip_count == 0) {
1164 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1165 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1166 }
Aart Bik14a68b42017-06-08 14:06:58 -07001167 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1168 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001169 HInstruction* rem = Insert(
1170 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001171 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001172 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001173 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1174 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001175 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001176
1177 // Generate runtime disambiguation test:
1178 // vtc = a != b ? vtc : 0;
1179 if (vector_runtime_test_a_ != nullptr) {
1180 HInstruction* rt = Insert(
1181 preheader,
1182 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1183 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001184 new (global_allocator_)
1185 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001186 needs_cleanup = true;
1187 }
1188
Aart Bik38a3f212017-10-20 17:02:21 -07001189 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001190 // for ( ; i < ptc; i += 1)
1191 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001192 //
1193 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1194 // moved around during suspend checks, since all analysis was based on
1195 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001196 if (ptc != nullptr) {
Artem Serov8ba4de12019-12-04 21:10:23 +00001197 DCHECK(!IsInPredicatedVectorizationMode());
Aart Bik14a68b42017-06-08 14:06:58 -07001198 vector_mode_ = kSequential;
1199 GenerateNewLoop(node,
1200 block,
1201 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1202 vector_index_,
1203 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001204 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001205 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001206 }
1207
1208 // Generate vector loop, possibly further unrolled:
1209 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001210 // <vectorized-loop-body>
1211 vector_mode_ = kVector;
1212 GenerateNewLoop(node,
1213 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001214 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1215 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001216 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001217 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001218 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001219 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1220
1221 // Generate cleanup loop, if needed:
1222 // for ( ; i < stc; i += 1)
1223 // <loop-body>
1224 if (needs_cleanup) {
Artem Serov8ba4de12019-12-04 21:10:23 +00001225 DCHECK(!IsInPredicatedVectorizationMode() || vector_runtime_test_a_ != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -08001226 vector_mode_ = kSequential;
1227 GenerateNewLoop(node,
1228 block,
1229 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001230 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001231 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001232 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001233 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001234 }
1235
Aart Bik0148de42017-09-05 09:25:01 -07001236 // Link reductions to their final uses.
1237 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1238 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001239 HInstruction* phi = i->first;
1240 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1241 // Deal with regular uses.
1242 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1243 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1244 }
1245 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001246 }
1247 }
1248
Aart Bikf8f5a162017-02-06 15:35:29 -08001249 // Remove the original loop by disconnecting the body block
1250 // and removing all instructions from the header.
1251 block->DisconnectAndDelete();
1252 while (!header->GetFirstInstruction()->IsGoto()) {
1253 header->RemoveInstruction(header->GetFirstInstruction());
1254 }
Aart Bikb29f6842017-07-28 15:58:41 -07001255
Aart Bik14a68b42017-06-08 14:06:58 -07001256 // Update loop hierarchy: the old header now resides in the same outer loop
1257 // as the old preheader. Note that we don't bother putting sequential
1258 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001259 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1260 node->loop_info = vloop;
1261}
1262
1263void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1264 HBasicBlock* block,
1265 HBasicBlock* new_preheader,
1266 HInstruction* lo,
1267 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001268 HInstruction* step,
1269 uint32_t unroll) {
1270 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001271 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001272 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001273 vector_preheader_ = new_preheader,
1274 vector_header_ = vector_preheader_->GetSingleSuccessor();
1275 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001276 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1277 kNoRegNumber,
1278 0,
1279 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001280 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001281 // for (i = lo; i < hi; i += step)
1282 // <loop-body>
Artem Serov8ba4de12019-12-04 21:10:23 +00001283 HInstruction* cond = nullptr;
1284 HInstruction* set_pred = nullptr;
1285 if (IsInPredicatedVectorizationMode()) {
1286 HVecPredWhile* pred_while =
1287 new (global_allocator_) HVecPredWhile(global_allocator_,
1288 phi,
1289 hi,
1290 HVecPredWhile::CondKind::kLO,
1291 DataType::Type::kInt32,
1292 vector_length_,
1293 0u);
1294
1295 cond = new (global_allocator_) HVecPredCondition(global_allocator_,
1296 pred_while,
1297 HVecPredCondition::PCondKind::kNFirst,
1298 DataType::Type::kInt32,
1299 vector_length_,
1300 0u);
1301
1302 vector_header_->AddPhi(phi);
1303 vector_header_->AddInstruction(pred_while);
1304 vector_header_->AddInstruction(cond);
1305 set_pred = pred_while;
1306 } else {
1307 cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1308 vector_header_->AddPhi(phi);
1309 vector_header_->AddInstruction(cond);
1310 }
1311
Aart Bikf8f5a162017-02-06 15:35:29 -08001312 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001313 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001314 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001315 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001316 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001317 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001318 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1319 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1320 DCHECK(vectorized_def);
1321 }
1322 // Generate body from the instruction map, but in original program order.
1323 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1324 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1325 auto i = vector_map_->find(it.Current());
1326 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1327 Insert(vector_body_, i->second);
Artem Serov8ba4de12019-12-04 21:10:23 +00001328 if (IsInPredicatedVectorizationMode() && i->second->IsVecOperation()) {
1329 HVecOperation* op = i->second->AsVecOperation();
1330 op->SetMergingGoverningPredicate(set_pred);
1331 }
Aart Bik14a68b42017-06-08 14:06:58 -07001332 // Deal with instructions that need an environment, such as the scalar intrinsics.
1333 if (i->second->NeedsEnvironment()) {
1334 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1335 }
1336 }
1337 }
Aart Bik0148de42017-09-05 09:25:01 -07001338 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001339 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1340 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001341 }
Aart Bik0148de42017-09-05 09:25:01 -07001342 // Finalize phi inputs for the reductions (if any).
1343 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1344 if (!i->first->IsPhi()) {
1345 DCHECK(i->second->IsPhi());
1346 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1347 }
1348 }
Aart Bikb29f6842017-07-28 15:58:41 -07001349 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001350 phi->AddInput(lo);
1351 phi->AddInput(vector_index_);
1352 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001353}
1354
Aart Bikf8f5a162017-02-06 15:35:29 -08001355bool HLoopOptimization::VectorizeDef(LoopNode* node,
1356 HInstruction* instruction,
1357 bool generate_code) {
1358 // Accept a left-hand-side array base[index] for
1359 // (1) supported vector type,
1360 // (2) loop-invariant base,
1361 // (3) unit stride index,
1362 // (4) vectorizable right-hand-side value.
1363 uint64_t restrictions = kNone;
Georgia Kouvelibac080b2019-01-31 16:12:16 +00001364 // Don't accept expressions that can throw.
1365 if (instruction->CanThrow()) {
1366 return false;
1367 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001368 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001369 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001370 HInstruction* base = instruction->InputAt(0);
1371 HInstruction* index = instruction->InputAt(1);
1372 HInstruction* value = instruction->InputAt(2);
1373 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001374 // For narrow types, explicit type conversion may have been
1375 // optimized way, so set the no hi bits restriction here.
1376 if (DataType::Size(type) <= 2) {
1377 restrictions |= kNoHiBits;
1378 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001379 if (TrySetVectorType(type, &restrictions) &&
1380 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001381 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001382 VectorizeUse(node, value, generate_code, type, restrictions)) {
1383 if (generate_code) {
1384 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001385 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001386 } else {
1387 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1388 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001389 return true;
1390 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001391 return false;
1392 }
Aart Bik0148de42017-09-05 09:25:01 -07001393 // Accept a left-hand-side reduction for
1394 // (1) supported vector type,
1395 // (2) vectorizable right-hand-side value.
1396 auto redit = reductions_->find(instruction);
1397 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001398 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001399 // Recognize SAD idiom or direct reduction.
1400 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
Artem Serovaaac0e32018-08-07 00:52:22 +01001401 VectorizeDotProdIdiom(node, instruction, generate_code, type, restrictions) ||
Aart Bikdbbac8f2017-09-01 13:06:08 -07001402 (TrySetVectorType(type, &restrictions) &&
1403 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001404 if (generate_code) {
1405 HInstruction* new_red = vector_map_->Get(instruction);
1406 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1407 vector_permanent_map_->Overwrite(redit->second, new_red);
1408 }
1409 return true;
1410 }
1411 return false;
1412 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001413 // Branch back okay.
1414 if (instruction->IsGoto()) {
1415 return true;
1416 }
1417 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1418 // Note that actual uses are inspected during right-hand-side tree traversal.
Georgia Kouvelibac080b2019-01-31 16:12:16 +00001419 return !IsUsedOutsideLoop(node->loop_info, instruction)
1420 && !instruction->DoesAnyWrite();
Aart Bikf8f5a162017-02-06 15:35:29 -08001421}
1422
Aart Bikf8f5a162017-02-06 15:35:29 -08001423bool HLoopOptimization::VectorizeUse(LoopNode* node,
1424 HInstruction* instruction,
1425 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001426 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001427 uint64_t restrictions) {
1428 // Accept anything for which code has already been generated.
1429 if (generate_code) {
1430 if (vector_map_->find(instruction) != vector_map_->end()) {
1431 return true;
1432 }
1433 }
1434 // Continue the right-hand-side tree traversal, passing in proper
1435 // types and vector restrictions along the way. During code generation,
1436 // all new nodes are drawn from the global allocator.
1437 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1438 // Accept invariant use, using scalar expansion.
1439 if (generate_code) {
1440 GenerateVecInv(instruction, type);
1441 }
1442 return true;
1443 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001444 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001445 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
Artem Serov8ba4de12019-12-04 21:10:23 +00001446
1447 if (is_string_char_at && (HasVectorRestrictions(restrictions, kNoStringCharAt) ||
1448 IsInPredicatedVectorizationMode())) {
1449 // TODO: Support CharAt for predicated mode.
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001450 return false;
1451 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001452 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001453 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001454 // (2) loop-invariant base,
1455 // (3) unit stride index,
1456 // (4) vectorizable right-hand-side value.
1457 HInstruction* base = instruction->InputAt(0);
1458 HInstruction* index = instruction->InputAt(1);
1459 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001460 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001461 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001462 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001463 if (generate_code) {
1464 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001465 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001466 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001467 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001468 }
1469 return true;
1470 }
Aart Bik0148de42017-09-05 09:25:01 -07001471 } else if (instruction->IsPhi()) {
1472 // Accept particular phi operations.
1473 if (reductions_->find(instruction) != reductions_->end()) {
1474 // Deal with vector restrictions.
1475 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1476 return false;
1477 }
1478 // Accept a reduction.
1479 if (generate_code) {
1480 GenerateVecReductionPhi(instruction->AsPhi());
1481 }
1482 return true;
1483 }
1484 // TODO: accept right-hand-side induction?
1485 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001486 } else if (instruction->IsTypeConversion()) {
1487 // Accept particular type conversions.
1488 HTypeConversion* conversion = instruction->AsTypeConversion();
1489 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001490 DataType::Type from = conversion->GetInputType();
1491 DataType::Type to = conversion->GetResultType();
1492 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001493 uint32_t size_vec = DataType::Size(type);
1494 uint32_t size_from = DataType::Size(from);
1495 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001496 // Accept an integral conversion
1497 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1498 // (1b) widening from at least vector type, and
1499 // (2) vectorizable operand.
1500 if ((size_to < size_from &&
1501 size_to == size_vec &&
1502 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1503 (size_to >= size_from &&
1504 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001505 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001506 if (generate_code) {
1507 if (vector_mode_ == kVector) {
1508 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1509 } else {
1510 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1511 }
1512 }
1513 return true;
1514 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001515 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001516 DCHECK_EQ(to, type);
1517 // Accept int to float conversion for
1518 // (1) supported int,
1519 // (2) vectorizable operand.
1520 if (TrySetVectorType(from, &restrictions) &&
1521 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1522 if (generate_code) {
1523 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1524 }
1525 return true;
1526 }
1527 }
1528 return false;
1529 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1530 // Accept unary operator for vectorizable operand.
1531 HInstruction* opa = instruction->InputAt(0);
1532 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1533 if (generate_code) {
1534 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1535 }
1536 return true;
1537 }
1538 } else if (instruction->IsAdd() || instruction->IsSub() ||
1539 instruction->IsMul() || instruction->IsDiv() ||
1540 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1541 // Deal with vector restrictions.
1542 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1543 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1544 return false;
1545 }
1546 // Accept binary operator for vectorizable operands.
1547 HInstruction* opa = instruction->InputAt(0);
1548 HInstruction* opb = instruction->InputAt(1);
1549 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1550 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1551 if (generate_code) {
1552 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1553 }
1554 return true;
1555 }
1556 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001557 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001558 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1559 return true;
1560 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001561 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001562 HInstruction* opa = instruction->InputAt(0);
1563 HInstruction* opb = instruction->InputAt(1);
1564 HInstruction* r = opa;
1565 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001566 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1567 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1568 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001569 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1570 // Shifts right need extra care to account for higher order bits.
1571 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1572 if (instruction->IsShr() &&
1573 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1574 return false; // reject, unless all operands are sign-extension narrower
1575 } else if (instruction->IsUShr() &&
1576 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1577 return false; // reject, unless all operands are zero-extension narrower
1578 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001579 }
1580 // Accept shift operator for vectorizable/invariant operands.
1581 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001582 DCHECK(r != nullptr);
1583 if (generate_code && vector_mode_ != kVector) { // de-idiom
1584 r = opa;
1585 }
Aart Bik50e20d52017-05-05 14:07:29 -07001586 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001587 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001588 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001589 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001590 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001591 if (0 <= distance && distance < max_distance) {
1592 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001593 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001594 }
1595 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001596 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001597 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001598 } else if (instruction->IsAbs()) {
1599 // Deal with vector restrictions.
1600 HInstruction* opa = instruction->InputAt(0);
1601 HInstruction* r = opa;
1602 bool is_unsigned = false;
1603 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1604 return false;
1605 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1606 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1607 return false; // reject, unless operand is sign-extension narrower
1608 }
1609 // Accept ABS(x) for vectorizable operand.
1610 DCHECK(r != nullptr);
1611 if (generate_code && vector_mode_ != kVector) { // de-idiom
1612 r = opa;
1613 }
1614 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1615 if (generate_code) {
1616 GenerateVecOp(instruction,
1617 vector_map_->Get(r),
1618 nullptr,
1619 HVecOperation::ToProperType(type, is_unsigned));
1620 }
1621 return true;
1622 }
Aart Bik281c6812016-08-26 11:31:48 -07001623 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001624 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001625}
1626
Aart Bik38a3f212017-10-20 17:02:21 -07001627uint32_t HLoopOptimization::GetVectorSizeInBytes() {
Artem Serovc8150b52019-07-31 18:28:00 +01001628 return simd_register_size_;
Aart Bik38a3f212017-10-20 17:02:21 -07001629}
1630
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001631bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001632 const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
1633 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001634 case InstructionSet::kArm:
1635 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001636 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001637 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001638 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001639 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001640 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001641 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001642 *restrictions |= kNoDiv | kNoReduction | kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001643 return TrySetVectorLength(type, 8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001644 case DataType::Type::kUint16:
1645 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001646 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001647 return TrySetVectorLength(type, 4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001648 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001649 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001650 return TrySetVectorLength(type, 2);
Artem Serov8f7c4102017-06-21 11:21:37 +01001651 default:
1652 break;
1653 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001654 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001655 case InstructionSet::kArm64:
Artem Serov8ba4de12019-12-04 21:10:23 +00001656 if (IsInPredicatedVectorizationMode()) {
1657 // SVE vectorization.
1658 CHECK(features->AsArm64InstructionSetFeatures()->HasSVE());
Artem Serov55ab7e82020-04-27 21:02:28 +01001659 size_t vector_length = simd_register_size_ / DataType::Size(type);
1660 DCHECK_EQ(simd_register_size_ % DataType::Size(type), 0u);
Artem Serov8ba4de12019-12-04 21:10:23 +00001661 switch (type) {
1662 case DataType::Type::kBool:
1663 case DataType::Type::kUint8:
1664 case DataType::Type::kInt8:
1665 *restrictions |= kNoDiv |
1666 kNoSignedHAdd |
1667 kNoUnsignedHAdd |
1668 kNoUnroundedHAdd |
1669 kNoSAD;
Artem Serov55ab7e82020-04-27 21:02:28 +01001670 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001671 case DataType::Type::kUint16:
1672 case DataType::Type::kInt16:
1673 *restrictions |= kNoDiv |
1674 kNoSignedHAdd |
1675 kNoUnsignedHAdd |
1676 kNoUnroundedHAdd |
1677 kNoSAD |
1678 kNoDotProd;
Artem Serov55ab7e82020-04-27 21:02:28 +01001679 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001680 case DataType::Type::kInt32:
1681 *restrictions |= kNoDiv | kNoSAD;
Artem Serov55ab7e82020-04-27 21:02:28 +01001682 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001683 case DataType::Type::kInt64:
1684 *restrictions |= kNoDiv | kNoSAD;
Artem Serov55ab7e82020-04-27 21:02:28 +01001685 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001686 case DataType::Type::kFloat32:
1687 *restrictions |= kNoReduction;
Artem Serov55ab7e82020-04-27 21:02:28 +01001688 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001689 case DataType::Type::kFloat64:
1690 *restrictions |= kNoReduction;
Artem Serov55ab7e82020-04-27 21:02:28 +01001691 return TrySetVectorLength(type, vector_length);
Artem Serov8ba4de12019-12-04 21:10:23 +00001692 default:
1693 break;
1694 }
1695 return false;
1696 } else {
1697 // Allow vectorization for all ARM devices, because Android assumes that
1698 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
1699 switch (type) {
1700 case DataType::Type::kBool:
1701 case DataType::Type::kUint8:
1702 case DataType::Type::kInt8:
1703 *restrictions |= kNoDiv;
1704 return TrySetVectorLength(type, 16);
1705 case DataType::Type::kUint16:
1706 case DataType::Type::kInt16:
1707 *restrictions |= kNoDiv;
1708 return TrySetVectorLength(type, 8);
1709 case DataType::Type::kInt32:
1710 *restrictions |= kNoDiv;
1711 return TrySetVectorLength(type, 4);
1712 case DataType::Type::kInt64:
1713 *restrictions |= kNoDiv | kNoMul;
1714 return TrySetVectorLength(type, 2);
1715 case DataType::Type::kFloat32:
1716 *restrictions |= kNoReduction;
1717 return TrySetVectorLength(type, 4);
1718 case DataType::Type::kFloat64:
1719 *restrictions |= kNoReduction;
1720 return TrySetVectorLength(type, 2);
1721 default:
1722 break;
1723 }
1724 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001725 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001726 case InstructionSet::kX86:
1727 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001728 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001729 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1730 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001731 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001732 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001733 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001734 *restrictions |= kNoMul |
1735 kNoDiv |
1736 kNoShift |
1737 kNoAbs |
1738 kNoSignedHAdd |
1739 kNoUnroundedHAdd |
1740 kNoSAD |
1741 kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001742 return TrySetVectorLength(type, 16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001743 case DataType::Type::kUint16:
Alex Light43f2f752019-12-04 17:48:45 +00001744 *restrictions |= kNoDiv |
1745 kNoAbs |
1746 kNoSignedHAdd |
1747 kNoUnroundedHAdd |
1748 kNoSAD |
1749 kNoDotProd;
Artem Serovc8150b52019-07-31 18:28:00 +01001750 return TrySetVectorLength(type, 8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001751 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001752 *restrictions |= kNoDiv |
1753 kNoAbs |
1754 kNoSignedHAdd |
1755 kNoUnroundedHAdd |
Alex Light43f2f752019-12-04 17:48:45 +00001756 kNoSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001757 return TrySetVectorLength(type, 8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001758 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001759 *restrictions |= kNoDiv | kNoSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001760 return TrySetVectorLength(type, 4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001761 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001762 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Artem Serovc8150b52019-07-31 18:28:00 +01001763 return TrySetVectorLength(type, 2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001764 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001765 *restrictions |= kNoReduction;
Artem Serovc8150b52019-07-31 18:28:00 +01001766 return TrySetVectorLength(type, 4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001767 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001768 *restrictions |= kNoReduction;
Artem Serovc8150b52019-07-31 18:28:00 +01001769 return TrySetVectorLength(type, 2);
Aart Bikf8f5a162017-02-06 15:35:29 -08001770 default:
1771 break;
1772 } // switch type
1773 }
1774 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001775 default:
1776 return false;
1777 } // switch instruction set
1778}
1779
Artem Serovc8150b52019-07-31 18:28:00 +01001780bool HLoopOptimization::TrySetVectorLengthImpl(uint32_t length) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001781 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1782 // First time set?
1783 if (vector_length_ == 0) {
1784 vector_length_ = length;
1785 }
1786 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1787 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1788 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1789 return vector_length_ == length;
1790}
1791
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001792void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001793 if (vector_map_->find(org) == vector_map_->end()) {
1794 // In scalar code, just use a self pass-through for scalar invariants
1795 // (viz. expression remains itself).
1796 if (vector_mode_ == kSequential) {
1797 vector_map_->Put(org, org);
1798 return;
1799 }
1800 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001801 HInstruction* vector = nullptr;
1802 auto it = vector_permanent_map_->find(org);
1803 if (it != vector_permanent_map_->end()) {
1804 vector = it->second; // reuse during unrolling
1805 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001806 // Generates ReplicateScalar( (optional_type_conv) org ).
1807 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001808 DataType::Type input_type = input->GetType();
1809 if (type != input_type && (type == DataType::Type::kInt64 ||
1810 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001811 input = Insert(vector_preheader_,
1812 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1813 }
1814 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001815 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001816 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
Artem Serov8ba4de12019-12-04 21:10:23 +00001817 if (IsInPredicatedVectorizationMode()) {
1818 HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1819 graph_->GetIntConstant(1),
1820 type,
1821 vector_length_,
1822 0u);
1823 vector_preheader_->InsertInstructionBefore(set_pred, vector);
1824 vector->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
1825 }
Aart Bik0148de42017-09-05 09:25:01 -07001826 }
1827 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001828 }
1829}
1830
1831void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1832 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001833 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001834 int64_t value = 0;
1835 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001836 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001837 if (org->IsPhi()) {
1838 Insert(vector_body_, subscript); // lacks layout placeholder
1839 }
1840 }
1841 vector_map_->Put(org, subscript);
1842 }
1843}
1844
1845void HLoopOptimization::GenerateVecMem(HInstruction* org,
1846 HInstruction* opa,
1847 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001848 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001849 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001850 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001851 HInstruction* vector = nullptr;
1852 if (vector_mode_ == kVector) {
1853 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001854 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001855 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001856 if (opb != nullptr) {
1857 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001858 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001859 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001860 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001861 vector = new (global_allocator_) HVecLoad(global_allocator_,
1862 base,
1863 opa,
1864 type,
1865 org->GetSideEffects(),
1866 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001867 is_string_char_at,
1868 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001869 }
Aart Bik38a3f212017-10-20 17:02:21 -07001870 // Known (forced/adjusted/original) alignment?
1871 if (vector_dynamic_peeling_candidate_ != nullptr) {
1872 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1873 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1874 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1875 vector->AsVecMemoryOperation()->SetAlignment( // forced
1876 Alignment(GetVectorSizeInBytes(), 0));
1877 }
1878 } else {
1879 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1880 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001881 }
1882 } else {
1883 // Scalar store or load.
1884 DCHECK(vector_mode_ == kSequential);
1885 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001886 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001887 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001888 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001889 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001890 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1891 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001892 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001893 }
1894 }
1895 vector_map_->Put(org, vector);
1896}
1897
Aart Bik0148de42017-09-05 09:25:01 -07001898void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1899 DCHECK(reductions_->find(phi) != reductions_->end());
1900 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1901 HInstruction* vector = nullptr;
1902 if (vector_mode_ == kSequential) {
1903 HPhi* new_phi = new (global_allocator_) HPhi(
1904 global_allocator_, kNoRegNumber, 0, phi->GetType());
1905 vector_header_->AddPhi(new_phi);
1906 vector = new_phi;
1907 } else {
1908 // Link vector reduction back to prior unrolled update, or a first phi.
1909 auto it = vector_permanent_map_->find(phi);
1910 if (it != vector_permanent_map_->end()) {
1911 vector = it->second;
1912 } else {
1913 HPhi* new_phi = new (global_allocator_) HPhi(
1914 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1915 vector_header_->AddPhi(new_phi);
1916 vector = new_phi;
1917 }
1918 }
1919 vector_map_->Put(phi, vector);
1920}
1921
1922void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1923 HInstruction* new_phi = vector_map_->Get(phi);
1924 HInstruction* new_init = reductions_->Get(phi);
1925 HInstruction* new_red = vector_map_->Get(reduction);
1926 // Link unrolled vector loop back to new phi.
1927 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1928 DCHECK(new_phi->IsVecOperation());
1929 }
1930 // Prepare the new initialization.
1931 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001932 // Generate a [initial, 0, .., 0] vector for add or
1933 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001934 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001935 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001936 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001937 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001938 if (kind == HVecReduce::ReductionKind::kSum) {
1939 new_init = Insert(vector_preheader_,
1940 new (global_allocator_) HVecSetScalars(global_allocator_,
1941 &new_init,
1942 type,
1943 vector_length,
1944 1,
1945 kNoDexPc));
1946 } else {
1947 new_init = Insert(vector_preheader_,
1948 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1949 new_init,
1950 type,
1951 vector_length,
1952 kNoDexPc));
1953 }
Artem Serov8ba4de12019-12-04 21:10:23 +00001954 if (IsInPredicatedVectorizationMode()) {
1955 HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1956 graph_->GetIntConstant(1),
1957 type,
1958 vector_length,
1959 0u);
1960 vector_preheader_->InsertInstructionBefore(set_pred, new_init);
1961 new_init->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
1962 }
Aart Bik0148de42017-09-05 09:25:01 -07001963 } else {
1964 new_init = ReduceAndExtractIfNeeded(new_init);
1965 }
1966 // Set the phi inputs.
1967 DCHECK(new_phi->IsPhi());
1968 new_phi->AsPhi()->AddInput(new_init);
1969 new_phi->AsPhi()->AddInput(new_red);
1970 // New feed value for next phi (safe mutation in iteration).
1971 reductions_->find(phi)->second = new_phi;
1972}
1973
1974HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1975 if (instruction->IsPhi()) {
1976 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001977 if (HVecOperation::ReturnsSIMDValue(input)) {
1978 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001979 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001980 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001981 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001982 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001983 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1984 // Generate a vector reduction and scalar extract
1985 // x = REDUCE( [x_1, .., x_n] )
1986 // y = x_1
1987 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001988 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001989 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001990 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1991 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001992 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001993 exit->InsertInstructionAfter(instruction, reduce);
Artem Serov8ba4de12019-12-04 21:10:23 +00001994
1995 if (IsInPredicatedVectorizationMode()) {
1996 HVecPredSetAll* set_pred = new (global_allocator_) HVecPredSetAll(global_allocator_,
1997 graph_->GetIntConstant(1),
1998 type,
1999 vector_length,
2000 0u);
2001 exit->InsertInstructionBefore(set_pred, reduce);
2002 reduce->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
2003 instruction->AsVecOperation()->SetMergingGoverningPredicate(set_pred);
2004 }
Aart Bik0148de42017-09-05 09:25:01 -07002005 }
2006 }
2007 return instruction;
2008}
2009
Aart Bikf8f5a162017-02-06 15:35:29 -08002010#define GENERATE_VEC(x, y) \
2011 if (vector_mode_ == kVector) { \
2012 vector = (x); \
2013 } else { \
2014 DCHECK(vector_mode_ == kSequential); \
2015 vector = (y); \
2016 } \
2017 break;
2018
2019void HLoopOptimization::GenerateVecOp(HInstruction* org,
2020 HInstruction* opa,
2021 HInstruction* opb,
Aart Bik3f08e9b2018-05-01 13:42:03 -07002022 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07002023 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08002024 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002025 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08002026 switch (org->GetKind()) {
2027 case HInstruction::kNeg:
2028 DCHECK(opb == nullptr);
2029 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002030 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
2031 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002032 case HInstruction::kNot:
2033 DCHECK(opb == nullptr);
2034 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002035 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2036 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002037 case HInstruction::kBooleanNot:
2038 DCHECK(opb == nullptr);
2039 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002040 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
2041 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002042 case HInstruction::kTypeConversion:
2043 DCHECK(opb == nullptr);
2044 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002045 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
2046 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002047 case HInstruction::kAdd:
2048 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002049 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2050 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002051 case HInstruction::kSub:
2052 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002053 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2054 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002055 case HInstruction::kMul:
2056 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002057 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2058 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002059 case HInstruction::kDiv:
2060 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002061 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2062 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002063 case HInstruction::kAnd:
2064 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002065 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2066 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002067 case HInstruction::kOr:
2068 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002069 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2070 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002071 case HInstruction::kXor:
2072 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002073 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2074 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002075 case HInstruction::kShl:
2076 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002077 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2078 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002079 case HInstruction::kShr:
2080 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002081 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2082 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002083 case HInstruction::kUShr:
2084 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002085 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2086 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08002087 case HInstruction::kAbs:
2088 DCHECK(opb == nullptr);
2089 GENERATE_VEC(
2090 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
2091 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002092 default:
2093 break;
2094 } // switch
2095 CHECK(vector != nullptr) << "Unsupported SIMD operator";
2096 vector_map_->Put(org, vector);
2097}
2098
2099#undef GENERATE_VEC
2100
2101//
Aart Bikf3e61ee2017-04-12 17:09:20 -07002102// Vectorization idioms.
2103//
2104
2105// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07002106// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2107// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07002108// Provided that the operands are promoted to a wider form to do the arithmetic and
2109// then cast back to narrower form, the idioms can be mapped into efficient SIMD
2110// implementation that operates directly in narrower form (plus one extra bit).
2111// TODO: current version recognizes implicit byte/short/char widening only;
2112// explicit widening from int to long could be added later.
2113bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2114 HInstruction* instruction,
2115 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002116 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07002117 uint64_t restrictions) {
2118 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07002119 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07002120 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07002121 if ((instruction->IsShr() ||
2122 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07002123 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07002124 // Test for (a + b + c) >> 1 for optional constant c.
2125 HInstruction* a = nullptr;
2126 HInstruction* b = nullptr;
2127 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002128 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07002129 // Accept c == 1 (rounded) or c == 0 (not rounded).
2130 bool is_rounded = false;
2131 if (c == 1) {
2132 is_rounded = true;
2133 } else if (c != 0) {
2134 return false;
2135 }
2136 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07002137 HInstruction* r = nullptr;
2138 HInstruction* s = nullptr;
2139 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002140 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002141 return false;
2142 }
2143 // Deal with vector restrictions.
Artem Serov8ba4de12019-12-04 21:10:23 +00002144 if ((is_unsigned && HasVectorRestrictions(restrictions, kNoUnsignedHAdd)) ||
2145 (!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
Aart Bikf3e61ee2017-04-12 17:09:20 -07002146 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2147 return false;
2148 }
2149 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2150 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002151 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002152 if (generate_code && vector_mode_ != kVector) { // de-idiom
2153 r = instruction->InputAt(0);
2154 s = instruction->InputAt(1);
2155 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002156 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2157 VectorizeUse(node, s, generate_code, type, restrictions)) {
2158 if (generate_code) {
2159 if (vector_mode_ == kVector) {
2160 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2161 global_allocator_,
2162 vector_map_->Get(r),
2163 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002164 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002165 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002166 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002167 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002168 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002169 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002170 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002171 }
2172 }
2173 return true;
2174 }
2175 }
2176 }
2177 return false;
2178}
2179
Aart Bikdbbac8f2017-09-01 13:06:08 -07002180// Method recognizes the following idiom:
2181// q += ABS(a - b) for signed operands a, b
2182// Provided that the operands have the same type or are promoted to a wider form.
2183// Since this may involve a vector length change, the idiom is handled by going directly
2184// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2185// TODO: unsigned SAD too?
2186bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2187 HInstruction* instruction,
2188 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002189 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002190 uint64_t restrictions) {
2191 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2192 // are done in the same precision (either int or long).
2193 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002194 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002195 return false;
2196 }
Artem Serove521eb02020-02-27 18:51:24 +00002197 HInstruction* acc = instruction->InputAt(0);
2198 HInstruction* abs = instruction->InputAt(1);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002199 HInstruction* a = nullptr;
2200 HInstruction* b = nullptr;
Artem Serove521eb02020-02-27 18:51:24 +00002201 if (abs->IsAbs() &&
2202 abs->GetType() == reduction_type &&
2203 IsSubConst2(graph_, abs->InputAt(0), /*out*/ &a, /*out*/ &b)) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002204 DCHECK(a != nullptr && b != nullptr);
2205 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002206 return false;
2207 }
2208 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2209 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002210 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002211 HInstruction* r = a;
2212 HInstruction* s = b;
2213 bool is_unsigned = false;
Artem Serovaaac0e32018-08-07 00:52:22 +01002214 DataType::Type sub_type = GetNarrowerType(a, b);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002215 if (reduction_type != sub_type &&
2216 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2217 return false;
2218 }
2219 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002220 if (!TrySetVectorType(sub_type, &restrictions) ||
2221 HasVectorRestrictions(restrictions, kNoSAD) ||
2222 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002223 return false;
2224 }
2225 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2226 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002227 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002228 if (generate_code && vector_mode_ != kVector) { // de-idiom
Artem Serove521eb02020-02-27 18:51:24 +00002229 r = s = abs->InputAt(0);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002230 }
Artem Serove521eb02020-02-27 18:51:24 +00002231 if (VectorizeUse(node, acc, generate_code, sub_type, restrictions) &&
Aart Bikdbbac8f2017-09-01 13:06:08 -07002232 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2233 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2234 if (generate_code) {
2235 if (vector_mode_ == kVector) {
2236 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2237 global_allocator_,
Artem Serove521eb02020-02-27 18:51:24 +00002238 vector_map_->Get(acc),
Aart Bikdbbac8f2017-09-01 13:06:08 -07002239 vector_map_->Get(r),
2240 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002241 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002242 GetOtherVL(reduction_type, sub_type, vector_length_),
2243 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002244 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2245 } else {
Artem Serove521eb02020-02-27 18:51:24 +00002246 // "GenerateVecOp()" must not be called more than once for each original loop body
2247 // instruction. As the SAD idiom processes both "current" instruction ("instruction")
2248 // and its ABS input in one go, we must check that for the scalar case the ABS instruction
2249 // has not yet been processed.
2250 if (vector_map_->find(abs) == vector_map_->end()) {
2251 GenerateVecOp(abs, vector_map_->Get(r), nullptr, reduction_type);
2252 }
2253 GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(abs), reduction_type);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002254 }
2255 }
2256 return true;
2257 }
2258 return false;
2259}
2260
Artem Serovaaac0e32018-08-07 00:52:22 +01002261// Method recognises the following dot product idiom:
2262// q += a * b for operands a, b whose type is narrower than the reduction one.
2263// Provided that the operands have the same type or are promoted to a wider form.
2264// Since this may involve a vector length change, the idiom is handled by going directly
2265// to a dot product node (rather than relying combining finer grained nodes later).
2266bool HLoopOptimization::VectorizeDotProdIdiom(LoopNode* node,
2267 HInstruction* instruction,
2268 bool generate_code,
2269 DataType::Type reduction_type,
2270 uint64_t restrictions) {
Alex Light43f2f752019-12-04 17:48:45 +00002271 if (!instruction->IsAdd() || reduction_type != DataType::Type::kInt32) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002272 return false;
2273 }
2274
Artem Serove521eb02020-02-27 18:51:24 +00002275 HInstruction* const acc = instruction->InputAt(0);
2276 HInstruction* const mul = instruction->InputAt(1);
2277 if (!mul->IsMul() || mul->GetType() != reduction_type) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002278 return false;
2279 }
2280
Artem Serove521eb02020-02-27 18:51:24 +00002281 HInstruction* const mul_left = mul->InputAt(0);
2282 HInstruction* const mul_right = mul->InputAt(1);
2283 HInstruction* r = mul_left;
2284 HInstruction* s = mul_right;
2285 DataType::Type op_type = GetNarrowerType(mul_left, mul_right);
Artem Serovaaac0e32018-08-07 00:52:22 +01002286 bool is_unsigned = false;
2287
Artem Serove521eb02020-02-27 18:51:24 +00002288 if (!IsNarrowerOperands(mul_left, mul_right, op_type, &r, &s, &is_unsigned)) {
Artem Serovaaac0e32018-08-07 00:52:22 +01002289 return false;
2290 }
2291 op_type = HVecOperation::ToProperType(op_type, is_unsigned);
2292
2293 if (!TrySetVectorType(op_type, &restrictions) ||
2294 HasVectorRestrictions(restrictions, kNoDotProd)) {
2295 return false;
2296 }
2297
2298 DCHECK(r != nullptr && s != nullptr);
2299 // Accept dot product idiom for vectorizable operands. Vectorized code uses the shorthand
2300 // idiomatic operation. Sequential code uses the original scalar expressions.
2301 if (generate_code && vector_mode_ != kVector) { // de-idiom
Artem Serove521eb02020-02-27 18:51:24 +00002302 r = mul_left;
2303 s = mul_right;
Artem Serovaaac0e32018-08-07 00:52:22 +01002304 }
Artem Serove521eb02020-02-27 18:51:24 +00002305 if (VectorizeUse(node, acc, generate_code, op_type, restrictions) &&
Artem Serovaaac0e32018-08-07 00:52:22 +01002306 VectorizeUse(node, r, generate_code, op_type, restrictions) &&
2307 VectorizeUse(node, s, generate_code, op_type, restrictions)) {
2308 if (generate_code) {
2309 if (vector_mode_ == kVector) {
2310 vector_map_->Put(instruction, new (global_allocator_) HVecDotProd(
2311 global_allocator_,
Artem Serove521eb02020-02-27 18:51:24 +00002312 vector_map_->Get(acc),
Artem Serovaaac0e32018-08-07 00:52:22 +01002313 vector_map_->Get(r),
2314 vector_map_->Get(s),
2315 reduction_type,
2316 is_unsigned,
2317 GetOtherVL(reduction_type, op_type, vector_length_),
2318 kNoDexPc));
2319 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2320 } else {
Artem Serove521eb02020-02-27 18:51:24 +00002321 // "GenerateVecOp()" must not be called more than once for each original loop body
2322 // instruction. As the DotProd idiom processes both "current" instruction ("instruction")
2323 // and its MUL input in one go, we must check that for the scalar case the MUL instruction
2324 // has not yet been processed.
2325 if (vector_map_->find(mul) == vector_map_->end()) {
2326 GenerateVecOp(mul, vector_map_->Get(r), vector_map_->Get(s), reduction_type);
2327 }
2328 GenerateVecOp(instruction, vector_map_->Get(acc), vector_map_->Get(mul), reduction_type);
Artem Serovaaac0e32018-08-07 00:52:22 +01002329 }
2330 }
2331 return true;
2332 }
2333 return false;
2334}
2335
Aart Bikf3e61ee2017-04-12 17:09:20 -07002336//
Aart Bik14a68b42017-06-08 14:06:58 -07002337// Vectorization heuristics.
2338//
2339
Aart Bik38a3f212017-10-20 17:02:21 -07002340Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2341 DataType::Type type,
2342 bool is_string_char_at,
2343 uint32_t peeling) {
2344 // Combine the alignment and hidden offset that is guaranteed by
2345 // the Android runtime with a known starting index adjusted as bytes.
2346 int64_t value = 0;
2347 if (IsInt64AndGet(offset, /*out*/ &value)) {
2348 uint32_t start_offset =
2349 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2350 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2351 }
2352 // Otherwise, the Android runtime guarantees at least natural alignment.
2353 return Alignment(DataType::Size(type), 0);
2354}
2355
Artem Serov55ab7e82020-04-27 21:02:28 +01002356void HLoopOptimization::SetAlignmentStrategy(const ScopedArenaVector<uint32_t>& peeling_votes,
Aart Bik38a3f212017-10-20 17:02:21 -07002357 const ArrayReference* peeling_candidate) {
2358 // Current heuristic: pick the best static loop peeling factor, if any,
2359 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2360 uint32_t max_vote = 0;
Artem Serov55ab7e82020-04-27 21:02:28 +01002361 for (size_t i = 0; i < peeling_votes.size(); i++) {
Aart Bik38a3f212017-10-20 17:02:21 -07002362 if (peeling_votes[i] > max_vote) {
2363 max_vote = peeling_votes[i];
2364 vector_static_peeling_factor_ = i;
2365 }
2366 }
2367 if (max_vote == 0) {
2368 vector_dynamic_peeling_candidate_ = peeling_candidate;
2369 }
2370}
2371
2372uint32_t HLoopOptimization::MaxNumberPeeled() {
2373 if (vector_dynamic_peeling_candidate_ != nullptr) {
2374 return vector_length_ - 1u; // worst-case
2375 }
2376 return vector_static_peeling_factor_; // known exactly
2377}
2378
Aart Bik14a68b42017-06-08 14:06:58 -07002379bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002380 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002381 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002382 // TODO: trip count is really unsigned entity, provided the guarding test
2383 // is satisfied; deal with this more carefully later
2384 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002385 if (vector_length_ == 0) {
2386 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002387 } else if (trip_count < 0) {
2388 return false; // guard against non-taken/large
2389 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002390 return false; // insufficient iterations
2391 }
2392 return true;
2393}
2394
Aart Bik14a68b42017-06-08 14:06:58 -07002395//
Aart Bikf8f5a162017-02-06 15:35:29 -08002396// Helpers.
2397//
2398
2399bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002400 // Start with empty phi induction.
2401 iset_->clear();
2402
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002403 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2404 // smart enough to follow strongly connected components (and it's probably not worth
2405 // it to make it so). See b/33775412.
2406 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2407 return false;
2408 }
Aart Bikb29f6842017-07-28 15:58:41 -07002409
2410 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002411 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2412 if (set != nullptr) {
2413 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002414 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002415 // each instruction is removable and, when restrict uses are requested, other than for phi,
2416 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002417 if (!i->IsInBlock()) {
2418 continue;
2419 } else if (!i->IsRemovable()) {
2420 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002421 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002422 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002423 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2424 if (set->find(use.GetUser()) == set->end()) {
2425 return false;
2426 }
2427 }
2428 }
Aart Bike3dedc52016-11-02 17:50:27 -07002429 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002430 }
Aart Bikcc42be02016-10-20 16:14:16 -07002431 return true;
2432 }
2433 return false;
2434}
2435
Aart Bikb29f6842017-07-28 15:58:41 -07002436bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002437 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002438 // Only unclassified phi cycles are candidates for reductions.
2439 if (induction_range_.IsClassified(phi)) {
2440 return false;
2441 }
2442 // Accept operations like x = x + .., provided that the phi and the reduction are
2443 // used exactly once inside the loop, and by each other.
2444 HInputsRef inputs = phi->GetInputs();
2445 if (inputs.size() == 2) {
2446 HInstruction* reduction = inputs[1];
2447 if (HasReductionFormat(reduction, phi)) {
2448 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002449 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002450 bool single_use_inside_loop =
2451 // Reduction update only used by phi.
2452 reduction->GetUses().HasExactlyOneElement() &&
2453 !reduction->HasEnvironmentUses() &&
2454 // Reduction update is only use of phi inside the loop.
2455 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2456 iset_->size() == 1;
2457 iset_->clear(); // leave the way you found it
2458 if (single_use_inside_loop) {
2459 // Link reduction back, and start recording feed value.
2460 reductions_->Put(reduction, phi);
2461 reductions_->Put(phi, phi->InputAt(0));
2462 return true;
2463 }
2464 }
2465 }
2466 return false;
2467}
2468
2469bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2470 // Start with empty phi induction and reductions.
2471 iset_->clear();
2472 reductions_->clear();
2473
2474 // Scan the phis to find the following (the induction structure has already
2475 // been optimized, so we don't need to worry about trivial cases):
2476 // (1) optional reductions in loop,
2477 // (2) the main induction, used in loop control.
2478 HPhi* phi = nullptr;
2479 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2480 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2481 continue;
2482 } else if (phi == nullptr) {
2483 // Found the first candidate for main induction.
2484 phi = it.Current()->AsPhi();
2485 } else {
2486 return false;
2487 }
2488 }
2489
2490 // Then test for a typical loopheader:
2491 // s: SuspendCheck
2492 // c: Condition(phi, bound)
2493 // i: If(c)
2494 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002495 HInstruction* s = block->GetFirstInstruction();
2496 if (s != nullptr && s->IsSuspendCheck()) {
2497 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002498 if (c != nullptr &&
2499 c->IsCondition() &&
2500 c->GetUses().HasExactlyOneElement() && // only used for termination
2501 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002502 HInstruction* i = c->GetNext();
2503 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2504 iset_->insert(c);
2505 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002506 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002507 return true;
2508 }
2509 }
2510 }
2511 }
2512 return false;
2513}
2514
2515bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002516 if (!block->GetPhis().IsEmpty()) {
2517 return false;
2518 }
2519 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2520 HInstruction* instruction = it.Current();
2521 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2522 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002523 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002524 }
2525 return true;
2526}
2527
2528bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2529 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002530 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002531 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2532 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2533 return true;
2534 }
Aart Bikcc42be02016-10-20 16:14:16 -07002535 }
2536 return false;
2537}
2538
Aart Bik482095d2016-10-10 15:39:10 -07002539bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002540 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002541 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002542 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002543 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002544 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2545 HInstruction* user = use.GetUser();
2546 if (iset_->find(user) == iset_->end()) { // not excluded?
2547 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002548 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002549 // If collect_loop_uses is set, simply keep adding those uses to the set.
2550 // Otherwise, reject uses inside the loop that were not already in the set.
2551 if (collect_loop_uses) {
2552 iset_->insert(user);
2553 continue;
2554 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002555 return false;
2556 }
2557 ++*use_count;
2558 }
2559 }
2560 return true;
2561}
2562
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002563bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2564 HInstruction* instruction,
2565 HBasicBlock* block) {
2566 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002567 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002568 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002569 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002570 const HUseList<HInstruction*>& uses = instruction->GetUses();
2571 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2572 HInstruction* user = it->GetUser();
2573 size_t index = it->GetIndex();
2574 ++it; // increment before replacing
2575 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002576 if (kIsDebugBuild) {
2577 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2578 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2579 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2580 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002581 user->ReplaceInput(replacement, index);
2582 induction_range_.Replace(user, instruction, replacement); // update induction
2583 }
2584 }
Aart Bikb29f6842017-07-28 15:58:41 -07002585 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002586 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2587 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2588 HEnvironment* user = it->GetUser();
2589 size_t index = it->GetIndex();
2590 ++it; // increment before replacing
2591 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002592 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002593 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002594 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2595 user->RemoveAsUserOfInput(index);
2596 user->SetRawEnvAt(index, replacement);
2597 replacement->AddEnvUseAt(user, index);
2598 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002599 }
2600 }
Aart Bik807868e2016-11-03 17:51:43 -07002601 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002602 }
Aart Bik807868e2016-11-03 17:51:43 -07002603 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002604}
2605
Aart Bikf8f5a162017-02-06 15:35:29 -08002606bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2607 HInstruction* instruction,
2608 HBasicBlock* block,
2609 bool collect_loop_uses) {
2610 // Assigning the last value is always successful if there are no uses.
2611 // Otherwise, it succeeds in a no early-exit loop by generating the
2612 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002613 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002614 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2615 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002616 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002617}
2618
Aart Bik6b69e0a2017-01-11 10:20:43 -08002619void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2620 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2621 HInstruction* instruction = i.Current();
2622 if (instruction->IsDeadAndRemovable()) {
2623 simplified_ = true;
2624 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2625 }
2626 }
2627}
2628
Aart Bik14a68b42017-06-08 14:06:58 -07002629bool HLoopOptimization::CanRemoveCycle() {
2630 for (HInstruction* i : *iset_) {
2631 // We can never remove instructions that have environment
2632 // uses when we compile 'debuggable'.
2633 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2634 return false;
2635 }
2636 // A deoptimization should never have an environment input removed.
2637 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2638 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2639 return false;
2640 }
2641 }
2642 }
2643 return true;
2644}
2645
Aart Bik281c6812016-08-26 11:31:48 -07002646} // namespace art