blob: 12b180d5ffa5fa7e6d8bea4ef9e4e87c6d2dfd05 [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) {
Artem Serovaaac0e32018-08-07 00:52:22 +0100354 if (reduction->IsVecAdd() ||
355 reduction->IsVecSub() ||
356 reduction->IsVecSADAccumulate() ||
357 reduction->IsVecDotProd()) {
Aart Bik0148de42017-09-05 09:25:01 -0700358 return HVecReduce::kSum;
Aart Bik0148de42017-09-05 09:25:01 -0700359 }
Aart Bik38a3f212017-10-20 17:02:21 -0700360 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700361 UNREACHABLE();
362}
363
Aart Bikf8f5a162017-02-06 15:35:29 -0800364// Test vector restrictions.
365static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
366 return (restrictions & tested) != 0;
367}
368
Aart Bikf3e61ee2017-04-12 17:09:20 -0700369// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800370static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
371 DCHECK(block != nullptr);
372 DCHECK(instruction != nullptr);
373 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
374 return instruction;
375}
376
Artem Serov21c7e6f2017-07-27 16:04:42 +0100377// Check that instructions from the induction sets are fully removed: have no uses
378// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100379static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100380 for (HInstruction* instr : *iset) {
381 if (instr->GetBlock() != nullptr ||
382 !instr->GetUses().empty() ||
383 !instr->GetEnvUses().empty() ||
384 HasEnvironmentUsedByOthers(instr)) {
385 return false;
386 }
387 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100388 return true;
389}
390
Artem Serov72411e62017-10-19 16:18:07 +0100391// Tries to statically evaluate condition of the specified "HIf" for other condition checks.
392static void TryToEvaluateIfCondition(HIf* instruction, HGraph* graph) {
393 HInstruction* cond = instruction->InputAt(0);
394
395 // If a condition 'cond' is evaluated in an HIf instruction then in the successors of the
396 // IF_BLOCK we statically know the value of the condition 'cond' (TRUE in TRUE_SUCC, FALSE in
397 // FALSE_SUCC). Using that we can replace another evaluation (use) EVAL of the same 'cond'
398 // with TRUE value (FALSE value) if every path from the ENTRY_BLOCK to EVAL_BLOCK contains the
399 // edge HIF_BLOCK->TRUE_SUCC (HIF_BLOCK->FALSE_SUCC).
400 // if (cond) { if(cond) {
401 // if (cond) {} if (1) {}
402 // } else { =======> } else {
403 // if (cond) {} if (0) {}
404 // } }
405 if (!cond->IsConstant()) {
406 HBasicBlock* true_succ = instruction->IfTrueSuccessor();
407 HBasicBlock* false_succ = instruction->IfFalseSuccessor();
408
409 DCHECK_EQ(true_succ->GetPredecessors().size(), 1u);
410 DCHECK_EQ(false_succ->GetPredecessors().size(), 1u);
411
412 const HUseList<HInstruction*>& uses = cond->GetUses();
413 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
414 HInstruction* user = it->GetUser();
415 size_t index = it->GetIndex();
416 HBasicBlock* user_block = user->GetBlock();
417 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
418 ++it;
419 if (true_succ->Dominates(user_block)) {
420 user->ReplaceInput(graph->GetIntConstant(1), index);
421 } else if (false_succ->Dominates(user_block)) {
422 user->ReplaceInput(graph->GetIntConstant(0), index);
423 }
424 }
425 }
426}
427
Artem Serov18ba1da2018-05-16 19:06:32 +0100428// Peel the first 'count' iterations of the loop.
429static void PeelByCount(HLoopInformation* loop_info, int count) {
430 for (int i = 0; i < count; i++) {
431 // Perform peeling.
432 PeelUnrollSimpleHelper helper(loop_info);
433 helper.DoPeeling();
434 }
435}
436
Artem Serovaaac0e32018-08-07 00:52:22 +0100437// Returns the narrower type out of instructions a and b types.
438static DataType::Type GetNarrowerType(HInstruction* a, HInstruction* b) {
439 DataType::Type type = a->GetType();
440 if (DataType::Size(b->GetType()) < DataType::Size(type)) {
441 type = b->GetType();
442 }
443 if (a->IsTypeConversion() &&
444 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(type)) {
445 type = a->InputAt(0)->GetType();
446 }
447 if (b->IsTypeConversion() &&
448 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(type)) {
449 type = b->InputAt(0)->GetType();
450 }
451 return type;
452}
453
Aart Bik281c6812016-08-26 11:31:48 -0700454//
Aart Bikb29f6842017-07-28 15:58:41 -0700455// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700456//
457
458HLoopOptimization::HLoopOptimization(HGraph* graph,
Vladimir Markoa0431112018-06-25 09:32:54 +0100459 const CompilerOptions* compiler_options,
Aart Bikb92cc332017-09-06 15:53:17 -0700460 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800461 OptimizingCompilerStats* stats,
462 const char* name)
463 : HOptimization(graph, name, stats),
Vladimir Markoa0431112018-06-25 09:32:54 +0100464 compiler_options_(compiler_options),
Aart Bik281c6812016-08-26 11:31:48 -0700465 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700466 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100467 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700468 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700469 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700470 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700471 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800472 simplified_(false),
473 vector_length_(0),
474 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700475 vector_static_peeling_factor_(0),
476 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700477 vector_runtime_test_a_(nullptr),
478 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700479 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100480 vector_permanent_map_(nullptr),
481 vector_mode_(kSequential),
482 vector_preheader_(nullptr),
483 vector_header_(nullptr),
484 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100485 vector_index_(nullptr),
Vladimir Markoa0431112018-06-25 09:32:54 +0100486 arch_loop_helper_(ArchNoOptsLoopHelper::Create(compiler_options_ != nullptr
487 ? compiler_options_->GetInstructionSet()
Artem Serov121f2032017-10-23 19:19:06 +0100488 : InstructionSet::kNone,
489 global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700490}
491
Aart Bik24773202018-04-26 10:28:51 -0700492bool HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800493 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700494 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800495 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik24773202018-04-26 10:28:51 -0700496 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700497 }
498
Vladimir Markoca6fff82017-10-03 14:49:14 +0100499 // Phase-local allocator.
500 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700501 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100502
Aart Bik96202302016-10-04 17:33:56 -0700503 // Perform loop optimizations.
Aart Bik24773202018-04-26 10:28:51 -0700504 bool didLoopOpt = LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800505 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800506 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800507 }
508
Aart Bik96202302016-10-04 17:33:56 -0700509 // Detach.
510 loop_allocator_ = nullptr;
511 last_loop_ = top_loop_ = nullptr;
Aart Bik24773202018-04-26 10:28:51 -0700512
513 return didLoopOpt;
Aart Bik96202302016-10-04 17:33:56 -0700514}
515
Aart Bikb29f6842017-07-28 15:58:41 -0700516//
517// Loop setup and traversal.
518//
519
Aart Bik24773202018-04-26 10:28:51 -0700520bool HLoopOptimization::LocalRun() {
521 bool didLoopOpt = false;
Aart Bik96202302016-10-04 17:33:56 -0700522 // Build the linear order using the phase-local allocator. This step enables building
523 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100524 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
525 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700526
Aart Bik281c6812016-08-26 11:31:48 -0700527 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700528 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700529 if (block->IsLoopHeader()) {
530 AddLoop(block->GetLoopInformation());
531 }
532 }
Aart Bik96202302016-10-04 17:33:56 -0700533
Aart Bik8c4a8542016-10-06 11:36:57 -0700534 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800535 // temporary data structures using the phase-local allocator. All new HIR
536 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700537 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100538 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
539 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700540 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100541 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
542 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800543 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100544 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700545 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800546 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700547 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700548 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800549 vector_refs_ = &refs;
550 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700551 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800552 // Traverse.
Aart Bik24773202018-04-26 10:28:51 -0700553 didLoopOpt = TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800554 // Detach.
555 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700556 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800557 vector_refs_ = nullptr;
558 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700559 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700560 }
Aart Bik24773202018-04-26 10:28:51 -0700561 return didLoopOpt;
Aart Bik281c6812016-08-26 11:31:48 -0700562}
563
564void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
565 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800566 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700567 if (last_loop_ == nullptr) {
568 // First loop.
569 DCHECK(top_loop_ == nullptr);
570 last_loop_ = top_loop_ = node;
571 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
572 // Inner loop.
573 node->outer = last_loop_;
574 DCHECK(last_loop_->inner == nullptr);
575 last_loop_ = last_loop_->inner = node;
576 } else {
577 // Subsequent loop.
578 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
579 last_loop_ = last_loop_->outer;
580 }
581 node->outer = last_loop_->outer;
582 node->previous = last_loop_;
583 DCHECK(last_loop_->next == nullptr);
584 last_loop_ = last_loop_->next = node;
585 }
586}
587
588void HLoopOptimization::RemoveLoop(LoopNode* node) {
589 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700590 DCHECK(node->inner == nullptr);
591 if (node->previous != nullptr) {
592 // Within sequence.
593 node->previous->next = node->next;
594 if (node->next != nullptr) {
595 node->next->previous = node->previous;
596 }
597 } else {
598 // First of sequence.
599 if (node->outer != nullptr) {
600 node->outer->inner = node->next;
601 } else {
602 top_loop_ = node->next;
603 }
604 if (node->next != nullptr) {
605 node->next->outer = node->outer;
606 node->next->previous = nullptr;
607 }
608 }
Aart Bik281c6812016-08-26 11:31:48 -0700609}
610
Aart Bikb29f6842017-07-28 15:58:41 -0700611bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
612 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700613 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700614 // Visit inner loops first. Recompute induction information for this
615 // loop if the induction of any inner loop has changed.
616 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700617 induction_range_.ReVisit(node->loop_info);
Aart Bika8360cd2018-05-02 16:07:51 -0700618 changed = true;
Aart Bik482095d2016-10-10 15:39:10 -0700619 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800620 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800621 // Note that since each simplification consists of eliminating code (without
622 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800623 do {
624 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800625 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800626 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700627 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800628 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800629 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700630 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700631 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700632 }
Aart Bik281c6812016-08-26 11:31:48 -0700633 }
Aart Bikb29f6842017-07-28 15:58:41 -0700634 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700635}
636
Aart Bikf8f5a162017-02-06 15:35:29 -0800637//
638// Optimization.
639//
640
Aart Bik281c6812016-08-26 11:31:48 -0700641void HLoopOptimization::SimplifyInduction(LoopNode* node) {
642 HBasicBlock* header = node->loop_info->GetHeader();
643 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700644 // Scan the phis in the header to find opportunities to simplify an induction
645 // cycle that is only used outside the loop. Replace these uses, if any, with
646 // the last value and remove the induction cycle.
647 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
648 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700649 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
650 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800651 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
652 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700653 // Note that it's ok to have replaced uses after the loop with the last value, without
654 // being able to remove the cycle. Environment uses (which are the reason we may not be
655 // able to remove the cycle) within the loop will still hold the right value. We must
656 // have tried first, however, to replace outside uses.
657 if (CanRemoveCycle()) {
658 simplified_ = true;
659 for (HInstruction* i : *iset_) {
660 RemoveFromCycle(i);
661 }
662 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700663 }
Aart Bik482095d2016-10-10 15:39:10 -0700664 }
665 }
666}
667
668void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800669 // Iterate over all basic blocks in the loop-body.
670 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
671 HBasicBlock* block = it.Current();
672 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800673 RemoveDeadInstructions(block->GetPhis());
674 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800675 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800676 if (block->GetPredecessors().size() == 1 &&
677 block->GetSuccessors().size() == 1 &&
678 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800679 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800680 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800681 } else if (block->GetSuccessors().size() == 2) {
682 // Trivial if block can be bypassed to either branch.
683 HBasicBlock* succ0 = block->GetSuccessors()[0];
684 HBasicBlock* succ1 = block->GetSuccessors()[1];
685 HBasicBlock* meet0 = nullptr;
686 HBasicBlock* meet1 = nullptr;
687 if (succ0 != succ1 &&
688 IsGotoBlock(succ0, &meet0) &&
689 IsGotoBlock(succ1, &meet1) &&
690 meet0 == meet1 && // meets again
691 meet0 != block && // no self-loop
692 meet0->GetPhis().IsEmpty()) { // not used for merging
693 simplified_ = true;
694 succ0->DisconnectAndDelete();
695 if (block->Dominates(meet0)) {
696 block->RemoveDominatedBlock(meet0);
697 succ1->AddDominatedBlock(meet0);
698 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700699 }
Aart Bik482095d2016-10-10 15:39:10 -0700700 }
Aart Bik281c6812016-08-26 11:31:48 -0700701 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800702 }
Aart Bik281c6812016-08-26 11:31:48 -0700703}
704
Artem Serov121f2032017-10-23 19:19:06 +0100705bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700706 HBasicBlock* header = node->loop_info->GetHeader();
707 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700708 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800709 int64_t trip_count = 0;
710 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700711 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700712 }
Aart Bik281c6812016-08-26 11:31:48 -0700713 // Ensure there is only a single loop-body (besides the header).
714 HBasicBlock* body = nullptr;
715 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
716 if (it.Current() != header) {
717 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700718 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700719 }
720 body = it.Current();
721 }
722 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700723 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700724 // Ensure there is only a single exit point.
725 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700726 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700727 }
728 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
729 ? header->GetSuccessors()[1]
730 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700731 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700732 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700733 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700734 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800735 // Detect either an empty loop (no side effects other than plain iteration) or
736 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
737 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700738 HPhi* main_phi = nullptr;
739 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800740 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700741 if (reductions_->empty() && // TODO: possible with some effort
742 (is_empty || trip_count == 1) &&
743 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800744 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800745 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700746 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800747 preheader->MergeInstructionsWith(body);
748 }
749 body->DisconnectAndDelete();
750 exit->RemovePredecessor(header);
751 header->RemoveSuccessor(exit);
752 header->RemoveDominatedBlock(exit);
753 header->DisconnectAndDelete();
754 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800755 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800756 preheader->AddDominatedBlock(exit);
757 exit->SetDominator(preheader);
758 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700759 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800760 }
761 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800762 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700763 if (kEnableVectorization &&
764 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700765 ShouldVectorize(node, body, trip_count) &&
766 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
767 Vectorize(node, body, exit, trip_count);
768 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700769 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700770 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800771 }
Aart Bikb29f6842017-07-28 15:58:41 -0700772 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800773}
774
Artem Serov121f2032017-10-23 19:19:06 +0100775bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Artem Serov0e329082018-06-12 10:23:27 +0100776 return TryOptimizeInnerLoopFinite(node) || TryPeelingAndUnrolling(node);
Artem Serov121f2032017-10-23 19:19:06 +0100777}
778
Artem Serov121f2032017-10-23 19:19:06 +0100779
Artem Serov121f2032017-10-23 19:19:06 +0100780
781//
Artem Serov0e329082018-06-12 10:23:27 +0100782// Scalar loop peeling and unrolling: generic part methods.
Artem Serov121f2032017-10-23 19:19:06 +0100783//
784
Artem Serov0e329082018-06-12 10:23:27 +0100785bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
786 bool generate_code) {
787 if (analysis_info->GetNumberOfExits() > 1) {
Artem Serov121f2032017-10-23 19:19:06 +0100788 return false;
789 }
790
Artem Serov0e329082018-06-12 10:23:27 +0100791 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
792 if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
Artem Serov121f2032017-10-23 19:19:06 +0100793 return false;
794 }
795
Artem Serov0e329082018-06-12 10:23:27 +0100796 if (generate_code) {
797 // TODO: support other unrolling factors.
798 DCHECK_EQ(unrolling_factor, 2u);
799
800 // Perform unrolling.
801 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
802 PeelUnrollSimpleHelper helper(loop_info);
803 helper.DoUnrolling();
804
805 // Remove the redundant loop check after unrolling.
806 HIf* copy_hif =
807 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
808 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
809 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
Artem Serov121f2032017-10-23 19:19:06 +0100810 }
Artem Serov121f2032017-10-23 19:19:06 +0100811 return true;
812}
813
Artem Serov0e329082018-06-12 10:23:27 +0100814bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
815 bool generate_code) {
816 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov72411e62017-10-19 16:18:07 +0100817 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
818 return false;
819 }
820
Artem Serov0e329082018-06-12 10:23:27 +0100821 if (analysis_info->GetNumberOfInvariantExits() == 0) {
Artem Serov72411e62017-10-19 16:18:07 +0100822 return false;
823 }
824
Artem Serov0e329082018-06-12 10:23:27 +0100825 if (generate_code) {
826 // Perform peeling.
827 PeelUnrollSimpleHelper helper(loop_info);
828 helper.DoPeeling();
Artem Serov72411e62017-10-19 16:18:07 +0100829
Artem Serov0e329082018-06-12 10:23:27 +0100830 // Statically evaluate loop check after peeling for loop invariant condition.
831 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
832 for (auto entry : *hir_map) {
833 HInstruction* copy = entry.second;
834 if (copy->IsIf()) {
835 TryToEvaluateIfCondition(copy->AsIf(), graph_);
836 }
Artem Serov72411e62017-10-19 16:18:07 +0100837 }
838 }
839
840 return true;
841}
842
Artem Serov18ba1da2018-05-16 19:06:32 +0100843bool HLoopOptimization::TryFullUnrolling(LoopAnalysisInfo* analysis_info, bool generate_code) {
844 // Fully unroll loops with a known and small trip count.
845 int64_t trip_count = analysis_info->GetTripCount();
846 if (!arch_loop_helper_->IsLoopPeelingEnabled() ||
847 trip_count == LoopAnalysisInfo::kUnknownTripCount ||
848 !arch_loop_helper_->IsFullUnrollingBeneficial(analysis_info)) {
849 return false;
850 }
851
852 if (generate_code) {
853 // Peeling of the N first iterations (where N equals to the trip count) will effectively
854 // eliminate the loop: after peeling we will have N sequential iterations copied into the loop
855 // preheader and the original loop. The trip count of this loop will be 0 as the sequential
856 // iterations are executed first and there are exactly N of them. Thus we can statically
857 // evaluate the loop exit condition to 'false' and fully eliminate it.
858 //
859 // Here is an example of full unrolling of a loop with a trip count 2:
860 //
861 // loop_cond_1
862 // loop_body_1 <- First iteration.
863 // |
864 // \ v
865 // ==\ loop_cond_2
866 // ==/ loop_body_2 <- Second iteration.
867 // / |
868 // <- v <-
869 // loop_cond \ loop_cond \ <- This cond is always false.
870 // loop_body _/ loop_body _/
871 //
872 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
873 PeelByCount(loop_info, trip_count);
874 HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
875 int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
876 loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
877 }
878
879 return true;
880}
881
Artem Serov0e329082018-06-12 10:23:27 +0100882bool HLoopOptimization::TryPeelingAndUnrolling(LoopNode* node) {
883 // Don't run peeling/unrolling if compiler_options_ is nullptr (i.e., running under tests)
884 // as InstructionSet is needed.
885 if (compiler_options_ == nullptr) {
886 return false;
887 }
888
889 HLoopInformation* loop_info = node->loop_info;
890 int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
891 LoopAnalysisInfo analysis_info(loop_info);
892 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
893
894 if (analysis_info.HasInstructionsPreventingScalarOpts() ||
895 arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
896 return false;
897 }
898
Artem Serov18ba1da2018-05-16 19:06:32 +0100899 if (!TryFullUnrolling(&analysis_info, /*generate_code*/ false) &&
900 !TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
Artem Serov0e329082018-06-12 10:23:27 +0100901 !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false)) {
902 return false;
903 }
904
905 // Run 'IsLoopClonable' the last as it might be time-consuming.
906 if (!PeelUnrollHelper::IsLoopClonable(loop_info)) {
907 return false;
908 }
909
Artem Serov18ba1da2018-05-16 19:06:32 +0100910 return TryFullUnrolling(&analysis_info) ||
911 TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
Artem Serov0e329082018-06-12 10:23:27 +0100912 TryUnrollingForBranchPenaltyReduction(&analysis_info);
913}
914
Aart Bikf8f5a162017-02-06 15:35:29 -0800915//
916// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
917// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
918// Intel Press, June, 2004 (http://www.aartbik.com/).
919//
920
Aart Bik14a68b42017-06-08 14:06:58 -0700921bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800922 // Reset vector bookkeeping.
923 vector_length_ = 0;
924 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700925 vector_static_peeling_factor_ = 0;
926 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800927 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800928 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800929
930 // Phis in the loop-body prevent vectorization.
931 if (!block->GetPhis().IsEmpty()) {
932 return false;
933 }
934
935 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
936 // occurrence, which allows passing down attributes down the use tree.
937 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
938 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
939 return false; // failure to vectorize a left-hand-side
940 }
941 }
942
Aart Bik38a3f212017-10-20 17:02:21 -0700943 // Prepare alignment analysis:
944 // (1) find desired alignment (SIMD vector size in bytes).
945 // (2) initialize static loop peeling votes (peeling factor that will
946 // make one particular reference aligned), never to exceed (1).
947 // (3) variable to record how many references share same alignment.
948 // (4) variable to record suitable candidate for dynamic loop peeling.
949 uint32_t desired_alignment = GetVectorSizeInBytes();
950 DCHECK_LE(desired_alignment, 16u);
951 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
952 uint32_t max_num_same_alignment = 0;
953 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800954
955 // Data dependence analysis. Find each pair of references with same type, where
956 // at least one is a write. Each such pair denotes a possible data dependence.
957 // This analysis exploits the property that differently typed arrays cannot be
958 // aliased, as well as the property that references either point to the same
959 // array or to two completely disjoint arrays, i.e., no partial aliasing.
960 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700961 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800962 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700963 uint32_t num_same_alignment = 0;
964 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800965 for (auto j = i; ++j != vector_refs_->end(); ) {
966 if (i->type == j->type && (i->lhs || j->lhs)) {
967 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
968 HInstruction* a = i->base;
969 HInstruction* b = j->base;
970 HInstruction* x = i->offset;
971 HInstruction* y = j->offset;
972 if (a == b) {
973 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
974 // Conservatively assume a loop-carried data dependence otherwise, and reject.
975 if (x != y) {
976 return false;
977 }
Aart Bik38a3f212017-10-20 17:02:21 -0700978 // Count the number of references that have the same alignment (since
979 // base and offset are the same) and where at least one is a write, so
980 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
981 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800982 } else {
983 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
984 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
985 // generating an explicit a != b disambiguation runtime test on the two references.
986 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700987 // To avoid excessive overhead, we only accept one a != b test.
988 if (vector_runtime_test_a_ == nullptr) {
989 // First test found.
990 vector_runtime_test_a_ = a;
991 vector_runtime_test_b_ = b;
992 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
993 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
994 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800995 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800996 }
997 }
998 }
999 }
Aart Bik38a3f212017-10-20 17:02:21 -07001000 // Update information for finding suitable alignment strategy:
1001 // (1) update votes for static loop peeling,
1002 // (2) update suitable candidate for dynamic loop peeling.
1003 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
1004 if (alignment.Base() >= desired_alignment) {
1005 // If the array/string object has a known, sufficient alignment, use the
1006 // initial offset to compute the static loop peeling vote (this always
1007 // works, since elements have natural alignment).
1008 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
1009 uint32_t vote = (offset == 0)
1010 ? 0
1011 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
1012 DCHECK_LT(vote, 16u);
1013 ++peeling_votes[vote];
1014 } else if (BaseAlignment() >= desired_alignment &&
1015 num_same_alignment > max_num_same_alignment) {
1016 // Otherwise, if the array/string object has a known, sufficient alignment
1017 // for just the base but with an unknown offset, record the candidate with
1018 // the most occurrences for dynamic loop peeling (again, the peeling always
1019 // works, since elements have natural alignment).
1020 max_num_same_alignment = num_same_alignment;
1021 peeling_candidate = &(*i);
1022 }
1023 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -08001024
Aart Bik38a3f212017-10-20 17:02:21 -07001025 // Find a suitable alignment strategy.
1026 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1027
1028 // Does vectorization seem profitable?
1029 if (!IsVectorizationProfitable(trip_count)) {
1030 return false;
1031 }
Aart Bik14a68b42017-06-08 14:06:58 -07001032
Aart Bikf8f5a162017-02-06 15:35:29 -08001033 // Success!
1034 return true;
1035}
1036
1037void HLoopOptimization::Vectorize(LoopNode* node,
1038 HBasicBlock* block,
1039 HBasicBlock* exit,
1040 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001041 HBasicBlock* header = node->loop_info->GetHeader();
1042 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1043
Aart Bik14a68b42017-06-08 14:06:58 -07001044 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +01001045 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1046 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -07001047 uint32_t chunk = vector_length_ * unroll;
1048
Aart Bik38a3f212017-10-20 17:02:21 -07001049 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1050
Aart Bik14a68b42017-06-08 14:06:58 -07001051 // A cleanup loop is needed, at least, for any unknown trip count or
1052 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -07001053 bool needs_cleanup = trip_count == 0 ||
1054 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001055
1056 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -07001057 HPhi* main_phi = nullptr;
1058 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -08001059 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -07001060 vector_header_ = header;
1061 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -08001062
Aart Bikdbbac8f2017-09-01 13:06:08 -07001063 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001064 DataType::Type induc_type = main_phi->GetType();
1065 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1066 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001067
Aart Bik38a3f212017-10-20 17:02:21 -07001068 // Generate the trip count for static or dynamic loop peeling, if needed:
1069 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001070 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001071 if (vector_static_peeling_factor_ != 0) {
1072 // Static loop peeling for SIMD alignment (using the most suitable
1073 // fixed peeling factor found during prior alignment analysis).
1074 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1075 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1076 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1077 // Dynamic loop peeling for SIMD alignment (using the most suitable
1078 // candidate found during prior alignment analysis):
1079 // rem = offset % ALIGN; // adjusted as #elements
1080 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1081 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1082 uint32_t align = GetVectorSizeInBytes() >> shift;
1083 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1084 vector_dynamic_peeling_candidate_->is_string_char_at);
1085 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1086 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1087 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1088 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1089 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1090 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1091 induc_type, graph_->GetConstant(induc_type, align), rem));
1092 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1093 rem, graph_->GetConstant(induc_type, 0)));
1094 ptc = Insert(preheader, new (global_allocator_) HSelect(
1095 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1096 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001097 }
1098
1099 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001100 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001101 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001102 // vtc = stc - (stc - ptc) % chunk;
1103 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001104 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1105 HInstruction* vtc = stc;
1106 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001107 DCHECK(IsPowerOfTwo(chunk));
1108 HInstruction* diff = stc;
1109 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001110 if (trip_count == 0) {
1111 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1112 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1113 }
Aart Bik14a68b42017-06-08 14:06:58 -07001114 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1115 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001116 HInstruction* rem = Insert(
1117 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001118 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001119 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001120 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1121 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001122 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001123
1124 // Generate runtime disambiguation test:
1125 // vtc = a != b ? vtc : 0;
1126 if (vector_runtime_test_a_ != nullptr) {
1127 HInstruction* rt = Insert(
1128 preheader,
1129 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1130 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001131 new (global_allocator_)
1132 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001133 needs_cleanup = true;
1134 }
1135
Aart Bik38a3f212017-10-20 17:02:21 -07001136 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001137 // for ( ; i < ptc; i += 1)
1138 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001139 //
1140 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1141 // moved around during suspend checks, since all analysis was based on
1142 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001143 if (ptc != nullptr) {
1144 vector_mode_ = kSequential;
1145 GenerateNewLoop(node,
1146 block,
1147 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1148 vector_index_,
1149 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001150 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001151 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001152 }
1153
1154 // Generate vector loop, possibly further unrolled:
1155 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001156 // <vectorized-loop-body>
1157 vector_mode_ = kVector;
1158 GenerateNewLoop(node,
1159 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001160 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1161 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001162 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001163 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001164 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001165 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1166
1167 // Generate cleanup loop, if needed:
1168 // for ( ; i < stc; i += 1)
1169 // <loop-body>
1170 if (needs_cleanup) {
1171 vector_mode_ = kSequential;
1172 GenerateNewLoop(node,
1173 block,
1174 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001175 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001176 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001177 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001178 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001179 }
1180
Aart Bik0148de42017-09-05 09:25:01 -07001181 // Link reductions to their final uses.
1182 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1183 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001184 HInstruction* phi = i->first;
1185 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1186 // Deal with regular uses.
1187 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1188 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1189 }
1190 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001191 }
1192 }
1193
Aart Bikf8f5a162017-02-06 15:35:29 -08001194 // Remove the original loop by disconnecting the body block
1195 // and removing all instructions from the header.
1196 block->DisconnectAndDelete();
1197 while (!header->GetFirstInstruction()->IsGoto()) {
1198 header->RemoveInstruction(header->GetFirstInstruction());
1199 }
Aart Bikb29f6842017-07-28 15:58:41 -07001200
Aart Bik14a68b42017-06-08 14:06:58 -07001201 // Update loop hierarchy: the old header now resides in the same outer loop
1202 // as the old preheader. Note that we don't bother putting sequential
1203 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001204 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1205 node->loop_info = vloop;
1206}
1207
1208void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1209 HBasicBlock* block,
1210 HBasicBlock* new_preheader,
1211 HInstruction* lo,
1212 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001213 HInstruction* step,
1214 uint32_t unroll) {
1215 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001216 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001217 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001218 vector_preheader_ = new_preheader,
1219 vector_header_ = vector_preheader_->GetSingleSuccessor();
1220 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001221 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1222 kNoRegNumber,
1223 0,
1224 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001225 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001226 // for (i = lo; i < hi; i += step)
1227 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001228 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1229 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001230 vector_header_->AddInstruction(cond);
1231 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001232 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001233 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001234 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001235 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001236 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001237 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1238 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1239 DCHECK(vectorized_def);
1240 }
1241 // Generate body from the instruction map, but in original program order.
1242 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1243 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1244 auto i = vector_map_->find(it.Current());
1245 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1246 Insert(vector_body_, i->second);
1247 // Deal with instructions that need an environment, such as the scalar intrinsics.
1248 if (i->second->NeedsEnvironment()) {
1249 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1250 }
1251 }
1252 }
Aart Bik0148de42017-09-05 09:25:01 -07001253 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001254 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1255 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001256 }
Aart Bik0148de42017-09-05 09:25:01 -07001257 // Finalize phi inputs for the reductions (if any).
1258 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1259 if (!i->first->IsPhi()) {
1260 DCHECK(i->second->IsPhi());
1261 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1262 }
1263 }
Aart Bikb29f6842017-07-28 15:58:41 -07001264 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001265 phi->AddInput(lo);
1266 phi->AddInput(vector_index_);
1267 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001268}
1269
Aart Bikf8f5a162017-02-06 15:35:29 -08001270bool HLoopOptimization::VectorizeDef(LoopNode* node,
1271 HInstruction* instruction,
1272 bool generate_code) {
1273 // Accept a left-hand-side array base[index] for
1274 // (1) supported vector type,
1275 // (2) loop-invariant base,
1276 // (3) unit stride index,
1277 // (4) vectorizable right-hand-side value.
1278 uint64_t restrictions = kNone;
1279 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001280 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001281 HInstruction* base = instruction->InputAt(0);
1282 HInstruction* index = instruction->InputAt(1);
1283 HInstruction* value = instruction->InputAt(2);
1284 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001285 // For narrow types, explicit type conversion may have been
1286 // optimized way, so set the no hi bits restriction here.
1287 if (DataType::Size(type) <= 2) {
1288 restrictions |= kNoHiBits;
1289 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001290 if (TrySetVectorType(type, &restrictions) &&
1291 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001292 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001293 VectorizeUse(node, value, generate_code, type, restrictions)) {
1294 if (generate_code) {
1295 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001296 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001297 } else {
1298 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1299 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001300 return true;
1301 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001302 return false;
1303 }
Aart Bik0148de42017-09-05 09:25:01 -07001304 // Accept a left-hand-side reduction for
1305 // (1) supported vector type,
1306 // (2) vectorizable right-hand-side value.
1307 auto redit = reductions_->find(instruction);
1308 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001309 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001310 // Recognize SAD idiom or direct reduction.
1311 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
Artem Serovaaac0e32018-08-07 00:52:22 +01001312 VectorizeDotProdIdiom(node, instruction, generate_code, type, restrictions) ||
Aart Bikdbbac8f2017-09-01 13:06:08 -07001313 (TrySetVectorType(type, &restrictions) &&
1314 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001315 if (generate_code) {
1316 HInstruction* new_red = vector_map_->Get(instruction);
1317 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1318 vector_permanent_map_->Overwrite(redit->second, new_red);
1319 }
1320 return true;
1321 }
1322 return false;
1323 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001324 // Branch back okay.
1325 if (instruction->IsGoto()) {
1326 return true;
1327 }
1328 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1329 // Note that actual uses are inspected during right-hand-side tree traversal.
1330 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1331}
1332
Aart Bikf8f5a162017-02-06 15:35:29 -08001333bool HLoopOptimization::VectorizeUse(LoopNode* node,
1334 HInstruction* instruction,
1335 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001336 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001337 uint64_t restrictions) {
1338 // Accept anything for which code has already been generated.
1339 if (generate_code) {
1340 if (vector_map_->find(instruction) != vector_map_->end()) {
1341 return true;
1342 }
1343 }
1344 // Continue the right-hand-side tree traversal, passing in proper
1345 // types and vector restrictions along the way. During code generation,
1346 // all new nodes are drawn from the global allocator.
1347 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1348 // Accept invariant use, using scalar expansion.
1349 if (generate_code) {
1350 GenerateVecInv(instruction, type);
1351 }
1352 return true;
1353 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001354 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001355 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1356 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001357 return false;
1358 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001359 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001360 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001361 // (2) loop-invariant base,
1362 // (3) unit stride index,
1363 // (4) vectorizable right-hand-side value.
1364 HInstruction* base = instruction->InputAt(0);
1365 HInstruction* index = instruction->InputAt(1);
1366 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001367 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001368 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001369 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001370 if (generate_code) {
1371 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001372 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001373 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001374 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001375 }
1376 return true;
1377 }
Aart Bik0148de42017-09-05 09:25:01 -07001378 } else if (instruction->IsPhi()) {
1379 // Accept particular phi operations.
1380 if (reductions_->find(instruction) != reductions_->end()) {
1381 // Deal with vector restrictions.
1382 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1383 return false;
1384 }
1385 // Accept a reduction.
1386 if (generate_code) {
1387 GenerateVecReductionPhi(instruction->AsPhi());
1388 }
1389 return true;
1390 }
1391 // TODO: accept right-hand-side induction?
1392 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001393 } else if (instruction->IsTypeConversion()) {
1394 // Accept particular type conversions.
1395 HTypeConversion* conversion = instruction->AsTypeConversion();
1396 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001397 DataType::Type from = conversion->GetInputType();
1398 DataType::Type to = conversion->GetResultType();
1399 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001400 uint32_t size_vec = DataType::Size(type);
1401 uint32_t size_from = DataType::Size(from);
1402 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001403 // Accept an integral conversion
1404 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1405 // (1b) widening from at least vector type, and
1406 // (2) vectorizable operand.
1407 if ((size_to < size_from &&
1408 size_to == size_vec &&
1409 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1410 (size_to >= size_from &&
1411 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001412 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001413 if (generate_code) {
1414 if (vector_mode_ == kVector) {
1415 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1416 } else {
1417 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1418 }
1419 }
1420 return true;
1421 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001422 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001423 DCHECK_EQ(to, type);
1424 // Accept int to float conversion for
1425 // (1) supported int,
1426 // (2) vectorizable operand.
1427 if (TrySetVectorType(from, &restrictions) &&
1428 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1429 if (generate_code) {
1430 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1431 }
1432 return true;
1433 }
1434 }
1435 return false;
1436 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1437 // Accept unary operator for vectorizable operand.
1438 HInstruction* opa = instruction->InputAt(0);
1439 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1440 if (generate_code) {
1441 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1442 }
1443 return true;
1444 }
1445 } else if (instruction->IsAdd() || instruction->IsSub() ||
1446 instruction->IsMul() || instruction->IsDiv() ||
1447 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1448 // Deal with vector restrictions.
1449 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1450 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1451 return false;
1452 }
1453 // Accept binary operator for vectorizable operands.
1454 HInstruction* opa = instruction->InputAt(0);
1455 HInstruction* opb = instruction->InputAt(1);
1456 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1457 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1458 if (generate_code) {
1459 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1460 }
1461 return true;
1462 }
1463 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001464 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001465 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1466 return true;
1467 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001468 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001469 HInstruction* opa = instruction->InputAt(0);
1470 HInstruction* opb = instruction->InputAt(1);
1471 HInstruction* r = opa;
1472 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001473 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1474 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1475 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001476 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1477 // Shifts right need extra care to account for higher order bits.
1478 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1479 if (instruction->IsShr() &&
1480 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1481 return false; // reject, unless all operands are sign-extension narrower
1482 } else if (instruction->IsUShr() &&
1483 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1484 return false; // reject, unless all operands are zero-extension narrower
1485 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001486 }
1487 // Accept shift operator for vectorizable/invariant operands.
1488 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001489 DCHECK(r != nullptr);
1490 if (generate_code && vector_mode_ != kVector) { // de-idiom
1491 r = opa;
1492 }
Aart Bik50e20d52017-05-05 14:07:29 -07001493 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001494 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001495 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001496 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001497 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001498 if (0 <= distance && distance < max_distance) {
1499 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001500 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001501 }
1502 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001503 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001504 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001505 } else if (instruction->IsAbs()) {
1506 // Deal with vector restrictions.
1507 HInstruction* opa = instruction->InputAt(0);
1508 HInstruction* r = opa;
1509 bool is_unsigned = false;
1510 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1511 return false;
1512 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1513 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1514 return false; // reject, unless operand is sign-extension narrower
1515 }
1516 // Accept ABS(x) for vectorizable operand.
1517 DCHECK(r != nullptr);
1518 if (generate_code && vector_mode_ != kVector) { // de-idiom
1519 r = opa;
1520 }
1521 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1522 if (generate_code) {
1523 GenerateVecOp(instruction,
1524 vector_map_->Get(r),
1525 nullptr,
1526 HVecOperation::ToProperType(type, is_unsigned));
1527 }
1528 return true;
1529 }
Aart Bik281c6812016-08-26 11:31:48 -07001530 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001531 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001532}
1533
Aart Bik38a3f212017-10-20 17:02:21 -07001534uint32_t HLoopOptimization::GetVectorSizeInBytes() {
Vladimir Markoa0431112018-06-25 09:32:54 +01001535 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001536 case InstructionSet::kArm:
1537 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001538 return 8; // 64-bit SIMD
1539 default:
1540 return 16; // 128-bit SIMD
1541 }
1542}
1543
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001544bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001545 const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
1546 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001547 case InstructionSet::kArm:
1548 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001549 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001550 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001551 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001552 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001553 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001554 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001555 *restrictions |= kNoDiv | kNoReduction | kNoDotProd;
Artem Serov8f7c4102017-06-21 11:21:37 +01001556 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001557 case DataType::Type::kUint16:
1558 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001559 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction | kNoDotProd;
Artem Serov8f7c4102017-06-21 11:21:37 +01001560 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001561 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001562 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001563 return TrySetVectorLength(2);
1564 default:
1565 break;
1566 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001567 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001568 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001569 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001570 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001571 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001572 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001573 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001574 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001575 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001576 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001577 case DataType::Type::kUint16:
1578 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001579 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001580 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001581 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001582 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001583 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001584 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001585 *restrictions |= kNoDiv | kNoMul;
Aart Bikf8f5a162017-02-06 15:35:29 -08001586 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001587 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001588 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001589 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001590 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001591 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001592 return TrySetVectorLength(2);
1593 default:
1594 return false;
1595 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001596 case InstructionSet::kX86:
1597 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001598 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001599 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1600 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001601 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001602 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001603 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001604 *restrictions |= kNoMul |
1605 kNoDiv |
1606 kNoShift |
1607 kNoAbs |
1608 kNoSignedHAdd |
1609 kNoUnroundedHAdd |
1610 kNoSAD |
1611 kNoDotProd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001612 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001613 case DataType::Type::kUint16:
1614 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001615 *restrictions |= kNoDiv |
1616 kNoAbs |
1617 kNoSignedHAdd |
1618 kNoUnroundedHAdd |
1619 kNoSAD|
1620 kNoDotProd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001621 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001622 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001623 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001624 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001625 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001626 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001627 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001628 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001629 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001630 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001631 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001632 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001633 return TrySetVectorLength(2);
1634 default:
1635 break;
1636 } // switch type
1637 }
1638 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001639 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001640 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1641 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001642 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001643 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001644 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001645 *restrictions |= kNoDiv | kNoDotProd;
Lena Djokic51765b02017-06-22 13:49:59 +02001646 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001647 case DataType::Type::kUint16:
1648 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001649 *restrictions |= kNoDiv | kNoStringCharAt | kNoDotProd;
Lena Djokic51765b02017-06-22 13:49:59 +02001650 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001651 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001652 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001653 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001654 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001655 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001656 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001657 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001658 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001659 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001660 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001661 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001662 return TrySetVectorLength(2);
1663 default:
1664 break;
1665 } // switch type
1666 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001667 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001668 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001669 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1670 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001671 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001672 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001673 case DataType::Type::kInt8:
Artem Serovaaac0e32018-08-07 00:52:22 +01001674 *restrictions |= kNoDiv | kNoDotProd;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001675 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001676 case DataType::Type::kUint16:
1677 case DataType::Type::kInt16:
Artem Serovaaac0e32018-08-07 00:52:22 +01001678 *restrictions |= kNoDiv | kNoStringCharAt | kNoDotProd;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001679 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001680 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001681 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001682 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001683 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001684 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001685 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001686 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001687 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001688 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001689 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001690 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001691 return TrySetVectorLength(2);
1692 default:
1693 break;
1694 } // switch type
1695 }
1696 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001697 default:
1698 return false;
1699 } // switch instruction set
1700}
1701
1702bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1703 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1704 // First time set?
1705 if (vector_length_ == 0) {
1706 vector_length_ = length;
1707 }
1708 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1709 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1710 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1711 return vector_length_ == length;
1712}
1713
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001714void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001715 if (vector_map_->find(org) == vector_map_->end()) {
1716 // In scalar code, just use a self pass-through for scalar invariants
1717 // (viz. expression remains itself).
1718 if (vector_mode_ == kSequential) {
1719 vector_map_->Put(org, org);
1720 return;
1721 }
1722 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001723 HInstruction* vector = nullptr;
1724 auto it = vector_permanent_map_->find(org);
1725 if (it != vector_permanent_map_->end()) {
1726 vector = it->second; // reuse during unrolling
1727 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001728 // Generates ReplicateScalar( (optional_type_conv) org ).
1729 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001730 DataType::Type input_type = input->GetType();
1731 if (type != input_type && (type == DataType::Type::kInt64 ||
1732 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001733 input = Insert(vector_preheader_,
1734 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1735 }
1736 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001737 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001738 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1739 }
1740 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001741 }
1742}
1743
1744void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1745 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001746 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001747 int64_t value = 0;
1748 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001749 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001750 if (org->IsPhi()) {
1751 Insert(vector_body_, subscript); // lacks layout placeholder
1752 }
1753 }
1754 vector_map_->Put(org, subscript);
1755 }
1756}
1757
1758void HLoopOptimization::GenerateVecMem(HInstruction* org,
1759 HInstruction* opa,
1760 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001761 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001762 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001763 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001764 HInstruction* vector = nullptr;
1765 if (vector_mode_ == kVector) {
1766 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001767 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001768 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001769 if (opb != nullptr) {
1770 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001771 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001772 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001773 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001774 vector = new (global_allocator_) HVecLoad(global_allocator_,
1775 base,
1776 opa,
1777 type,
1778 org->GetSideEffects(),
1779 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001780 is_string_char_at,
1781 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001782 }
Aart Bik38a3f212017-10-20 17:02:21 -07001783 // Known (forced/adjusted/original) alignment?
1784 if (vector_dynamic_peeling_candidate_ != nullptr) {
1785 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1786 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1787 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1788 vector->AsVecMemoryOperation()->SetAlignment( // forced
1789 Alignment(GetVectorSizeInBytes(), 0));
1790 }
1791 } else {
1792 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1793 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001794 }
1795 } else {
1796 // Scalar store or load.
1797 DCHECK(vector_mode_ == kSequential);
1798 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001799 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001800 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001801 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001802 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001803 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1804 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001805 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001806 }
1807 }
1808 vector_map_->Put(org, vector);
1809}
1810
Aart Bik0148de42017-09-05 09:25:01 -07001811void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1812 DCHECK(reductions_->find(phi) != reductions_->end());
1813 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1814 HInstruction* vector = nullptr;
1815 if (vector_mode_ == kSequential) {
1816 HPhi* new_phi = new (global_allocator_) HPhi(
1817 global_allocator_, kNoRegNumber, 0, phi->GetType());
1818 vector_header_->AddPhi(new_phi);
1819 vector = new_phi;
1820 } else {
1821 // Link vector reduction back to prior unrolled update, or a first phi.
1822 auto it = vector_permanent_map_->find(phi);
1823 if (it != vector_permanent_map_->end()) {
1824 vector = it->second;
1825 } else {
1826 HPhi* new_phi = new (global_allocator_) HPhi(
1827 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1828 vector_header_->AddPhi(new_phi);
1829 vector = new_phi;
1830 }
1831 }
1832 vector_map_->Put(phi, vector);
1833}
1834
1835void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1836 HInstruction* new_phi = vector_map_->Get(phi);
1837 HInstruction* new_init = reductions_->Get(phi);
1838 HInstruction* new_red = vector_map_->Get(reduction);
1839 // Link unrolled vector loop back to new phi.
1840 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1841 DCHECK(new_phi->IsVecOperation());
1842 }
1843 // Prepare the new initialization.
1844 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001845 // Generate a [initial, 0, .., 0] vector for add or
1846 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001847 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001848 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001849 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001850 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001851 if (kind == HVecReduce::ReductionKind::kSum) {
1852 new_init = Insert(vector_preheader_,
1853 new (global_allocator_) HVecSetScalars(global_allocator_,
1854 &new_init,
1855 type,
1856 vector_length,
1857 1,
1858 kNoDexPc));
1859 } else {
1860 new_init = Insert(vector_preheader_,
1861 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1862 new_init,
1863 type,
1864 vector_length,
1865 kNoDexPc));
1866 }
Aart Bik0148de42017-09-05 09:25:01 -07001867 } else {
1868 new_init = ReduceAndExtractIfNeeded(new_init);
1869 }
1870 // Set the phi inputs.
1871 DCHECK(new_phi->IsPhi());
1872 new_phi->AsPhi()->AddInput(new_init);
1873 new_phi->AsPhi()->AddInput(new_red);
1874 // New feed value for next phi (safe mutation in iteration).
1875 reductions_->find(phi)->second = new_phi;
1876}
1877
1878HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1879 if (instruction->IsPhi()) {
1880 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001881 if (HVecOperation::ReturnsSIMDValue(input)) {
1882 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001883 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001884 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001885 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001886 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001887 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1888 // Generate a vector reduction and scalar extract
1889 // x = REDUCE( [x_1, .., x_n] )
1890 // y = x_1
1891 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001892 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001893 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001894 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1895 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001896 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001897 exit->InsertInstructionAfter(instruction, reduce);
1898 }
1899 }
1900 return instruction;
1901}
1902
Aart Bikf8f5a162017-02-06 15:35:29 -08001903#define GENERATE_VEC(x, y) \
1904 if (vector_mode_ == kVector) { \
1905 vector = (x); \
1906 } else { \
1907 DCHECK(vector_mode_ == kSequential); \
1908 vector = (y); \
1909 } \
1910 break;
1911
1912void HLoopOptimization::GenerateVecOp(HInstruction* org,
1913 HInstruction* opa,
1914 HInstruction* opb,
Aart Bik3f08e9b2018-05-01 13:42:03 -07001915 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001916 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001917 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001918 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001919 switch (org->GetKind()) {
1920 case HInstruction::kNeg:
1921 DCHECK(opb == nullptr);
1922 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001923 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1924 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001925 case HInstruction::kNot:
1926 DCHECK(opb == nullptr);
1927 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001928 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1929 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001930 case HInstruction::kBooleanNot:
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_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001935 case HInstruction::kTypeConversion:
1936 DCHECK(opb == nullptr);
1937 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001938 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1939 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001940 case HInstruction::kAdd:
1941 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001942 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1943 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001944 case HInstruction::kSub:
1945 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001946 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1947 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001948 case HInstruction::kMul:
1949 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001950 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1951 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001952 case HInstruction::kDiv:
1953 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001954 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1955 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001956 case HInstruction::kAnd:
1957 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001958 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1959 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001960 case HInstruction::kOr:
1961 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001962 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1963 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001964 case HInstruction::kXor:
1965 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001966 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1967 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001968 case HInstruction::kShl:
1969 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001970 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1971 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001972 case HInstruction::kShr:
1973 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001974 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1975 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001976 case HInstruction::kUShr:
1977 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001978 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1979 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001980 case HInstruction::kAbs:
1981 DCHECK(opb == nullptr);
1982 GENERATE_VEC(
1983 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1984 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001985 default:
1986 break;
1987 } // switch
1988 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1989 vector_map_->Put(org, vector);
1990}
1991
1992#undef GENERATE_VEC
1993
1994//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001995// Vectorization idioms.
1996//
1997
1998// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001999// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
2000// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07002001// Provided that the operands are promoted to a wider form to do the arithmetic and
2002// then cast back to narrower form, the idioms can be mapped into efficient SIMD
2003// implementation that operates directly in narrower form (plus one extra bit).
2004// TODO: current version recognizes implicit byte/short/char widening only;
2005// explicit widening from int to long could be added later.
2006bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
2007 HInstruction* instruction,
2008 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002009 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07002010 uint64_t restrictions) {
2011 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07002012 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07002013 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07002014 if ((instruction->IsShr() ||
2015 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07002016 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07002017 // Test for (a + b + c) >> 1 for optional constant c.
2018 HInstruction* a = nullptr;
2019 HInstruction* b = nullptr;
2020 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002021 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07002022 // Accept c == 1 (rounded) or c == 0 (not rounded).
2023 bool is_rounded = false;
2024 if (c == 1) {
2025 is_rounded = true;
2026 } else if (c != 0) {
2027 return false;
2028 }
2029 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07002030 HInstruction* r = nullptr;
2031 HInstruction* s = nullptr;
2032 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002033 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002034 return false;
2035 }
2036 // Deal with vector restrictions.
2037 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2038 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2039 return false;
2040 }
2041 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2042 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002043 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002044 if (generate_code && vector_mode_ != kVector) { // de-idiom
2045 r = instruction->InputAt(0);
2046 s = instruction->InputAt(1);
2047 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002048 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2049 VectorizeUse(node, s, generate_code, type, restrictions)) {
2050 if (generate_code) {
2051 if (vector_mode_ == kVector) {
2052 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2053 global_allocator_,
2054 vector_map_->Get(r),
2055 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002056 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002057 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002058 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002059 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002060 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002061 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002062 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002063 }
2064 }
2065 return true;
2066 }
2067 }
2068 }
2069 return false;
2070}
2071
Aart Bikdbbac8f2017-09-01 13:06:08 -07002072// Method recognizes the following idiom:
2073// q += ABS(a - b) for signed operands a, b
2074// Provided that the operands have the same type or are promoted to a wider form.
2075// Since this may involve a vector length change, the idiom is handled by going directly
2076// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2077// TODO: unsigned SAD too?
2078bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2079 HInstruction* instruction,
2080 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002081 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002082 uint64_t restrictions) {
2083 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2084 // are done in the same precision (either int or long).
2085 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002086 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002087 return false;
2088 }
2089 HInstruction* q = instruction->InputAt(0);
2090 HInstruction* v = instruction->InputAt(1);
2091 HInstruction* a = nullptr;
2092 HInstruction* b = nullptr;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002093 if (v->IsAbs() &&
2094 v->GetType() == reduction_type &&
2095 IsSubConst2(graph_, v->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2096 DCHECK(a != nullptr && b != nullptr);
2097 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002098 return false;
2099 }
2100 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2101 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002102 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002103 HInstruction* r = a;
2104 HInstruction* s = b;
2105 bool is_unsigned = false;
Artem Serovaaac0e32018-08-07 00:52:22 +01002106 DataType::Type sub_type = GetNarrowerType(a, b);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002107 if (reduction_type != sub_type &&
2108 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2109 return false;
2110 }
2111 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002112 if (!TrySetVectorType(sub_type, &restrictions) ||
2113 HasVectorRestrictions(restrictions, kNoSAD) ||
2114 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002115 return false;
2116 }
2117 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2118 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002119 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002120 if (generate_code && vector_mode_ != kVector) { // de-idiom
2121 r = s = v->InputAt(0);
2122 }
2123 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2124 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2125 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2126 if (generate_code) {
2127 if (vector_mode_ == kVector) {
2128 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2129 global_allocator_,
2130 vector_map_->Get(q),
2131 vector_map_->Get(r),
2132 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002133 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002134 GetOtherVL(reduction_type, sub_type, vector_length_),
2135 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002136 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2137 } else {
2138 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2139 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2140 }
2141 }
2142 return true;
2143 }
2144 return false;
2145}
2146
Artem Serovaaac0e32018-08-07 00:52:22 +01002147// Method recognises the following dot product idiom:
2148// q += a * b for operands a, b whose type is narrower than the reduction one.
2149// Provided that the operands have the same type or are promoted to a wider form.
2150// Since this may involve a vector length change, the idiom is handled by going directly
2151// to a dot product node (rather than relying combining finer grained nodes later).
2152bool HLoopOptimization::VectorizeDotProdIdiom(LoopNode* node,
2153 HInstruction* instruction,
2154 bool generate_code,
2155 DataType::Type reduction_type,
2156 uint64_t restrictions) {
2157 if (!instruction->IsAdd() || (reduction_type != DataType::Type::kInt32)) {
2158 return false;
2159 }
2160
2161 HInstruction* q = instruction->InputAt(0);
2162 HInstruction* v = instruction->InputAt(1);
2163 if (!v->IsMul() || v->GetType() != reduction_type) {
2164 return false;
2165 }
2166
2167 HInstruction* a = v->InputAt(0);
2168 HInstruction* b = v->InputAt(1);
2169 HInstruction* r = a;
2170 HInstruction* s = b;
2171 DataType::Type op_type = GetNarrowerType(a, b);
2172 bool is_unsigned = false;
2173
2174 if (!IsNarrowerOperands(a, b, op_type, &r, &s, &is_unsigned)) {
2175 return false;
2176 }
2177 op_type = HVecOperation::ToProperType(op_type, is_unsigned);
2178
2179 if (!TrySetVectorType(op_type, &restrictions) ||
2180 HasVectorRestrictions(restrictions, kNoDotProd)) {
2181 return false;
2182 }
2183
2184 DCHECK(r != nullptr && s != nullptr);
2185 // Accept dot product idiom for vectorizable operands. Vectorized code uses the shorthand
2186 // idiomatic operation. Sequential code uses the original scalar expressions.
2187 if (generate_code && vector_mode_ != kVector) { // de-idiom
2188 r = a;
2189 s = b;
2190 }
2191 if (VectorizeUse(node, q, generate_code, op_type, restrictions) &&
2192 VectorizeUse(node, r, generate_code, op_type, restrictions) &&
2193 VectorizeUse(node, s, generate_code, op_type, restrictions)) {
2194 if (generate_code) {
2195 if (vector_mode_ == kVector) {
2196 vector_map_->Put(instruction, new (global_allocator_) HVecDotProd(
2197 global_allocator_,
2198 vector_map_->Get(q),
2199 vector_map_->Get(r),
2200 vector_map_->Get(s),
2201 reduction_type,
2202 is_unsigned,
2203 GetOtherVL(reduction_type, op_type, vector_length_),
2204 kNoDexPc));
2205 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2206 } else {
2207 GenerateVecOp(v, vector_map_->Get(r), vector_map_->Get(s), reduction_type);
2208 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2209 }
2210 }
2211 return true;
2212 }
2213 return false;
2214}
2215
Aart Bikf3e61ee2017-04-12 17:09:20 -07002216//
Aart Bik14a68b42017-06-08 14:06:58 -07002217// Vectorization heuristics.
2218//
2219
Aart Bik38a3f212017-10-20 17:02:21 -07002220Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2221 DataType::Type type,
2222 bool is_string_char_at,
2223 uint32_t peeling) {
2224 // Combine the alignment and hidden offset that is guaranteed by
2225 // the Android runtime with a known starting index adjusted as bytes.
2226 int64_t value = 0;
2227 if (IsInt64AndGet(offset, /*out*/ &value)) {
2228 uint32_t start_offset =
2229 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2230 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2231 }
2232 // Otherwise, the Android runtime guarantees at least natural alignment.
2233 return Alignment(DataType::Size(type), 0);
2234}
2235
2236void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2237 const ArrayReference* peeling_candidate) {
2238 // Current heuristic: pick the best static loop peeling factor, if any,
2239 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2240 uint32_t max_vote = 0;
2241 for (int32_t i = 0; i < 16; i++) {
2242 if (peeling_votes[i] > max_vote) {
2243 max_vote = peeling_votes[i];
2244 vector_static_peeling_factor_ = i;
2245 }
2246 }
2247 if (max_vote == 0) {
2248 vector_dynamic_peeling_candidate_ = peeling_candidate;
2249 }
2250}
2251
2252uint32_t HLoopOptimization::MaxNumberPeeled() {
2253 if (vector_dynamic_peeling_candidate_ != nullptr) {
2254 return vector_length_ - 1u; // worst-case
2255 }
2256 return vector_static_peeling_factor_; // known exactly
2257}
2258
Aart Bik14a68b42017-06-08 14:06:58 -07002259bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002260 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002261 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002262 // TODO: trip count is really unsigned entity, provided the guarding test
2263 // is satisfied; deal with this more carefully later
2264 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002265 if (vector_length_ == 0) {
2266 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002267 } else if (trip_count < 0) {
2268 return false; // guard against non-taken/large
2269 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002270 return false; // insufficient iterations
2271 }
2272 return true;
2273}
2274
Aart Bik14a68b42017-06-08 14:06:58 -07002275//
Aart Bikf8f5a162017-02-06 15:35:29 -08002276// Helpers.
2277//
2278
2279bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002280 // Start with empty phi induction.
2281 iset_->clear();
2282
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002283 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2284 // smart enough to follow strongly connected components (and it's probably not worth
2285 // it to make it so). See b/33775412.
2286 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2287 return false;
2288 }
Aart Bikb29f6842017-07-28 15:58:41 -07002289
2290 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002291 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2292 if (set != nullptr) {
2293 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002294 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002295 // each instruction is removable and, when restrict uses are requested, other than for phi,
2296 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002297 if (!i->IsInBlock()) {
2298 continue;
2299 } else if (!i->IsRemovable()) {
2300 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002301 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002302 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002303 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2304 if (set->find(use.GetUser()) == set->end()) {
2305 return false;
2306 }
2307 }
2308 }
Aart Bike3dedc52016-11-02 17:50:27 -07002309 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002310 }
Aart Bikcc42be02016-10-20 16:14:16 -07002311 return true;
2312 }
2313 return false;
2314}
2315
Aart Bikb29f6842017-07-28 15:58:41 -07002316bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002317 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002318 // Only unclassified phi cycles are candidates for reductions.
2319 if (induction_range_.IsClassified(phi)) {
2320 return false;
2321 }
2322 // Accept operations like x = x + .., provided that the phi and the reduction are
2323 // used exactly once inside the loop, and by each other.
2324 HInputsRef inputs = phi->GetInputs();
2325 if (inputs.size() == 2) {
2326 HInstruction* reduction = inputs[1];
2327 if (HasReductionFormat(reduction, phi)) {
2328 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002329 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002330 bool single_use_inside_loop =
2331 // Reduction update only used by phi.
2332 reduction->GetUses().HasExactlyOneElement() &&
2333 !reduction->HasEnvironmentUses() &&
2334 // Reduction update is only use of phi inside the loop.
2335 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2336 iset_->size() == 1;
2337 iset_->clear(); // leave the way you found it
2338 if (single_use_inside_loop) {
2339 // Link reduction back, and start recording feed value.
2340 reductions_->Put(reduction, phi);
2341 reductions_->Put(phi, phi->InputAt(0));
2342 return true;
2343 }
2344 }
2345 }
2346 return false;
2347}
2348
2349bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2350 // Start with empty phi induction and reductions.
2351 iset_->clear();
2352 reductions_->clear();
2353
2354 // Scan the phis to find the following (the induction structure has already
2355 // been optimized, so we don't need to worry about trivial cases):
2356 // (1) optional reductions in loop,
2357 // (2) the main induction, used in loop control.
2358 HPhi* phi = nullptr;
2359 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2360 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2361 continue;
2362 } else if (phi == nullptr) {
2363 // Found the first candidate for main induction.
2364 phi = it.Current()->AsPhi();
2365 } else {
2366 return false;
2367 }
2368 }
2369
2370 // Then test for a typical loopheader:
2371 // s: SuspendCheck
2372 // c: Condition(phi, bound)
2373 // i: If(c)
2374 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002375 HInstruction* s = block->GetFirstInstruction();
2376 if (s != nullptr && s->IsSuspendCheck()) {
2377 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002378 if (c != nullptr &&
2379 c->IsCondition() &&
2380 c->GetUses().HasExactlyOneElement() && // only used for termination
2381 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002382 HInstruction* i = c->GetNext();
2383 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2384 iset_->insert(c);
2385 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002386 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002387 return true;
2388 }
2389 }
2390 }
2391 }
2392 return false;
2393}
2394
2395bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002396 if (!block->GetPhis().IsEmpty()) {
2397 return false;
2398 }
2399 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2400 HInstruction* instruction = it.Current();
2401 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2402 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002403 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002404 }
2405 return true;
2406}
2407
2408bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2409 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002410 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002411 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2412 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2413 return true;
2414 }
Aart Bikcc42be02016-10-20 16:14:16 -07002415 }
2416 return false;
2417}
2418
Aart Bik482095d2016-10-10 15:39:10 -07002419bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002420 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002421 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002422 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002423 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002424 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2425 HInstruction* user = use.GetUser();
2426 if (iset_->find(user) == iset_->end()) { // not excluded?
2427 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002428 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002429 // If collect_loop_uses is set, simply keep adding those uses to the set.
2430 // Otherwise, reject uses inside the loop that were not already in the set.
2431 if (collect_loop_uses) {
2432 iset_->insert(user);
2433 continue;
2434 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002435 return false;
2436 }
2437 ++*use_count;
2438 }
2439 }
2440 return true;
2441}
2442
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002443bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2444 HInstruction* instruction,
2445 HBasicBlock* block) {
2446 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002447 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002448 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002449 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002450 const HUseList<HInstruction*>& uses = instruction->GetUses();
2451 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2452 HInstruction* user = it->GetUser();
2453 size_t index = it->GetIndex();
2454 ++it; // increment before replacing
2455 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002456 if (kIsDebugBuild) {
2457 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2458 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2459 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2460 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002461 user->ReplaceInput(replacement, index);
2462 induction_range_.Replace(user, instruction, replacement); // update induction
2463 }
2464 }
Aart Bikb29f6842017-07-28 15:58:41 -07002465 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002466 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2467 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2468 HEnvironment* user = it->GetUser();
2469 size_t index = it->GetIndex();
2470 ++it; // increment before replacing
2471 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002472 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002473 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002474 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2475 user->RemoveAsUserOfInput(index);
2476 user->SetRawEnvAt(index, replacement);
2477 replacement->AddEnvUseAt(user, index);
2478 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002479 }
2480 }
Aart Bik807868e2016-11-03 17:51:43 -07002481 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002482 }
Aart Bik807868e2016-11-03 17:51:43 -07002483 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002484}
2485
Aart Bikf8f5a162017-02-06 15:35:29 -08002486bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2487 HInstruction* instruction,
2488 HBasicBlock* block,
2489 bool collect_loop_uses) {
2490 // Assigning the last value is always successful if there are no uses.
2491 // Otherwise, it succeeds in a no early-exit loop by generating the
2492 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002493 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002494 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2495 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002496 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002497}
2498
Aart Bik6b69e0a2017-01-11 10:20:43 -08002499void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2500 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2501 HInstruction* instruction = i.Current();
2502 if (instruction->IsDeadAndRemovable()) {
2503 simplified_ = true;
2504 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2505 }
2506 }
2507}
2508
Aart Bik14a68b42017-06-08 14:06:58 -07002509bool HLoopOptimization::CanRemoveCycle() {
2510 for (HInstruction* i : *iset_) {
2511 // We can never remove instructions that have environment
2512 // uses when we compile 'debuggable'.
2513 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2514 return false;
2515 }
2516 // A deoptimization should never have an environment input removed.
2517 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2518 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2519 return false;
2520 }
2521 }
2522 }
2523 return true;
2524}
2525
Aart Bik281c6812016-08-26 11:31:48 -07002526} // namespace art