blob: c6e7560aed92809a160b4be8821a34456ec6552a [file] [log] [blame]
Aart Bik281c6812016-08-26 11:31:48 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "loop_optimization.h"
18
Aart Bikf8f5a162017-02-06 15:35:29 -080019#include "arch/arm/instruction_set_features_arm.h"
20#include "arch/arm64/instruction_set_features_arm64.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "arch/instruction_set.h"
Aart Bikf8f5a162017-02-06 15:35:29 -080022#include "arch/mips/instruction_set_features_mips.h"
23#include "arch/mips64/instruction_set_features_mips64.h"
24#include "arch/x86/instruction_set_features_x86.h"
25#include "arch/x86_64/instruction_set_features_x86_64.h"
Vladimir Markoa0431112018-06-25 09:32:54 +010026#include "driver/compiler_options.h"
Aart Bik96202302016-10-04 17:33:56 -070027#include "linear_order.h"
Aart Bik38a3f212017-10-20 17:02:21 -070028#include "mirror/array-inl.h"
29#include "mirror/string.h"
Aart Bik281c6812016-08-26 11:31:48 -070030
31namespace art {
32
Aart Bikf8f5a162017-02-06 15:35:29 -080033// Enables vectorization (SIMDization) in the loop optimizer.
34static constexpr bool kEnableVectorization = true;
35
Aart Bik38a3f212017-10-20 17:02:21 -070036//
37// Static helpers.
38//
39
40// Base alignment for arrays/strings guaranteed by the Android runtime.
41static uint32_t BaseAlignment() {
42 return kObjectAlignment;
43}
44
45// Hidden offset for arrays/strings guaranteed by the Android runtime.
46static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
47 return is_string_char_at
48 ? mirror::String::ValueOffset().Uint32Value()
49 : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
50}
51
Aart Bik9abf8942016-10-14 09:49:42 -070052// Remove the instruction from the graph. A bit more elaborate than the usual
53// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070054static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070055 instruction->RemoveAsUserOfAllInputs();
56 instruction->RemoveEnvironmentUsers();
57 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010058 RemoveEnvironmentUses(instruction);
59 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070060}
61
Aart Bik807868e2016-11-03 17:51:43 -070062// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070063static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
64 if (block->GetPredecessors().size() == 1 &&
65 block->GetSuccessors().size() == 1 &&
66 block->IsSingleGoto()) {
67 *succ = block->GetSingleSuccessor();
68 return true;
69 }
70 return false;
71}
72
Aart Bik807868e2016-11-03 17:51:43 -070073// Detect an early exit loop.
74static bool IsEarlyExit(HLoopInformation* loop_info) {
75 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
76 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
77 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
78 if (!loop_info->Contains(*successor)) {
79 return true;
80 }
81 }
82 }
83 return false;
84}
85
Aart Bik68ca7022017-09-26 16:44:23 -070086// Forward declaration.
87static bool IsZeroExtensionAndGet(HInstruction* instruction,
88 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070089 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -070090
Aart Bikdf011c32017-09-28 12:53:04 -070091// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -070092// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070093static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010094 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070095 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070096 // Accept any already wider constant that would be handled properly by sign
97 // extension when represented in the *width* of the given narrower data type
Aart Bik4d1a9d42017-10-19 14:40:55 -070098 // (the fact that Uint8/Uint16 normally zero extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -070099 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700100 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700101 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100102 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100103 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700104 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700105 *operand = instruction;
106 return true;
107 }
108 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100109 case DataType::Type::kUint16:
110 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700111 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700112 *operand = instruction;
113 return true;
114 }
115 return false;
116 default:
117 return false;
118 }
119 }
Aart Bikdf011c32017-09-28 12:53:04 -0700120 // An implicit widening conversion of any signed expression sign-extends.
121 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700122 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100123 case DataType::Type::kInt8:
124 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700125 *operand = instruction;
126 return true;
127 default:
128 return false;
129 }
130 }
Aart Bikdf011c32017-09-28 12:53:04 -0700131 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700132 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700133 HInstruction* conv = instruction->InputAt(0);
134 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700135 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700136 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700137 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700138 if (type == from && (from == DataType::Type::kInt8 ||
139 from == DataType::Type::kInt16 ||
140 from == DataType::Type::kInt32)) {
141 *operand = conv;
142 return true;
143 }
144 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700145 case DataType::Type::kInt16:
146 return type == DataType::Type::kUint16 &&
147 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700148 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700149 default:
150 return false;
151 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700152 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700153 return false;
154}
155
Aart Bikdf011c32017-09-28 12:53:04 -0700156// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700157// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700158static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100159 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700160 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700161 // Accept any already wider constant that would be handled properly by zero
162 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700163 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700164 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700165 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700166 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100167 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100168 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700169 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700170 *operand = instruction;
171 return true;
172 }
173 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100174 case DataType::Type::kUint16:
175 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700176 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700177 *operand = instruction;
178 return true;
179 }
180 return false;
181 default:
182 return false;
183 }
184 }
Aart Bikdf011c32017-09-28 12:53:04 -0700185 // An implicit widening conversion of any unsigned expression zero-extends.
186 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100187 switch (type) {
188 case DataType::Type::kUint8:
189 case DataType::Type::kUint16:
190 *operand = instruction;
191 return true;
192 default:
193 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700194 }
195 }
Aart Bikdf011c32017-09-28 12:53:04 -0700196 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700197 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700198 HInstruction* conv = instruction->InputAt(0);
199 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700200 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700201 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700202 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700203 if (type == from && from == DataType::Type::kUint16) {
204 *operand = conv;
205 return true;
206 }
207 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700208 case DataType::Type::kUint16:
209 return type == DataType::Type::kInt16 &&
210 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700211 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700212 default:
213 return false;
214 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700215 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700216 return false;
217}
218
Aart Bik304c8a52017-05-23 11:01:13 -0700219// Detect situations with same-extension narrower operands.
220// Returns true on success and sets is_unsigned accordingly.
221static bool IsNarrowerOperands(HInstruction* a,
222 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100223 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700224 /*out*/ HInstruction** r,
225 /*out*/ HInstruction** s,
226 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000227 DCHECK(a != nullptr && b != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700228 // Look for a matching sign extension.
229 DataType::Type stype = HVecOperation::ToSignedType(type);
230 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700231 *is_unsigned = false;
232 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700233 }
234 // Look for a matching zero extension.
235 DataType::Type utype = HVecOperation::ToUnsignedType(type);
236 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700237 *is_unsigned = true;
238 return true;
239 }
240 return false;
241}
242
243// As above, single operand.
244static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100245 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700246 /*out*/ HInstruction** r,
247 /*out*/ bool* is_unsigned) {
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000248 DCHECK(a != nullptr);
Aart Bik4d1a9d42017-10-19 14:40:55 -0700249 // Look for a matching sign extension.
250 DataType::Type stype = HVecOperation::ToSignedType(type);
251 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700252 *is_unsigned = false;
253 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700254 }
255 // Look for a matching zero extension.
256 DataType::Type utype = HVecOperation::ToUnsignedType(type);
257 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700258 *is_unsigned = true;
259 return true;
260 }
261 return false;
262}
263
Aart Bikdbbac8f2017-09-01 13:06:08 -0700264// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700265static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100266 DCHECK(DataType::IsIntegralType(other_type));
267 DCHECK(DataType::IsIntegralType(vector_type));
268 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
269 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700270}
271
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000272// Detect up to two added operands a and b and an acccumulated constant c.
273static bool IsAddConst(HInstruction* instruction,
274 /*out*/ HInstruction** a,
275 /*out*/ HInstruction** b,
276 /*out*/ int64_t* c,
277 int32_t depth = 8) { // don't search too deep
Aart Bik5f805002017-05-16 16:42:41 -0700278 int64_t value = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000279 // Enter add/sub while still within reasonable depth.
280 if (depth > 0) {
281 if (instruction->IsAdd()) {
282 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1) &&
283 IsAddConst(instruction->InputAt(1), a, b, c, depth - 1);
284 } else if (instruction->IsSub() &&
285 IsInt64AndGet(instruction->InputAt(1), &value)) {
286 *c -= value;
287 return IsAddConst(instruction->InputAt(0), a, b, c, depth - 1);
288 }
289 }
290 // Otherwise, deal with leaf nodes.
Aart Bik5f805002017-05-16 16:42:41 -0700291 if (IsInt64AndGet(instruction, &value)) {
292 *c += value;
293 return true;
Aart Bik5f805002017-05-16 16:42:41 -0700294 } else if (*a == nullptr) {
295 *a = instruction;
296 return true;
297 } else if (*b == nullptr) {
298 *b = instruction;
299 return true;
300 }
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000301 return false; // too many operands
Aart Bik5f805002017-05-16 16:42:41 -0700302}
303
Nicolas Geoffraya3e23262018-03-28 11:15:12 +0000304// Detect a + b + c with optional constant c.
305static bool IsAddConst2(HGraph* graph,
306 HInstruction* instruction,
307 /*out*/ HInstruction** a,
308 /*out*/ HInstruction** b,
309 /*out*/ int64_t* c) {
310 if (IsAddConst(instruction, a, b, c) && *a != nullptr) {
311 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() ||
Shalini Salomi Bodapati81d15be2019-05-30 11:00:42 +0530356 #if defined(ART_ENABLE_CODEGEN_x86) || defined(ART_ENABLE_CODEGEN_x86_64)
357 reduction->IsVecAvxSub() || reduction->IsVecAvxAdd() ||
358 #endif
Artem Serovaaac0e32018-08-07 00:52:22 +0100359 reduction->IsVecSADAccumulate() ||
360 reduction->IsVecDotProd()) {
Aart Bik0148de42017-09-05 09:25:01 -0700361 return HVecReduce::kSum;
Aart Bik0148de42017-09-05 09:25:01 -0700362 }
Aart Bik38a3f212017-10-20 17:02:21 -0700363 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700364 UNREACHABLE();
365}
366
Aart Bikf8f5a162017-02-06 15:35:29 -0800367// Test vector restrictions.
368static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
369 return (restrictions & tested) != 0;
370}
371
Aart Bikf3e61ee2017-04-12 17:09:20 -0700372// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800373static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
374 DCHECK(block != nullptr);
375 DCHECK(instruction != nullptr);
376 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
377 return instruction;
378}
379
Artem Serov21c7e6f2017-07-27 16:04:42 +0100380// Check that instructions from the induction sets are fully removed: have no uses
381// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100382static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100383 for (HInstruction* instr : *iset) {
384 if (instr->GetBlock() != nullptr ||
385 !instr->GetUses().empty() ||
386 !instr->GetEnvUses().empty() ||
387 HasEnvironmentUsedByOthers(instr)) {
388 return false;
389 }
390 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100391 return true;
392}
393
Artem Serov72411e62017-10-19 16:18:07 +0100394// Tries to statically evaluate condition of the specified "HIf" for other condition checks.
395static void TryToEvaluateIfCondition(HIf* instruction, HGraph* graph) {
396 HInstruction* cond = instruction->InputAt(0);
397
398 // If a condition 'cond' is evaluated in an HIf instruction then in the successors of the
399 // IF_BLOCK we statically know the value of the condition 'cond' (TRUE in TRUE_SUCC, FALSE in
400 // FALSE_SUCC). Using that we can replace another evaluation (use) EVAL of the same 'cond'
401 // with TRUE value (FALSE value) if every path from the ENTRY_BLOCK to EVAL_BLOCK contains the
402 // edge HIF_BLOCK->TRUE_SUCC (HIF_BLOCK->FALSE_SUCC).
403 // if (cond) { if(cond) {
404 // if (cond) {} if (1) {}
405 // } else { =======> } else {
406 // if (cond) {} if (0) {}
407 // } }
408 if (!cond->IsConstant()) {
409 HBasicBlock* true_succ = instruction->IfTrueSuccessor();
410 HBasicBlock* false_succ = instruction->IfFalseSuccessor();
411
412 DCHECK_EQ(true_succ->GetPredecessors().size(), 1u);
413 DCHECK_EQ(false_succ->GetPredecessors().size(), 1u);
414
415 const HUseList<HInstruction*>& uses = cond->GetUses();
416 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
417 HInstruction* user = it->GetUser();
418 size_t index = it->GetIndex();
419 HBasicBlock* user_block = user->GetBlock();
420 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
421 ++it;
422 if (true_succ->Dominates(user_block)) {
423 user->ReplaceInput(graph->GetIntConstant(1), index);
424 } else if (false_succ->Dominates(user_block)) {
425 user->ReplaceInput(graph->GetIntConstant(0), index);
426 }
427 }
428 }
429}
430
Artem Serov18ba1da2018-05-16 19:06:32 +0100431// Peel the first 'count' iterations of the loop.
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100432static void PeelByCount(HLoopInformation* loop_info,
433 int count,
434 InductionVarRange* induction_range) {
Artem Serov18ba1da2018-05-16 19:06:32 +0100435 for (int i = 0; i < count; i++) {
436 // Perform peeling.
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100437 PeelUnrollSimpleHelper helper(loop_info, induction_range);
Artem Serov18ba1da2018-05-16 19:06:32 +0100438 helper.DoPeeling();
439 }
440}
441
Artem Serovaaac0e32018-08-07 00:52:22 +0100442// Returns the narrower type out of instructions a and b types.
443static DataType::Type GetNarrowerType(HInstruction* a, HInstruction* b) {
444 DataType::Type type = a->GetType();
445 if (DataType::Size(b->GetType()) < DataType::Size(type)) {
446 type = b->GetType();
447 }
448 if (a->IsTypeConversion() &&
449 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(type)) {
450 type = a->InputAt(0)->GetType();
451 }
452 if (b->IsTypeConversion() &&
453 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(type)) {
454 type = b->InputAt(0)->GetType();
455 }
456 return type;
457}
458
Aart Bik281c6812016-08-26 11:31:48 -0700459//
Aart Bikb29f6842017-07-28 15:58:41 -0700460// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700461//
462
463HLoopOptimization::HLoopOptimization(HGraph* graph,
Vladimir Markoa0431112018-06-25 09:32:54 +0100464 const CompilerOptions* compiler_options,
Aart Bikb92cc332017-09-06 15:53:17 -0700465 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800466 OptimizingCompilerStats* stats,
467 const char* name)
468 : HOptimization(graph, name, stats),
Vladimir Markoa0431112018-06-25 09:32:54 +0100469 compiler_options_(compiler_options),
Aart Bik281c6812016-08-26 11:31:48 -0700470 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700471 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100472 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700473 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700474 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700475 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700476 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800477 simplified_(false),
478 vector_length_(0),
479 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700480 vector_static_peeling_factor_(0),
481 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700482 vector_runtime_test_a_(nullptr),
483 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700484 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100485 vector_permanent_map_(nullptr),
486 vector_mode_(kSequential),
487 vector_preheader_(nullptr),
488 vector_header_(nullptr),
489 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100490 vector_index_(nullptr),
Vladimir Markoa0431112018-06-25 09:32:54 +0100491 arch_loop_helper_(ArchNoOptsLoopHelper::Create(compiler_options_ != nullptr
492 ? compiler_options_->GetInstructionSet()
Artem Serov121f2032017-10-23 19:19:06 +0100493 : InstructionSet::kNone,
494 global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700495}
496
Aart Bik24773202018-04-26 10:28:51 -0700497bool HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800498 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700499 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800500 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik24773202018-04-26 10:28:51 -0700501 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700502 }
503
Vladimir Markoca6fff82017-10-03 14:49:14 +0100504 // Phase-local allocator.
505 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700506 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100507
Aart Bik96202302016-10-04 17:33:56 -0700508 // Perform loop optimizations.
Aart Bik24773202018-04-26 10:28:51 -0700509 bool didLoopOpt = LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800510 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800511 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800512 }
513
Aart Bik96202302016-10-04 17:33:56 -0700514 // Detach.
515 loop_allocator_ = nullptr;
516 last_loop_ = top_loop_ = nullptr;
Aart Bik24773202018-04-26 10:28:51 -0700517
518 return didLoopOpt;
Aart Bik96202302016-10-04 17:33:56 -0700519}
520
Aart Bikb29f6842017-07-28 15:58:41 -0700521//
522// Loop setup and traversal.
523//
524
Aart Bik24773202018-04-26 10:28:51 -0700525bool HLoopOptimization::LocalRun() {
526 bool didLoopOpt = false;
Aart Bik96202302016-10-04 17:33:56 -0700527 // Build the linear order using the phase-local allocator. This step enables building
528 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100529 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
530 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700531
Aart Bik281c6812016-08-26 11:31:48 -0700532 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700533 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700534 if (block->IsLoopHeader()) {
535 AddLoop(block->GetLoopInformation());
536 }
537 }
Aart Bik96202302016-10-04 17:33:56 -0700538
Aart Bik8c4a8542016-10-06 11:36:57 -0700539 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800540 // temporary data structures using the phase-local allocator. All new HIR
541 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700542 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100543 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
544 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700545 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100546 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
547 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800548 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100549 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700550 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800551 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700552 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700553 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800554 vector_refs_ = &refs;
555 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700556 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800557 // Traverse.
Aart Bik24773202018-04-26 10:28:51 -0700558 didLoopOpt = TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800559 // Detach.
560 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700561 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800562 vector_refs_ = nullptr;
563 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700564 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700565 }
Aart Bik24773202018-04-26 10:28:51 -0700566 return didLoopOpt;
Aart Bik281c6812016-08-26 11:31:48 -0700567}
568
569void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
570 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800571 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700572 if (last_loop_ == nullptr) {
573 // First loop.
574 DCHECK(top_loop_ == nullptr);
575 last_loop_ = top_loop_ = node;
576 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
577 // Inner loop.
578 node->outer = last_loop_;
579 DCHECK(last_loop_->inner == nullptr);
580 last_loop_ = last_loop_->inner = node;
581 } else {
582 // Subsequent loop.
583 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
584 last_loop_ = last_loop_->outer;
585 }
586 node->outer = last_loop_->outer;
587 node->previous = last_loop_;
588 DCHECK(last_loop_->next == nullptr);
589 last_loop_ = last_loop_->next = node;
590 }
591}
592
593void HLoopOptimization::RemoveLoop(LoopNode* node) {
594 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700595 DCHECK(node->inner == nullptr);
596 if (node->previous != nullptr) {
597 // Within sequence.
598 node->previous->next = node->next;
599 if (node->next != nullptr) {
600 node->next->previous = node->previous;
601 }
602 } else {
603 // First of sequence.
604 if (node->outer != nullptr) {
605 node->outer->inner = node->next;
606 } else {
607 top_loop_ = node->next;
608 }
609 if (node->next != nullptr) {
610 node->next->outer = node->outer;
611 node->next->previous = nullptr;
612 }
613 }
Aart Bik281c6812016-08-26 11:31:48 -0700614}
615
Aart Bikb29f6842017-07-28 15:58:41 -0700616bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
617 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700618 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700619 // Visit inner loops first. Recompute induction information for this
620 // loop if the induction of any inner loop has changed.
621 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700622 induction_range_.ReVisit(node->loop_info);
Aart Bika8360cd2018-05-02 16:07:51 -0700623 changed = true;
Aart Bik482095d2016-10-10 15:39:10 -0700624 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800625 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800626 // Note that since each simplification consists of eliminating code (without
627 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800628 do {
629 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800630 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800631 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700632 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800633 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800634 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700635 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700636 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700637 }
Aart Bik281c6812016-08-26 11:31:48 -0700638 }
Aart Bikb29f6842017-07-28 15:58:41 -0700639 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700640}
641
Aart Bikf8f5a162017-02-06 15:35:29 -0800642//
643// Optimization.
644//
645
Aart Bik281c6812016-08-26 11:31:48 -0700646void HLoopOptimization::SimplifyInduction(LoopNode* node) {
647 HBasicBlock* header = node->loop_info->GetHeader();
648 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700649 // Scan the phis in the header to find opportunities to simplify an induction
650 // cycle that is only used outside the loop. Replace these uses, if any, with
651 // the last value and remove the induction cycle.
652 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
653 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700654 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
655 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800656 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
657 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700658 // Note that it's ok to have replaced uses after the loop with the last value, without
659 // being able to remove the cycle. Environment uses (which are the reason we may not be
660 // able to remove the cycle) within the loop will still hold the right value. We must
661 // have tried first, however, to replace outside uses.
662 if (CanRemoveCycle()) {
663 simplified_ = true;
664 for (HInstruction* i : *iset_) {
665 RemoveFromCycle(i);
666 }
667 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700668 }
Aart Bik482095d2016-10-10 15:39:10 -0700669 }
670 }
671}
672
673void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800674 // Iterate over all basic blocks in the loop-body.
675 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
676 HBasicBlock* block = it.Current();
677 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800678 RemoveDeadInstructions(block->GetPhis());
679 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800680 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800681 if (block->GetPredecessors().size() == 1 &&
682 block->GetSuccessors().size() == 1 &&
683 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800684 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800685 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800686 } else if (block->GetSuccessors().size() == 2) {
687 // Trivial if block can be bypassed to either branch.
688 HBasicBlock* succ0 = block->GetSuccessors()[0];
689 HBasicBlock* succ1 = block->GetSuccessors()[1];
690 HBasicBlock* meet0 = nullptr;
691 HBasicBlock* meet1 = nullptr;
692 if (succ0 != succ1 &&
693 IsGotoBlock(succ0, &meet0) &&
694 IsGotoBlock(succ1, &meet1) &&
695 meet0 == meet1 && // meets again
696 meet0 != block && // no self-loop
697 meet0->GetPhis().IsEmpty()) { // not used for merging
698 simplified_ = true;
699 succ0->DisconnectAndDelete();
700 if (block->Dominates(meet0)) {
701 block->RemoveDominatedBlock(meet0);
702 succ1->AddDominatedBlock(meet0);
703 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700704 }
Aart Bik482095d2016-10-10 15:39:10 -0700705 }
Aart Bik281c6812016-08-26 11:31:48 -0700706 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800707 }
Aart Bik281c6812016-08-26 11:31:48 -0700708}
709
Artem Serov121f2032017-10-23 19:19:06 +0100710bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700711 HBasicBlock* header = node->loop_info->GetHeader();
712 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700713 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800714 int64_t trip_count = 0;
715 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700716 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700717 }
Aart Bik281c6812016-08-26 11:31:48 -0700718 // Ensure there is only a single loop-body (besides the header).
719 HBasicBlock* body = nullptr;
720 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
721 if (it.Current() != header) {
722 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700723 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700724 }
725 body = it.Current();
726 }
727 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700728 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700729 // Ensure there is only a single exit point.
730 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700731 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700732 }
733 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
734 ? header->GetSuccessors()[1]
735 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700736 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700737 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700738 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700739 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800740 // Detect either an empty loop (no side effects other than plain iteration) or
741 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
742 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700743 HPhi* main_phi = nullptr;
744 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800745 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700746 if (reductions_->empty() && // TODO: possible with some effort
747 (is_empty || trip_count == 1) &&
748 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800749 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800750 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700751 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800752 preheader->MergeInstructionsWith(body);
753 }
754 body->DisconnectAndDelete();
755 exit->RemovePredecessor(header);
756 header->RemoveSuccessor(exit);
757 header->RemoveDominatedBlock(exit);
758 header->DisconnectAndDelete();
759 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800760 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800761 preheader->AddDominatedBlock(exit);
762 exit->SetDominator(preheader);
763 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700764 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800765 }
766 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800767 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700768 if (kEnableVectorization &&
769 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700770 ShouldVectorize(node, body, trip_count) &&
771 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
772 Vectorize(node, body, exit, trip_count);
773 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700774 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700775 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800776 }
Aart Bikb29f6842017-07-28 15:58:41 -0700777 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800778}
779
Artem Serov121f2032017-10-23 19:19:06 +0100780bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Artem Serov0e329082018-06-12 10:23:27 +0100781 return TryOptimizeInnerLoopFinite(node) || TryPeelingAndUnrolling(node);
Artem Serov121f2032017-10-23 19:19:06 +0100782}
783
Artem Serov121f2032017-10-23 19:19:06 +0100784
Artem Serov121f2032017-10-23 19:19:06 +0100785
786//
Artem Serov0e329082018-06-12 10:23:27 +0100787// Scalar loop peeling and unrolling: generic part methods.
Artem Serov121f2032017-10-23 19:19:06 +0100788//
789
Artem Serov0e329082018-06-12 10:23:27 +0100790bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
791 bool generate_code) {
792 if (analysis_info->GetNumberOfExits() > 1) {
Artem Serov121f2032017-10-23 19:19:06 +0100793 return false;
794 }
795
Artem Serov0e329082018-06-12 10:23:27 +0100796 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
797 if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
Artem Serov121f2032017-10-23 19:19:06 +0100798 return false;
799 }
800
Artem Serov0e329082018-06-12 10:23:27 +0100801 if (generate_code) {
802 // TODO: support other unrolling factors.
803 DCHECK_EQ(unrolling_factor, 2u);
804
805 // Perform unrolling.
806 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100807 PeelUnrollSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100808 helper.DoUnrolling();
809
810 // Remove the redundant loop check after unrolling.
811 HIf* copy_hif =
812 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
813 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
814 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
Artem Serov121f2032017-10-23 19:19:06 +0100815 }
Artem Serov121f2032017-10-23 19:19:06 +0100816 return true;
817}
818
Artem Serov0e329082018-06-12 10:23:27 +0100819bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
820 bool generate_code) {
821 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov72411e62017-10-19 16:18:07 +0100822 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
823 return false;
824 }
825
Artem Serov0e329082018-06-12 10:23:27 +0100826 if (analysis_info->GetNumberOfInvariantExits() == 0) {
Artem Serov72411e62017-10-19 16:18:07 +0100827 return false;
828 }
829
Artem Serov0e329082018-06-12 10:23:27 +0100830 if (generate_code) {
831 // Perform peeling.
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100832 PeelUnrollSimpleHelper helper(loop_info, &induction_range_);
Artem Serov0e329082018-06-12 10:23:27 +0100833 helper.DoPeeling();
Artem Serov72411e62017-10-19 16:18:07 +0100834
Artem Serov0e329082018-06-12 10:23:27 +0100835 // Statically evaluate loop check after peeling for loop invariant condition.
836 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
837 for (auto entry : *hir_map) {
838 HInstruction* copy = entry.second;
839 if (copy->IsIf()) {
840 TryToEvaluateIfCondition(copy->AsIf(), graph_);
841 }
Artem Serov72411e62017-10-19 16:18:07 +0100842 }
843 }
844
845 return true;
846}
847
Artem Serov18ba1da2018-05-16 19:06:32 +0100848bool HLoopOptimization::TryFullUnrolling(LoopAnalysisInfo* analysis_info, bool generate_code) {
849 // Fully unroll loops with a known and small trip count.
850 int64_t trip_count = analysis_info->GetTripCount();
851 if (!arch_loop_helper_->IsLoopPeelingEnabled() ||
852 trip_count == LoopAnalysisInfo::kUnknownTripCount ||
853 !arch_loop_helper_->IsFullUnrollingBeneficial(analysis_info)) {
854 return false;
855 }
856
857 if (generate_code) {
858 // Peeling of the N first iterations (where N equals to the trip count) will effectively
859 // eliminate the loop: after peeling we will have N sequential iterations copied into the loop
860 // preheader and the original loop. The trip count of this loop will be 0 as the sequential
861 // iterations are executed first and there are exactly N of them. Thus we can statically
862 // evaluate the loop exit condition to 'false' and fully eliminate it.
863 //
864 // Here is an example of full unrolling of a loop with a trip count 2:
865 //
866 // loop_cond_1
867 // loop_body_1 <- First iteration.
868 // |
869 // \ v
870 // ==\ loop_cond_2
871 // ==/ loop_body_2 <- Second iteration.
872 // / |
873 // <- v <-
874 // loop_cond \ loop_cond \ <- This cond is always false.
875 // loop_body _/ loop_body _/
876 //
877 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Nicolas Geoffray256c94b2019-04-29 10:55:09 +0100878 PeelByCount(loop_info, trip_count, &induction_range_);
Artem Serov18ba1da2018-05-16 19:06:32 +0100879 HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
880 int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
881 loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
882 }
883
884 return true;
885}
886
Artem Serov0e329082018-06-12 10:23:27 +0100887bool HLoopOptimization::TryPeelingAndUnrolling(LoopNode* node) {
888 // Don't run peeling/unrolling if compiler_options_ is nullptr (i.e., running under tests)
889 // as InstructionSet is needed.
890 if (compiler_options_ == nullptr) {
891 return false;
892 }
893
894 HLoopInformation* loop_info = node->loop_info;
895 int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
896 LoopAnalysisInfo analysis_info(loop_info);
897 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
898
899 if (analysis_info.HasInstructionsPreventingScalarOpts() ||
900 arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
901 return false;
902 }
903
Artem Serov18ba1da2018-05-16 19:06:32 +0100904 if (!TryFullUnrolling(&analysis_info, /*generate_code*/ false) &&
905 !TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
Artem Serov0e329082018-06-12 10:23:27 +0100906 !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false)) {
907 return false;
908 }
909
910 // Run 'IsLoopClonable' the last as it might be time-consuming.
911 if (!PeelUnrollHelper::IsLoopClonable(loop_info)) {
912 return false;
913 }
914
Artem Serov18ba1da2018-05-16 19:06:32 +0100915 return TryFullUnrolling(&analysis_info) ||
916 TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
Artem Serov0e329082018-06-12 10:23:27 +0100917 TryUnrollingForBranchPenaltyReduction(&analysis_info);
918}
919
Aart Bikf8f5a162017-02-06 15:35:29 -0800920//
921// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
922// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
923// Intel Press, June, 2004 (http://www.aartbik.com/).
924//
925
Aart Bik14a68b42017-06-08 14:06:58 -0700926bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800927 // Reset vector bookkeeping.
928 vector_length_ = 0;
929 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700930 vector_static_peeling_factor_ = 0;
931 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800932 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800933 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800934
935 // Phis in the loop-body prevent vectorization.
936 if (!block->GetPhis().IsEmpty()) {
937 return false;
938 }
939
940 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
941 // occurrence, which allows passing down attributes down the use tree.
942 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
943 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
944 return false; // failure to vectorize a left-hand-side
945 }
946 }
947
Aart Bik38a3f212017-10-20 17:02:21 -0700948 // Prepare alignment analysis:
949 // (1) find desired alignment (SIMD vector size in bytes).
950 // (2) initialize static loop peeling votes (peeling factor that will
951 // make one particular reference aligned), never to exceed (1).
952 // (3) variable to record how many references share same alignment.
953 // (4) variable to record suitable candidate for dynamic loop peeling.
954 uint32_t desired_alignment = GetVectorSizeInBytes();
955 DCHECK_LE(desired_alignment, 16u);
956 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
957 uint32_t max_num_same_alignment = 0;
958 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800959
960 // Data dependence analysis. Find each pair of references with same type, where
961 // at least one is a write. Each such pair denotes a possible data dependence.
962 // This analysis exploits the property that differently typed arrays cannot be
963 // aliased, as well as the property that references either point to the same
964 // array or to two completely disjoint arrays, i.e., no partial aliasing.
965 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700966 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800967 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700968 uint32_t num_same_alignment = 0;
969 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800970 for (auto j = i; ++j != vector_refs_->end(); ) {
971 if (i->type == j->type && (i->lhs || j->lhs)) {
972 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
973 HInstruction* a = i->base;
974 HInstruction* b = j->base;
975 HInstruction* x = i->offset;
976 HInstruction* y = j->offset;
977 if (a == b) {
978 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
979 // Conservatively assume a loop-carried data dependence otherwise, and reject.
980 if (x != y) {
981 return false;
982 }
Aart Bik38a3f212017-10-20 17:02:21 -0700983 // Count the number of references that have the same alignment (since
984 // base and offset are the same) and where at least one is a write, so
985 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
986 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800987 } else {
988 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
989 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
990 // generating an explicit a != b disambiguation runtime test on the two references.
991 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700992 // To avoid excessive overhead, we only accept one a != b test.
993 if (vector_runtime_test_a_ == nullptr) {
994 // First test found.
995 vector_runtime_test_a_ = a;
996 vector_runtime_test_b_ = b;
997 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
998 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
999 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -08001000 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001001 }
1002 }
1003 }
1004 }
Aart Bik38a3f212017-10-20 17:02:21 -07001005 // Update information for finding suitable alignment strategy:
1006 // (1) update votes for static loop peeling,
1007 // (2) update suitable candidate for dynamic loop peeling.
1008 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1009 if (alignment.Base() >= desired_alignment) {
1010 // If the array/string object has a known, sufficient alignment, use the
1011 // initial offset to compute the static loop peeling vote (this always
1012 // works, since elements have natural alignment).
1013 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1014 uint32_t vote = (offset == 0)
1015 ? 0
1016 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1017 DCHECK_LT(vote, 16u);
1018 ++peeling_votes[vote];
1019 } else if (BaseAlignment() >= desired_alignment &&
1020 num_same_alignment > max_num_same_alignment) {
1021 // Otherwise, if the array/string object has a known, sufficient alignment
1022 // for just the base but with an unknown offset, record the candidate with
1023 // the most occurrences for dynamic loop peeling (again, the peeling always
1024 // works, since elements have natural alignment).
1025 max_num_same_alignment = num_same_alignment;
1026 peeling_candidate = &(*i);
1027 }
1028 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -08001029
Aart Bik38a3f212017-10-20 17:02:21 -07001030 // Find a suitable alignment strategy.
1031 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1032
1033 // Does vectorization seem profitable?
1034 if (!IsVectorizationProfitable(trip_count)) {
1035 return false;
1036 }
Aart Bik14a68b42017-06-08 14:06:58 -07001037
Aart Bikf8f5a162017-02-06 15:35:29 -08001038 // Success!
1039 return true;
1040}
1041
1042void HLoopOptimization::Vectorize(LoopNode* node,
1043 HBasicBlock* block,
1044 HBasicBlock* exit,
1045 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001046 HBasicBlock* header = node->loop_info->GetHeader();
1047 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1048
Aart Bik14a68b42017-06-08 14:06:58 -07001049 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +01001050 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1051 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -07001052 uint32_t chunk = vector_length_ * unroll;
1053
Aart Bik38a3f212017-10-20 17:02:21 -07001054 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1055
Aart Bik14a68b42017-06-08 14:06:58 -07001056 // A cleanup loop is needed, at least, for any unknown trip count or
1057 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -07001058 bool needs_cleanup = trip_count == 0 ||
1059 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001060
1061 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -07001062 HPhi* main_phi = nullptr;
1063 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -08001064 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -07001065 vector_header_ = header;
1066 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -08001067
Aart Bikdbbac8f2017-09-01 13:06:08 -07001068 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001069 DataType::Type induc_type = main_phi->GetType();
1070 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1071 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001072
Aart Bik38a3f212017-10-20 17:02:21 -07001073 // Generate the trip count for static or dynamic loop peeling, if needed:
1074 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001075 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001076 if (vector_static_peeling_factor_ != 0) {
1077 // Static loop peeling for SIMD alignment (using the most suitable
1078 // fixed peeling factor found during prior alignment analysis).
1079 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1080 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1081 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1082 // Dynamic loop peeling for SIMD alignment (using the most suitable
1083 // candidate found during prior alignment analysis):
1084 // rem = offset % ALIGN; // adjusted as #elements
1085 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1086 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1087 uint32_t align = GetVectorSizeInBytes() >> shift;
1088 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1089 vector_dynamic_peeling_candidate_->is_string_char_at);
1090 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1091 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1092 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1093 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1094 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1095 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1096 induc_type, graph_->GetConstant(induc_type, align), rem));
1097 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1098 rem, graph_->GetConstant(induc_type, 0)));
1099 ptc = Insert(preheader, new (global_allocator_) HSelect(
1100 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1101 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001102 }
1103
1104 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001105 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001106 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001107 // vtc = stc - (stc - ptc) % chunk;
1108 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001109 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1110 HInstruction* vtc = stc;
1111 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001112 DCHECK(IsPowerOfTwo(chunk));
1113 HInstruction* diff = stc;
1114 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001115 if (trip_count == 0) {
1116 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1117 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1118 }
Aart Bik14a68b42017-06-08 14:06:58 -07001119 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1120 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001121 HInstruction* rem = Insert(
1122 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001123 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001124 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001125 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1126 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001127 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001128
1129 // Generate runtime disambiguation test:
1130 // vtc = a != b ? vtc : 0;
1131 if (vector_runtime_test_a_ != nullptr) {
1132 HInstruction* rt = Insert(
1133 preheader,
1134 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1135 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001136 new (global_allocator_)
1137 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001138 needs_cleanup = true;
1139 }
1140
Aart Bik38a3f212017-10-20 17:02:21 -07001141 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001142 // for ( ; i < ptc; i += 1)
1143 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001144 //
1145 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1146 // moved around during suspend checks, since all analysis was based on
1147 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001148 if (ptc != nullptr) {
1149 vector_mode_ = kSequential;
1150 GenerateNewLoop(node,
1151 block,
1152 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1153 vector_index_,
1154 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001155 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001156 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001157 }
1158
1159 // Generate vector loop, possibly further unrolled:
1160 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001161 // <vectorized-loop-body>
1162 vector_mode_ = kVector;
1163 GenerateNewLoop(node,
1164 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001165 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1166 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001167 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001168 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001169 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001170 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1171
1172 // Generate cleanup loop, if needed:
1173 // for ( ; i < stc; i += 1)
1174 // <loop-body>
1175 if (needs_cleanup) {
1176 vector_mode_ = kSequential;
1177 GenerateNewLoop(node,
1178 block,
1179 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001180 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001181 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001182 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001183 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001184 }
1185
Aart Bik0148de42017-09-05 09:25:01 -07001186 // Link reductions to their final uses.
1187 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1188 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001189 HInstruction* phi = i->first;
1190 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1191 // Deal with regular uses.
1192 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1193 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1194 }
1195 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001196 }
1197 }
1198
Aart Bikf8f5a162017-02-06 15:35:29 -08001199 // Remove the original loop by disconnecting the body block
1200 // and removing all instructions from the header.
1201 block->DisconnectAndDelete();
1202 while (!header->GetFirstInstruction()->IsGoto()) {
1203 header->RemoveInstruction(header->GetFirstInstruction());
1204 }
Aart Bikb29f6842017-07-28 15:58:41 -07001205
Aart Bik14a68b42017-06-08 14:06:58 -07001206 // Update loop hierarchy: the old header now resides in the same outer loop
1207 // as the old preheader. Note that we don't bother putting sequential
1208 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001209 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1210 node->loop_info = vloop;
1211}
1212
1213void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1214 HBasicBlock* block,
1215 HBasicBlock* new_preheader,
1216 HInstruction* lo,
1217 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001218 HInstruction* step,
1219 uint32_t unroll) {
1220 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001221 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001222 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001223 vector_preheader_ = new_preheader,
1224 vector_header_ = vector_preheader_->GetSingleSuccessor();
1225 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001226 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1227 kNoRegNumber,
1228 0,
1229 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001230 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001231 // for (i = lo; i < hi; i += step)
1232 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001233 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1234 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001235 vector_header_->AddInstruction(cond);
1236 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001237 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001238 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001239 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001240 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001241 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001242 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1243 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1244 DCHECK(vectorized_def);
1245 }
1246 // Generate body from the instruction map, but in original program order.
1247 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1248 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1249 auto i = vector_map_->find(it.Current());
1250 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1251 Insert(vector_body_, i->second);
1252 // Deal with instructions that need an environment, such as the scalar intrinsics.
1253 if (i->second->NeedsEnvironment()) {
1254 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1255 }
1256 }
1257 }
Aart Bik0148de42017-09-05 09:25:01 -07001258 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001259 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1260 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001261 }
Aart Bik0148de42017-09-05 09:25:01 -07001262 // Finalize phi inputs for the reductions (if any).
1263 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1264 if (!i->first->IsPhi()) {
1265 DCHECK(i->second->IsPhi());
1266 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1267 }
1268 }
Aart Bikb29f6842017-07-28 15:58:41 -07001269 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001270 phi->AddInput(lo);
1271 phi->AddInput(vector_index_);
1272 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001273}
1274
Aart Bikf8f5a162017-02-06 15:35:29 -08001275bool HLoopOptimization::VectorizeDef(LoopNode* node,
1276 HInstruction* instruction,
1277 bool generate_code) {
1278 // Accept a left-hand-side array base[index] for
1279 // (1) supported vector type,
1280 // (2) loop-invariant base,
1281 // (3) unit stride index,
1282 // (4) vectorizable right-hand-side value.
1283 uint64_t restrictions = kNone;
1284 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001285 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001286 HInstruction* base = instruction->InputAt(0);
1287 HInstruction* index = instruction->InputAt(1);
1288 HInstruction* value = instruction->InputAt(2);
1289 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001290 // For narrow types, explicit type conversion may have been
1291 // optimized way, so set the no hi bits restriction here.
1292 if (DataType::Size(type) <= 2) {
1293 restrictions |= kNoHiBits;
1294 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001295 if (TrySetVectorType(type, &restrictions) &&
1296 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001297 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001298 VectorizeUse(node, value, generate_code, type, restrictions)) {
1299 if (generate_code) {
1300 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001301 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001302 } else {
1303 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1304 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001305 return true;
1306 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001307 return false;
1308 }
Aart Bik0148de42017-09-05 09:25:01 -07001309 // Accept a left-hand-side reduction for
1310 // (1) supported vector type,
1311 // (2) vectorizable right-hand-side value.
1312 auto redit = reductions_->find(instruction);
1313 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001314 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001315 // Recognize SAD idiom or direct reduction.
1316 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
Artem Serovaaac0e32018-08-07 00:52:22 +01001317 VectorizeDotProdIdiom(node, instruction, generate_code, type, restrictions) ||
Aart Bikdbbac8f2017-09-01 13:06:08 -07001318 (TrySetVectorType(type, &restrictions) &&
1319 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001320 if (generate_code) {
1321 HInstruction* new_red = vector_map_->Get(instruction);
1322 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1323 vector_permanent_map_->Overwrite(redit->second, new_red);
1324 }
1325 return true;
1326 }
1327 return false;
1328 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001329 // Branch back okay.
1330 if (instruction->IsGoto()) {
1331 return true;
1332 }
1333 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1334 // Note that actual uses are inspected during right-hand-side tree traversal.
1335 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1336}
1337
Aart Bikf8f5a162017-02-06 15:35:29 -08001338bool HLoopOptimization::VectorizeUse(LoopNode* node,
1339 HInstruction* instruction,
1340 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001341 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001342 uint64_t restrictions) {
1343 // Accept anything for which code has already been generated.
1344 if (generate_code) {
1345 if (vector_map_->find(instruction) != vector_map_->end()) {
1346 return true;
1347 }
1348 }
1349 // Continue the right-hand-side tree traversal, passing in proper
1350 // types and vector restrictions along the way. During code generation,
1351 // all new nodes are drawn from the global allocator.
1352 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1353 // Accept invariant use, using scalar expansion.
1354 if (generate_code) {
1355 GenerateVecInv(instruction, type);
1356 }
1357 return true;
1358 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001359 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001360 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1361 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001362 return false;
1363 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001364 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001365 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001366 // (2) loop-invariant base,
1367 // (3) unit stride index,
1368 // (4) vectorizable right-hand-side value.
1369 HInstruction* base = instruction->InputAt(0);
1370 HInstruction* index = instruction->InputAt(1);
1371 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001372 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001373 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001374 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001375 if (generate_code) {
1376 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001377 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001378 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001379 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001380 }
1381 return true;
1382 }
Aart Bik0148de42017-09-05 09:25:01 -07001383 } else if (instruction->IsPhi()) {
1384 // Accept particular phi operations.
1385 if (reductions_->find(instruction) != reductions_->end()) {
1386 // Deal with vector restrictions.
1387 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1388 return false;
1389 }
1390 // Accept a reduction.
1391 if (generate_code) {
1392 GenerateVecReductionPhi(instruction->AsPhi());
1393 }
1394 return true;
1395 }
1396 // TODO: accept right-hand-side induction?
1397 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001398 } else if (instruction->IsTypeConversion()) {
1399 // Accept particular type conversions.
1400 HTypeConversion* conversion = instruction->AsTypeConversion();
1401 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001402 DataType::Type from = conversion->GetInputType();
1403 DataType::Type to = conversion->GetResultType();
1404 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001405 uint32_t size_vec = DataType::Size(type);
1406 uint32_t size_from = DataType::Size(from);
1407 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001408 // Accept an integral conversion
1409 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1410 // (1b) widening from at least vector type, and
1411 // (2) vectorizable operand.
1412 if ((size_to < size_from &&
1413 size_to == size_vec &&
1414 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1415 (size_to >= size_from &&
1416 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001417 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001418 if (generate_code) {
1419 if (vector_mode_ == kVector) {
1420 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1421 } else {
1422 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1423 }
1424 }
1425 return true;
1426 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001427 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001428 DCHECK_EQ(to, type);
1429 // Accept int to float conversion for
1430 // (1) supported int,
1431 // (2) vectorizable operand.
1432 if (TrySetVectorType(from, &restrictions) &&
1433 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1434 if (generate_code) {
1435 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1436 }
1437 return true;
1438 }
1439 }
1440 return false;
1441 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1442 // Accept unary operator for vectorizable operand.
1443 HInstruction* opa = instruction->InputAt(0);
1444 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1445 if (generate_code) {
1446 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1447 }
1448 return true;
1449 }
1450 } else if (instruction->IsAdd() || instruction->IsSub() ||
1451 instruction->IsMul() || instruction->IsDiv() ||
1452 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1453 // Deal with vector restrictions.
1454 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1455 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1456 return false;
1457 }
1458 // Accept binary operator for vectorizable operands.
1459 HInstruction* opa = instruction->InputAt(0);
1460 HInstruction* opb = instruction->InputAt(1);
1461 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1462 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1463 if (generate_code) {
1464 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1465 }
1466 return true;
1467 }
1468 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001469 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001470 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1471 return true;
1472 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001473 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001474 HInstruction* opa = instruction->InputAt(0);
1475 HInstruction* opb = instruction->InputAt(1);
1476 HInstruction* r = opa;
1477 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001478 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1479 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1480 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001481 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1482 // Shifts right need extra care to account for higher order bits.
1483 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1484 if (instruction->IsShr() &&
1485 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1486 return false; // reject, unless all operands are sign-extension narrower
1487 } else if (instruction->IsUShr() &&
1488 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1489 return false; // reject, unless all operands are zero-extension narrower
1490 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001491 }
1492 // Accept shift operator for vectorizable/invariant operands.
1493 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001494 DCHECK(r != nullptr);
1495 if (generate_code && vector_mode_ != kVector) { // de-idiom
1496 r = opa;
1497 }
Aart Bik50e20d52017-05-05 14:07:29 -07001498 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001499 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001500 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001501 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001502 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001503 if (0 <= distance && distance < max_distance) {
1504 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001505 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001506 }
1507 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001508 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001509 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001510 } else if (instruction->IsAbs()) {
1511 // Deal with vector restrictions.
1512 HInstruction* opa = instruction->InputAt(0);
1513 HInstruction* r = opa;
1514 bool is_unsigned = false;
1515 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1516 return false;
1517 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1518 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1519 return false; // reject, unless operand is sign-extension narrower
1520 }
1521 // Accept ABS(x) for vectorizable operand.
1522 DCHECK(r != nullptr);
1523 if (generate_code && vector_mode_ != kVector) { // de-idiom
1524 r = opa;
1525 }
1526 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1527 if (generate_code) {
1528 GenerateVecOp(instruction,
1529 vector_map_->Get(r),
1530 nullptr,
1531 HVecOperation::ToProperType(type, is_unsigned));
1532 }
1533 return true;
1534 }
Aart Bik281c6812016-08-26 11:31:48 -07001535 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001536 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001537}
1538
Aart Bik38a3f212017-10-20 17:02:21 -07001539uint32_t HLoopOptimization::GetVectorSizeInBytes() {
Vladimir Markoa0431112018-06-25 09:32:54 +01001540 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001541 case InstructionSet::kArm:
1542 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001543 return 8; // 64-bit SIMD
1544 default:
1545 return 16; // 128-bit SIMD
1546 }
1547}
1548
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001549bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001550 const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
1551 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001552 case InstructionSet::kArm:
1553 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001554 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001555 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001556 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001557 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001558 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001559 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001560 *restrictions |= kNoDiv | kNoReduction | kNoDotProd;
Artem Serov8f7c4102017-06-21 11:21:37 +01001561 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001562 case DataType::Type::kUint16:
1563 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001564 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoDotProd;
Artem Serov8f7c4102017-06-21 11:21:37 +01001565 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001566 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001567 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001568 return TrySetVectorLength(2);
1569 default:
1570 break;
1571 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001572 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001573 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001574 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001575 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001576 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001577 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001578 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001579 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001580 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001581 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001582 case DataType::Type::kUint16:
1583 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001584 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001585 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001586 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001587 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001588 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001589 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001590 *restrictions |= kNoDiv | kNoMul;
Aart Bikf8f5a162017-02-06 15:35:29 -08001591 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001592 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001593 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001594 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001595 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001596 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001597 return TrySetVectorLength(2);
1598 default:
1599 return false;
1600 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001601 case InstructionSet::kX86:
1602 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001603 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001604 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1605 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001606 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001607 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001608 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001609 *restrictions |= kNoMul |
1610 kNoDiv |
1611 kNoShift |
1612 kNoAbs |
1613 kNoSignedHAdd |
1614 kNoUnroundedHAdd |
1615 kNoSAD |
1616 kNoDotProd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001617 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001618 case DataType::Type::kUint16:
1619 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001620 *restrictions |= kNoDiv |
1621 kNoAbs |
1622 kNoSignedHAdd |
1623 kNoUnroundedHAdd |
1624 kNoSAD|
1625 kNoDotProd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001626 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001627 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001628 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001629 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001630 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001631 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001632 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001633 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001634 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001635 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001636 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001637 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001638 return TrySetVectorLength(2);
1639 default:
1640 break;
1641 } // switch type
1642 }
1643 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001644 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001645 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1646 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001647 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001648 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001649 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001650 *restrictions |= kNoDiv | kNoDotProd;
Lena Djokic51765b02017-06-22 13:49:59 +02001651 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001652 case DataType::Type::kUint16:
1653 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001654 *restrictions |= kNoDiv | kNoStringCharAt | kNoDotProd;
Lena Djokic51765b02017-06-22 13:49:59 +02001655 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001656 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001657 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001658 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001659 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001660 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001661 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001662 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001663 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001664 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001665 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001666 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001667 return TrySetVectorLength(2);
1668 default:
1669 break;
1670 } // switch type
1671 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001672 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001673 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001674 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1675 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001676 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001677 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001678 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001679 *restrictions |= kNoDiv | kNoDotProd;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001680 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001681 case DataType::Type::kUint16:
1682 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001683 *restrictions |= kNoDiv | kNoStringCharAt | kNoDotProd;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001684 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001685 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001686 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001687 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001688 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001689 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001690 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001691 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001692 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001693 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001694 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001695 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001696 return TrySetVectorLength(2);
1697 default:
1698 break;
1699 } // switch type
1700 }
1701 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001702 default:
1703 return false;
1704 } // switch instruction set
1705}
1706
1707bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1708 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1709 // First time set?
1710 if (vector_length_ == 0) {
1711 vector_length_ = length;
1712 }
1713 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1714 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1715 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1716 return vector_length_ == length;
1717}
1718
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001719void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001720 if (vector_map_->find(org) == vector_map_->end()) {
1721 // In scalar code, just use a self pass-through for scalar invariants
1722 // (viz. expression remains itself).
1723 if (vector_mode_ == kSequential) {
1724 vector_map_->Put(org, org);
1725 return;
1726 }
1727 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001728 HInstruction* vector = nullptr;
1729 auto it = vector_permanent_map_->find(org);
1730 if (it != vector_permanent_map_->end()) {
1731 vector = it->second; // reuse during unrolling
1732 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001733 // Generates ReplicateScalar( (optional_type_conv) org ).
1734 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001735 DataType::Type input_type = input->GetType();
1736 if (type != input_type && (type == DataType::Type::kInt64 ||
1737 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001738 input = Insert(vector_preheader_,
1739 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1740 }
1741 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001742 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001743 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1744 }
1745 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001746 }
1747}
1748
1749void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1750 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001751 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001752 int64_t value = 0;
1753 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001754 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001755 if (org->IsPhi()) {
1756 Insert(vector_body_, subscript); // lacks layout placeholder
1757 }
1758 }
1759 vector_map_->Put(org, subscript);
1760 }
1761}
1762
1763void HLoopOptimization::GenerateVecMem(HInstruction* org,
1764 HInstruction* opa,
1765 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001766 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001767 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001768 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001769 HInstruction* vector = nullptr;
1770 if (vector_mode_ == kVector) {
1771 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001772 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001773 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001774 if (opb != nullptr) {
1775 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001776 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001777 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001778 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001779 vector = new (global_allocator_) HVecLoad(global_allocator_,
1780 base,
1781 opa,
1782 type,
1783 org->GetSideEffects(),
1784 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001785 is_string_char_at,
1786 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001787 }
Aart Bik38a3f212017-10-20 17:02:21 -07001788 // Known (forced/adjusted/original) alignment?
1789 if (vector_dynamic_peeling_candidate_ != nullptr) {
1790 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1791 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1792 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1793 vector->AsVecMemoryOperation()->SetAlignment( // forced
1794 Alignment(GetVectorSizeInBytes(), 0));
1795 }
1796 } else {
1797 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1798 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001799 }
1800 } else {
1801 // Scalar store or load.
1802 DCHECK(vector_mode_ == kSequential);
1803 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001804 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001805 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001806 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001807 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001808 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1809 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001810 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001811 }
1812 }
1813 vector_map_->Put(org, vector);
1814}
1815
Aart Bik0148de42017-09-05 09:25:01 -07001816void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1817 DCHECK(reductions_->find(phi) != reductions_->end());
1818 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1819 HInstruction* vector = nullptr;
1820 if (vector_mode_ == kSequential) {
1821 HPhi* new_phi = new (global_allocator_) HPhi(
1822 global_allocator_, kNoRegNumber, 0, phi->GetType());
1823 vector_header_->AddPhi(new_phi);
1824 vector = new_phi;
1825 } else {
1826 // Link vector reduction back to prior unrolled update, or a first phi.
1827 auto it = vector_permanent_map_->find(phi);
1828 if (it != vector_permanent_map_->end()) {
1829 vector = it->second;
1830 } else {
1831 HPhi* new_phi = new (global_allocator_) HPhi(
1832 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1833 vector_header_->AddPhi(new_phi);
1834 vector = new_phi;
1835 }
1836 }
1837 vector_map_->Put(phi, vector);
1838}
1839
1840void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1841 HInstruction* new_phi = vector_map_->Get(phi);
1842 HInstruction* new_init = reductions_->Get(phi);
1843 HInstruction* new_red = vector_map_->Get(reduction);
1844 // Link unrolled vector loop back to new phi.
1845 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1846 DCHECK(new_phi->IsVecOperation());
1847 }
1848 // Prepare the new initialization.
1849 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001850 // Generate a [initial, 0, .., 0] vector for add or
1851 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001852 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001853 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001854 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001855 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001856 if (kind == HVecReduce::ReductionKind::kSum) {
1857 new_init = Insert(vector_preheader_,
1858 new (global_allocator_) HVecSetScalars(global_allocator_,
1859 &new_init,
1860 type,
1861 vector_length,
1862 1,
1863 kNoDexPc));
1864 } else {
1865 new_init = Insert(vector_preheader_,
1866 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1867 new_init,
1868 type,
1869 vector_length,
1870 kNoDexPc));
1871 }
Aart Bik0148de42017-09-05 09:25:01 -07001872 } else {
1873 new_init = ReduceAndExtractIfNeeded(new_init);
1874 }
1875 // Set the phi inputs.
1876 DCHECK(new_phi->IsPhi());
1877 new_phi->AsPhi()->AddInput(new_init);
1878 new_phi->AsPhi()->AddInput(new_red);
1879 // New feed value for next phi (safe mutation in iteration).
1880 reductions_->find(phi)->second = new_phi;
1881}
1882
1883HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1884 if (instruction->IsPhi()) {
1885 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001886 if (HVecOperation::ReturnsSIMDValue(input)) {
1887 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001888 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001889 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001890 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001891 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001892 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1893 // Generate a vector reduction and scalar extract
1894 // x = REDUCE( [x_1, .., x_n] )
1895 // y = x_1
1896 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001897 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001898 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001899 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1900 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001901 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001902 exit->InsertInstructionAfter(instruction, reduce);
1903 }
1904 }
1905 return instruction;
1906}
1907
Aart Bikf8f5a162017-02-06 15:35:29 -08001908#define GENERATE_VEC(x, y) \
1909 if (vector_mode_ == kVector) { \
1910 vector = (x); \
1911 } else { \
1912 DCHECK(vector_mode_ == kSequential); \
1913 vector = (y); \
1914 } \
1915 break;
1916
1917void HLoopOptimization::GenerateVecOp(HInstruction* org,
1918 HInstruction* opa,
1919 HInstruction* opb,
Aart Bik3f08e9b2018-05-01 13:42:03 -07001920 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001921 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001922 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001923 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001924 switch (org->GetKind()) {
1925 case HInstruction::kNeg:
1926 DCHECK(opb == nullptr);
1927 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001928 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1929 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001930 case HInstruction::kNot:
1931 DCHECK(opb == nullptr);
1932 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001933 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1934 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001935 case HInstruction::kBooleanNot:
1936 DCHECK(opb == nullptr);
1937 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001938 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1939 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001940 case HInstruction::kTypeConversion:
1941 DCHECK(opb == nullptr);
1942 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001943 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1944 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001945 case HInstruction::kAdd:
Shalini Salomi Bodapati81d15be2019-05-30 11:00:42 +05301946 #if defined(ART_ENABLE_CODEGEN_x86) || defined(ART_ENABLE_CODEGEN_x86_64)
1947 if ((compiler_options_->GetInstructionSet() == InstructionSet::kX86 ||
1948 compiler_options_->GetInstructionSet() == InstructionSet::kX86_64) &&
1949 compiler_options_->GetInstructionSetFeatures()->AsX86InstructionSetFeatures()
1950 ->HasAVX2()) {
1951 GENERATE_VEC(
1952 new (global_allocator_) HVecAvxAdd(
1953 global_allocator_, opa, opb, type, vector_length_, dex_pc),
1954 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
1955 UNREACHABLE(); // GENERATE_VEC ends with a "break".
1956 }
1957 #endif
Aart Bikf8f5a162017-02-06 15:35:29 -08001958 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001959 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1960 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001961 case HInstruction::kSub:
Shalini Salomi Bodapati81d15be2019-05-30 11:00:42 +05301962 #if defined(ART_ENABLE_CODEGEN_x86) || defined(ART_ENABLE_CODEGEN_x86_64)
1963 if ((compiler_options_->GetInstructionSet() == InstructionSet::kX86 ||
1964 compiler_options_->GetInstructionSet() == InstructionSet::kX86_64) &&
1965 compiler_options_->GetInstructionSetFeatures()->AsX86InstructionSetFeatures()
1966 ->HasAVX2()) {
1967 GENERATE_VEC(
1968 new (global_allocator_) HVecAvxSub(
1969 global_allocator_, opa, opb, type, vector_length_, dex_pc),
1970 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
1971 UNREACHABLE(); // GENERATE_VEC ends with a "break".
1972 }
1973 #endif
Aart Bikf8f5a162017-02-06 15:35:29 -08001974 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001975 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1976 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001977 case HInstruction::kMul:
1978 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001979 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1980 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001981 case HInstruction::kDiv:
1982 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001983 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1984 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001985 case HInstruction::kAnd:
1986 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001987 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1988 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001989 case HInstruction::kOr:
1990 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001991 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1992 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001993 case HInstruction::kXor:
1994 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001995 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1996 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001997 case HInstruction::kShl:
1998 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001999 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2000 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002001 case HInstruction::kShr:
2002 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002003 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2004 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002005 case HInstruction::kUShr:
2006 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07002007 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
2008 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08002009 case HInstruction::kAbs:
2010 DCHECK(opb == nullptr);
2011 GENERATE_VEC(
2012 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
2013 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08002014 default:
2015 break;
2016 } // switch
2017 CHECK(vector != nullptr) << "Unsupported SIMD operator";
2018 vector_map_->Put(org, vector);
2019}
2020
2021#undef GENERATE_VEC
2022
2023//
Aart Bikf3e61ee2017-04-12 17:09:20 -07002024// Vectorization idioms.
2025//
2026
2027// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07002028// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2029// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07002030// Provided that the operands are promoted to a wider form to do the arithmetic and
2031// then cast back to narrower form, the idioms can be mapped into efficient SIMD
2032// implementation that operates directly in narrower form (plus one extra bit).
2033// TODO: current version recognizes implicit byte/short/char widening only;
2034// explicit widening from int to long could be added later.
2035bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2036 HInstruction* instruction,
2037 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002038 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07002039 uint64_t restrictions) {
2040 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07002041 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07002042 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07002043 if ((instruction->IsShr() ||
2044 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07002045 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07002046 // Test for (a + b + c) >> 1 for optional constant c.
2047 HInstruction* a = nullptr;
2048 HInstruction* b = nullptr;
2049 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002050 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07002051 // Accept c == 1 (rounded) or c == 0 (not rounded).
2052 bool is_rounded = false;
2053 if (c == 1) {
2054 is_rounded = true;
2055 } else if (c != 0) {
2056 return false;
2057 }
2058 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07002059 HInstruction* r = nullptr;
2060 HInstruction* s = nullptr;
2061 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002062 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002063 return false;
2064 }
2065 // Deal with vector restrictions.
2066 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2067 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2068 return false;
2069 }
2070 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2071 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002072 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002073 if (generate_code && vector_mode_ != kVector) { // de-idiom
2074 r = instruction->InputAt(0);
2075 s = instruction->InputAt(1);
2076 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002077 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2078 VectorizeUse(node, s, generate_code, type, restrictions)) {
2079 if (generate_code) {
2080 if (vector_mode_ == kVector) {
2081 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2082 global_allocator_,
2083 vector_map_->Get(r),
2084 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002085 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002086 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002087 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002088 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002089 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002090 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002091 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002092 }
2093 }
2094 return true;
2095 }
2096 }
2097 }
2098 return false;
2099}
2100
Aart Bikdbbac8f2017-09-01 13:06:08 -07002101// Method recognizes the following idiom:
2102// q += ABS(a - b) for signed operands a, b
2103// Provided that the operands have the same type or are promoted to a wider form.
2104// Since this may involve a vector length change, the idiom is handled by going directly
2105// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2106// TODO: unsigned SAD too?
2107bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2108 HInstruction* instruction,
2109 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002110 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002111 uint64_t restrictions) {
2112 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2113 // are done in the same precision (either int or long).
2114 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002115 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002116 return false;
2117 }
2118 HInstruction* q = instruction->InputAt(0);
2119 HInstruction* v = instruction->InputAt(1);
2120 HInstruction* a = nullptr;
2121 HInstruction* b = nullptr;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002122 if (v->IsAbs() &&
2123 v->GetType() == reduction_type &&
2124 IsSubConst2(graph_, v->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2125 DCHECK(a != nullptr && b != nullptr);
2126 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002127 return false;
2128 }
2129 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2130 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002131 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002132 HInstruction* r = a;
2133 HInstruction* s = b;
2134 bool is_unsigned = false;
Artem Serovaaac0e32018-08-07 00:52:22 +01002135 DataType::Type sub_type = GetNarrowerType(a, b);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002136 if (reduction_type != sub_type &&
2137 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2138 return false;
2139 }
2140 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002141 if (!TrySetVectorType(sub_type, &restrictions) ||
2142 HasVectorRestrictions(restrictions, kNoSAD) ||
2143 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002144 return false;
2145 }
2146 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2147 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002148 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002149 if (generate_code && vector_mode_ != kVector) { // de-idiom
2150 r = s = v->InputAt(0);
2151 }
2152 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2153 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2154 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2155 if (generate_code) {
2156 if (vector_mode_ == kVector) {
2157 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2158 global_allocator_,
2159 vector_map_->Get(q),
2160 vector_map_->Get(r),
2161 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002162 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002163 GetOtherVL(reduction_type, sub_type, vector_length_),
2164 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002165 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2166 } else {
2167 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2168 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2169 }
2170 }
2171 return true;
2172 }
2173 return false;
2174}
2175
Artem Serovaaac0e32018-08-07 00:52:22 +01002176// Method recognises the following dot product idiom:
2177// q += a * b for operands a, b whose type is narrower than the reduction one.
2178// Provided that the operands have the same type or are promoted to a wider form.
2179// Since this may involve a vector length change, the idiom is handled by going directly
2180// to a dot product node (rather than relying combining finer grained nodes later).
2181bool HLoopOptimization::VectorizeDotProdIdiom(LoopNode* node,
2182 HInstruction* instruction,
2183 bool generate_code,
2184 DataType::Type reduction_type,
2185 uint64_t restrictions) {
2186 if (!instruction->IsAdd() || (reduction_type != DataType::Type::kInt32)) {
2187 return false;
2188 }
2189
2190 HInstruction* q = instruction->InputAt(0);
2191 HInstruction* v = instruction->InputAt(1);
2192 if (!v->IsMul() || v->GetType() != reduction_type) {
2193 return false;
2194 }
2195
2196 HInstruction* a = v->InputAt(0);
2197 HInstruction* b = v->InputAt(1);
2198 HInstruction* r = a;
2199 HInstruction* s = b;
2200 DataType::Type op_type = GetNarrowerType(a, b);
2201 bool is_unsigned = false;
2202
2203 if (!IsNarrowerOperands(a, b, op_type, &r, &s, &is_unsigned)) {
2204 return false;
2205 }
2206 op_type = HVecOperation::ToProperType(op_type, is_unsigned);
2207
2208 if (!TrySetVectorType(op_type, &restrictions) ||
2209 HasVectorRestrictions(restrictions, kNoDotProd)) {
2210 return false;
2211 }
2212
2213 DCHECK(r != nullptr && s != nullptr);
2214 // Accept dot product idiom for vectorizable operands. Vectorized code uses the shorthand
2215 // idiomatic operation. Sequential code uses the original scalar expressions.
2216 if (generate_code && vector_mode_ != kVector) { // de-idiom
2217 r = a;
2218 s = b;
2219 }
2220 if (VectorizeUse(node, q, generate_code, op_type, restrictions) &&
2221 VectorizeUse(node, r, generate_code, op_type, restrictions) &&
2222 VectorizeUse(node, s, generate_code, op_type, restrictions)) {
2223 if (generate_code) {
2224 if (vector_mode_ == kVector) {
2225 vector_map_->Put(instruction, new (global_allocator_) HVecDotProd(
2226 global_allocator_,
2227 vector_map_->Get(q),
2228 vector_map_->Get(r),
2229 vector_map_->Get(s),
2230 reduction_type,
2231 is_unsigned,
2232 GetOtherVL(reduction_type, op_type, vector_length_),
2233 kNoDexPc));
2234 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2235 } else {
2236 GenerateVecOp(v, vector_map_->Get(r), vector_map_->Get(s), reduction_type);
2237 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2238 }
2239 }
2240 return true;
2241 }
2242 return false;
2243}
2244
Aart Bikf3e61ee2017-04-12 17:09:20 -07002245//
Aart Bik14a68b42017-06-08 14:06:58 -07002246// Vectorization heuristics.
2247//
2248
Aart Bik38a3f212017-10-20 17:02:21 -07002249Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2250 DataType::Type type,
2251 bool is_string_char_at,
2252 uint32_t peeling) {
2253 // Combine the alignment and hidden offset that is guaranteed by
2254 // the Android runtime with a known starting index adjusted as bytes.
2255 int64_t value = 0;
2256 if (IsInt64AndGet(offset, /*out*/ &value)) {
2257 uint32_t start_offset =
2258 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2259 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2260 }
2261 // Otherwise, the Android runtime guarantees at least natural alignment.
2262 return Alignment(DataType::Size(type), 0);
2263}
2264
2265void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2266 const ArrayReference* peeling_candidate) {
2267 // Current heuristic: pick the best static loop peeling factor, if any,
2268 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2269 uint32_t max_vote = 0;
2270 for (int32_t i = 0; i < 16; i++) {
2271 if (peeling_votes[i] > max_vote) {
2272 max_vote = peeling_votes[i];
2273 vector_static_peeling_factor_ = i;
2274 }
2275 }
2276 if (max_vote == 0) {
2277 vector_dynamic_peeling_candidate_ = peeling_candidate;
2278 }
2279}
2280
2281uint32_t HLoopOptimization::MaxNumberPeeled() {
2282 if (vector_dynamic_peeling_candidate_ != nullptr) {
2283 return vector_length_ - 1u; // worst-case
2284 }
2285 return vector_static_peeling_factor_; // known exactly
2286}
2287
Aart Bik14a68b42017-06-08 14:06:58 -07002288bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002289 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002290 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002291 // TODO: trip count is really unsigned entity, provided the guarding test
2292 // is satisfied; deal with this more carefully later
2293 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002294 if (vector_length_ == 0) {
2295 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002296 } else if (trip_count < 0) {
2297 return false; // guard against non-taken/large
2298 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002299 return false; // insufficient iterations
2300 }
2301 return true;
2302}
2303
Aart Bik14a68b42017-06-08 14:06:58 -07002304//
Aart Bikf8f5a162017-02-06 15:35:29 -08002305// Helpers.
2306//
2307
2308bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002309 // Start with empty phi induction.
2310 iset_->clear();
2311
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002312 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2313 // smart enough to follow strongly connected components (and it's probably not worth
2314 // it to make it so). See b/33775412.
2315 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2316 return false;
2317 }
Aart Bikb29f6842017-07-28 15:58:41 -07002318
2319 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002320 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2321 if (set != nullptr) {
2322 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002323 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002324 // each instruction is removable and, when restrict uses are requested, other than for phi,
2325 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002326 if (!i->IsInBlock()) {
2327 continue;
2328 } else if (!i->IsRemovable()) {
2329 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002330 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002331 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002332 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2333 if (set->find(use.GetUser()) == set->end()) {
2334 return false;
2335 }
2336 }
2337 }
Aart Bike3dedc52016-11-02 17:50:27 -07002338 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002339 }
Aart Bikcc42be02016-10-20 16:14:16 -07002340 return true;
2341 }
2342 return false;
2343}
2344
Aart Bikb29f6842017-07-28 15:58:41 -07002345bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002346 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002347 // Only unclassified phi cycles are candidates for reductions.
2348 if (induction_range_.IsClassified(phi)) {
2349 return false;
2350 }
2351 // Accept operations like x = x + .., provided that the phi and the reduction are
2352 // used exactly once inside the loop, and by each other.
2353 HInputsRef inputs = phi->GetInputs();
2354 if (inputs.size() == 2) {
2355 HInstruction* reduction = inputs[1];
2356 if (HasReductionFormat(reduction, phi)) {
2357 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002358 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002359 bool single_use_inside_loop =
2360 // Reduction update only used by phi.
2361 reduction->GetUses().HasExactlyOneElement() &&
2362 !reduction->HasEnvironmentUses() &&
2363 // Reduction update is only use of phi inside the loop.
2364 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2365 iset_->size() == 1;
2366 iset_->clear(); // leave the way you found it
2367 if (single_use_inside_loop) {
2368 // Link reduction back, and start recording feed value.
2369 reductions_->Put(reduction, phi);
2370 reductions_->Put(phi, phi->InputAt(0));
2371 return true;
2372 }
2373 }
2374 }
2375 return false;
2376}
2377
2378bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2379 // Start with empty phi induction and reductions.
2380 iset_->clear();
2381 reductions_->clear();
2382
2383 // Scan the phis to find the following (the induction structure has already
2384 // been optimized, so we don't need to worry about trivial cases):
2385 // (1) optional reductions in loop,
2386 // (2) the main induction, used in loop control.
2387 HPhi* phi = nullptr;
2388 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2389 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2390 continue;
2391 } else if (phi == nullptr) {
2392 // Found the first candidate for main induction.
2393 phi = it.Current()->AsPhi();
2394 } else {
2395 return false;
2396 }
2397 }
2398
2399 // Then test for a typical loopheader:
2400 // s: SuspendCheck
2401 // c: Condition(phi, bound)
2402 // i: If(c)
2403 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002404 HInstruction* s = block->GetFirstInstruction();
2405 if (s != nullptr && s->IsSuspendCheck()) {
2406 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002407 if (c != nullptr &&
2408 c->IsCondition() &&
2409 c->GetUses().HasExactlyOneElement() && // only used for termination
2410 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002411 HInstruction* i = c->GetNext();
2412 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2413 iset_->insert(c);
2414 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002415 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002416 return true;
2417 }
2418 }
2419 }
2420 }
2421 return false;
2422}
2423
2424bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002425 if (!block->GetPhis().IsEmpty()) {
2426 return false;
2427 }
2428 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2429 HInstruction* instruction = it.Current();
2430 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2431 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002432 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002433 }
2434 return true;
2435}
2436
2437bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2438 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002439 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002440 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2441 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2442 return true;
2443 }
Aart Bikcc42be02016-10-20 16:14:16 -07002444 }
2445 return false;
2446}
2447
Aart Bik482095d2016-10-10 15:39:10 -07002448bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002449 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002450 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002451 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002452 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002453 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2454 HInstruction* user = use.GetUser();
2455 if (iset_->find(user) == iset_->end()) { // not excluded?
2456 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002457 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002458 // If collect_loop_uses is set, simply keep adding those uses to the set.
2459 // Otherwise, reject uses inside the loop that were not already in the set.
2460 if (collect_loop_uses) {
2461 iset_->insert(user);
2462 continue;
2463 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002464 return false;
2465 }
2466 ++*use_count;
2467 }
2468 }
2469 return true;
2470}
2471
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002472bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2473 HInstruction* instruction,
2474 HBasicBlock* block) {
2475 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002476 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002477 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002478 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002479 const HUseList<HInstruction*>& uses = instruction->GetUses();
2480 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2481 HInstruction* user = it->GetUser();
2482 size_t index = it->GetIndex();
2483 ++it; // increment before replacing
2484 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002485 if (kIsDebugBuild) {
2486 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2487 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2488 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2489 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002490 user->ReplaceInput(replacement, index);
2491 induction_range_.Replace(user, instruction, replacement); // update induction
2492 }
2493 }
Aart Bikb29f6842017-07-28 15:58:41 -07002494 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002495 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2496 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2497 HEnvironment* user = it->GetUser();
2498 size_t index = it->GetIndex();
2499 ++it; // increment before replacing
2500 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002501 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002502 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002503 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2504 user->RemoveAsUserOfInput(index);
2505 user->SetRawEnvAt(index, replacement);
2506 replacement->AddEnvUseAt(user, index);
2507 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002508 }
2509 }
Aart Bik807868e2016-11-03 17:51:43 -07002510 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002511 }
Aart Bik807868e2016-11-03 17:51:43 -07002512 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002513}
2514
Aart Bikf8f5a162017-02-06 15:35:29 -08002515bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2516 HInstruction* instruction,
2517 HBasicBlock* block,
2518 bool collect_loop_uses) {
2519 // Assigning the last value is always successful if there are no uses.
2520 // Otherwise, it succeeds in a no early-exit loop by generating the
2521 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002522 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002523 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2524 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002525 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002526}
2527
Aart Bik6b69e0a2017-01-11 10:20:43 -08002528void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2529 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2530 HInstruction* instruction = i.Current();
2531 if (instruction->IsDeadAndRemovable()) {
2532 simplified_ = true;
2533 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2534 }
2535 }
2536}
2537
Aart Bik14a68b42017-06-08 14:06:58 -07002538bool HLoopOptimization::CanRemoveCycle() {
2539 for (HInstruction* i : *iset_) {
2540 // We can never remove instructions that have environment
2541 // uses when we compile 'debuggable'.
2542 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2543 return false;
2544 }
2545 // A deoptimization should never have an environment input removed.
2546 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2547 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2548 return false;
2549 }
2550 }
2551 }
2552 return true;
2553}
2554
Aart Bik281c6812016-08-26 11:31:48 -07002555} // namespace art