blob: 7d66155b39e397ba82ccda419e1a6fe737cac92a [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) {
354 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700355 return HVecReduce::kSum;
Aart Bik0148de42017-09-05 09:25:01 -0700356 }
Aart Bik38a3f212017-10-20 17:02:21 -0700357 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700358 UNREACHABLE();
359}
360
Aart Bikf8f5a162017-02-06 15:35:29 -0800361// Test vector restrictions.
362static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
363 return (restrictions & tested) != 0;
364}
365
Aart Bikf3e61ee2017-04-12 17:09:20 -0700366// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800367static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
368 DCHECK(block != nullptr);
369 DCHECK(instruction != nullptr);
370 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
371 return instruction;
372}
373
Artem Serov21c7e6f2017-07-27 16:04:42 +0100374// Check that instructions from the induction sets are fully removed: have no uses
375// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100376static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100377 for (HInstruction* instr : *iset) {
378 if (instr->GetBlock() != nullptr ||
379 !instr->GetUses().empty() ||
380 !instr->GetEnvUses().empty() ||
381 HasEnvironmentUsedByOthers(instr)) {
382 return false;
383 }
384 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100385 return true;
386}
387
Artem Serov72411e62017-10-19 16:18:07 +0100388// Tries to statically evaluate condition of the specified "HIf" for other condition checks.
389static void TryToEvaluateIfCondition(HIf* instruction, HGraph* graph) {
390 HInstruction* cond = instruction->InputAt(0);
391
392 // If a condition 'cond' is evaluated in an HIf instruction then in the successors of the
393 // IF_BLOCK we statically know the value of the condition 'cond' (TRUE in TRUE_SUCC, FALSE in
394 // FALSE_SUCC). Using that we can replace another evaluation (use) EVAL of the same 'cond'
395 // with TRUE value (FALSE value) if every path from the ENTRY_BLOCK to EVAL_BLOCK contains the
396 // edge HIF_BLOCK->TRUE_SUCC (HIF_BLOCK->FALSE_SUCC).
397 // if (cond) { if(cond) {
398 // if (cond) {} if (1) {}
399 // } else { =======> } else {
400 // if (cond) {} if (0) {}
401 // } }
402 if (!cond->IsConstant()) {
403 HBasicBlock* true_succ = instruction->IfTrueSuccessor();
404 HBasicBlock* false_succ = instruction->IfFalseSuccessor();
405
406 DCHECK_EQ(true_succ->GetPredecessors().size(), 1u);
407 DCHECK_EQ(false_succ->GetPredecessors().size(), 1u);
408
409 const HUseList<HInstruction*>& uses = cond->GetUses();
410 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
411 HInstruction* user = it->GetUser();
412 size_t index = it->GetIndex();
413 HBasicBlock* user_block = user->GetBlock();
414 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
415 ++it;
416 if (true_succ->Dominates(user_block)) {
417 user->ReplaceInput(graph->GetIntConstant(1), index);
418 } else if (false_succ->Dominates(user_block)) {
419 user->ReplaceInput(graph->GetIntConstant(0), index);
420 }
421 }
422 }
423}
424
Artem Serov18ba1da2018-05-16 19:06:32 +0100425// Peel the first 'count' iterations of the loop.
426static void PeelByCount(HLoopInformation* loop_info, int count) {
427 for (int i = 0; i < count; i++) {
428 // Perform peeling.
429 PeelUnrollSimpleHelper helper(loop_info);
430 helper.DoPeeling();
431 }
432}
433
Aart Bik281c6812016-08-26 11:31:48 -0700434//
Aart Bikb29f6842017-07-28 15:58:41 -0700435// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700436//
437
438HLoopOptimization::HLoopOptimization(HGraph* graph,
Vladimir Markoa0431112018-06-25 09:32:54 +0100439 const CompilerOptions* compiler_options,
Aart Bikb92cc332017-09-06 15:53:17 -0700440 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800441 OptimizingCompilerStats* stats,
442 const char* name)
443 : HOptimization(graph, name, stats),
Vladimir Markoa0431112018-06-25 09:32:54 +0100444 compiler_options_(compiler_options),
Aart Bik281c6812016-08-26 11:31:48 -0700445 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700446 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100447 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700448 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700449 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700450 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700451 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800452 simplified_(false),
453 vector_length_(0),
454 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700455 vector_static_peeling_factor_(0),
456 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700457 vector_runtime_test_a_(nullptr),
458 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700459 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100460 vector_permanent_map_(nullptr),
461 vector_mode_(kSequential),
462 vector_preheader_(nullptr),
463 vector_header_(nullptr),
464 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100465 vector_index_(nullptr),
Vladimir Markoa0431112018-06-25 09:32:54 +0100466 arch_loop_helper_(ArchNoOptsLoopHelper::Create(compiler_options_ != nullptr
467 ? compiler_options_->GetInstructionSet()
Artem Serov121f2032017-10-23 19:19:06 +0100468 : InstructionSet::kNone,
469 global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700470}
471
Aart Bik24773202018-04-26 10:28:51 -0700472bool HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800473 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700474 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800475 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik24773202018-04-26 10:28:51 -0700476 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700477 }
478
Vladimir Markoca6fff82017-10-03 14:49:14 +0100479 // Phase-local allocator.
480 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700481 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100482
Aart Bik96202302016-10-04 17:33:56 -0700483 // Perform loop optimizations.
Aart Bik24773202018-04-26 10:28:51 -0700484 bool didLoopOpt = LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800485 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800486 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800487 }
488
Aart Bik96202302016-10-04 17:33:56 -0700489 // Detach.
490 loop_allocator_ = nullptr;
491 last_loop_ = top_loop_ = nullptr;
Aart Bik24773202018-04-26 10:28:51 -0700492
493 return didLoopOpt;
Aart Bik96202302016-10-04 17:33:56 -0700494}
495
Aart Bikb29f6842017-07-28 15:58:41 -0700496//
497// Loop setup and traversal.
498//
499
Aart Bik24773202018-04-26 10:28:51 -0700500bool HLoopOptimization::LocalRun() {
501 bool didLoopOpt = false;
Aart Bik96202302016-10-04 17:33:56 -0700502 // Build the linear order using the phase-local allocator. This step enables building
503 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100504 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
505 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700506
Aart Bik281c6812016-08-26 11:31:48 -0700507 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700508 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700509 if (block->IsLoopHeader()) {
510 AddLoop(block->GetLoopInformation());
511 }
512 }
Aart Bik96202302016-10-04 17:33:56 -0700513
Aart Bik8c4a8542016-10-06 11:36:57 -0700514 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800515 // temporary data structures using the phase-local allocator. All new HIR
516 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700517 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100518 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
519 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700520 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100521 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
522 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800523 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100524 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700525 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800526 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700527 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700528 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800529 vector_refs_ = &refs;
530 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700531 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800532 // Traverse.
Aart Bik24773202018-04-26 10:28:51 -0700533 didLoopOpt = TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800534 // Detach.
535 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700536 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800537 vector_refs_ = nullptr;
538 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700539 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700540 }
Aart Bik24773202018-04-26 10:28:51 -0700541 return didLoopOpt;
Aart Bik281c6812016-08-26 11:31:48 -0700542}
543
544void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
545 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800546 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700547 if (last_loop_ == nullptr) {
548 // First loop.
549 DCHECK(top_loop_ == nullptr);
550 last_loop_ = top_loop_ = node;
551 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
552 // Inner loop.
553 node->outer = last_loop_;
554 DCHECK(last_loop_->inner == nullptr);
555 last_loop_ = last_loop_->inner = node;
556 } else {
557 // Subsequent loop.
558 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
559 last_loop_ = last_loop_->outer;
560 }
561 node->outer = last_loop_->outer;
562 node->previous = last_loop_;
563 DCHECK(last_loop_->next == nullptr);
564 last_loop_ = last_loop_->next = node;
565 }
566}
567
568void HLoopOptimization::RemoveLoop(LoopNode* node) {
569 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700570 DCHECK(node->inner == nullptr);
571 if (node->previous != nullptr) {
572 // Within sequence.
573 node->previous->next = node->next;
574 if (node->next != nullptr) {
575 node->next->previous = node->previous;
576 }
577 } else {
578 // First of sequence.
579 if (node->outer != nullptr) {
580 node->outer->inner = node->next;
581 } else {
582 top_loop_ = node->next;
583 }
584 if (node->next != nullptr) {
585 node->next->outer = node->outer;
586 node->next->previous = nullptr;
587 }
588 }
Aart Bik281c6812016-08-26 11:31:48 -0700589}
590
Aart Bikb29f6842017-07-28 15:58:41 -0700591bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
592 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700593 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700594 // Visit inner loops first. Recompute induction information for this
595 // loop if the induction of any inner loop has changed.
596 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700597 induction_range_.ReVisit(node->loop_info);
Aart Bika8360cd2018-05-02 16:07:51 -0700598 changed = true;
Aart Bik482095d2016-10-10 15:39:10 -0700599 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800600 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800601 // Note that since each simplification consists of eliminating code (without
602 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800603 do {
604 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800605 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800606 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700607 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800608 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800609 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700610 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700611 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700612 }
Aart Bik281c6812016-08-26 11:31:48 -0700613 }
Aart Bikb29f6842017-07-28 15:58:41 -0700614 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700615}
616
Aart Bikf8f5a162017-02-06 15:35:29 -0800617//
618// Optimization.
619//
620
Aart Bik281c6812016-08-26 11:31:48 -0700621void HLoopOptimization::SimplifyInduction(LoopNode* node) {
622 HBasicBlock* header = node->loop_info->GetHeader();
623 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700624 // Scan the phis in the header to find opportunities to simplify an induction
625 // cycle that is only used outside the loop. Replace these uses, if any, with
626 // the last value and remove the induction cycle.
627 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
628 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700629 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
630 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800631 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
632 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700633 // Note that it's ok to have replaced uses after the loop with the last value, without
634 // being able to remove the cycle. Environment uses (which are the reason we may not be
635 // able to remove the cycle) within the loop will still hold the right value. We must
636 // have tried first, however, to replace outside uses.
637 if (CanRemoveCycle()) {
638 simplified_ = true;
639 for (HInstruction* i : *iset_) {
640 RemoveFromCycle(i);
641 }
642 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700643 }
Aart Bik482095d2016-10-10 15:39:10 -0700644 }
645 }
646}
647
648void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800649 // Iterate over all basic blocks in the loop-body.
650 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
651 HBasicBlock* block = it.Current();
652 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800653 RemoveDeadInstructions(block->GetPhis());
654 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800655 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800656 if (block->GetPredecessors().size() == 1 &&
657 block->GetSuccessors().size() == 1 &&
658 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800659 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800660 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800661 } else if (block->GetSuccessors().size() == 2) {
662 // Trivial if block can be bypassed to either branch.
663 HBasicBlock* succ0 = block->GetSuccessors()[0];
664 HBasicBlock* succ1 = block->GetSuccessors()[1];
665 HBasicBlock* meet0 = nullptr;
666 HBasicBlock* meet1 = nullptr;
667 if (succ0 != succ1 &&
668 IsGotoBlock(succ0, &meet0) &&
669 IsGotoBlock(succ1, &meet1) &&
670 meet0 == meet1 && // meets again
671 meet0 != block && // no self-loop
672 meet0->GetPhis().IsEmpty()) { // not used for merging
673 simplified_ = true;
674 succ0->DisconnectAndDelete();
675 if (block->Dominates(meet0)) {
676 block->RemoveDominatedBlock(meet0);
677 succ1->AddDominatedBlock(meet0);
678 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700679 }
Aart Bik482095d2016-10-10 15:39:10 -0700680 }
Aart Bik281c6812016-08-26 11:31:48 -0700681 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800682 }
Aart Bik281c6812016-08-26 11:31:48 -0700683}
684
Artem Serov121f2032017-10-23 19:19:06 +0100685bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700686 HBasicBlock* header = node->loop_info->GetHeader();
687 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700688 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800689 int64_t trip_count = 0;
690 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700691 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700692 }
Aart Bik281c6812016-08-26 11:31:48 -0700693 // Ensure there is only a single loop-body (besides the header).
694 HBasicBlock* body = nullptr;
695 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
696 if (it.Current() != header) {
697 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700698 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700699 }
700 body = it.Current();
701 }
702 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700703 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700704 // Ensure there is only a single exit point.
705 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700706 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700707 }
708 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
709 ? header->GetSuccessors()[1]
710 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700711 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700712 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700713 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700714 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800715 // Detect either an empty loop (no side effects other than plain iteration) or
716 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
717 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700718 HPhi* main_phi = nullptr;
719 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800720 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700721 if (reductions_->empty() && // TODO: possible with some effort
722 (is_empty || trip_count == 1) &&
723 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800724 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800725 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700726 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800727 preheader->MergeInstructionsWith(body);
728 }
729 body->DisconnectAndDelete();
730 exit->RemovePredecessor(header);
731 header->RemoveSuccessor(exit);
732 header->RemoveDominatedBlock(exit);
733 header->DisconnectAndDelete();
734 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800735 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800736 preheader->AddDominatedBlock(exit);
737 exit->SetDominator(preheader);
738 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700739 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800740 }
741 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800742 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700743 if (kEnableVectorization &&
744 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700745 ShouldVectorize(node, body, trip_count) &&
746 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
747 Vectorize(node, body, exit, trip_count);
748 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700749 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700750 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800751 }
Aart Bikb29f6842017-07-28 15:58:41 -0700752 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800753}
754
Artem Serov121f2032017-10-23 19:19:06 +0100755bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Artem Serov0e329082018-06-12 10:23:27 +0100756 return TryOptimizeInnerLoopFinite(node) || TryPeelingAndUnrolling(node);
Artem Serov121f2032017-10-23 19:19:06 +0100757}
758
Artem Serov121f2032017-10-23 19:19:06 +0100759
Artem Serov121f2032017-10-23 19:19:06 +0100760
761//
Artem Serov0e329082018-06-12 10:23:27 +0100762// Scalar loop peeling and unrolling: generic part methods.
Artem Serov121f2032017-10-23 19:19:06 +0100763//
764
Artem Serov0e329082018-06-12 10:23:27 +0100765bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
766 bool generate_code) {
767 if (analysis_info->GetNumberOfExits() > 1) {
Artem Serov121f2032017-10-23 19:19:06 +0100768 return false;
769 }
770
Artem Serov0e329082018-06-12 10:23:27 +0100771 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
772 if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
Artem Serov121f2032017-10-23 19:19:06 +0100773 return false;
774 }
775
Artem Serov0e329082018-06-12 10:23:27 +0100776 if (generate_code) {
777 // TODO: support other unrolling factors.
778 DCHECK_EQ(unrolling_factor, 2u);
779
780 // Perform unrolling.
781 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
782 PeelUnrollSimpleHelper helper(loop_info);
783 helper.DoUnrolling();
784
785 // Remove the redundant loop check after unrolling.
786 HIf* copy_hif =
787 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
788 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
789 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
Artem Serov121f2032017-10-23 19:19:06 +0100790 }
Artem Serov121f2032017-10-23 19:19:06 +0100791 return true;
792}
793
Artem Serov0e329082018-06-12 10:23:27 +0100794bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
795 bool generate_code) {
796 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov72411e62017-10-19 16:18:07 +0100797 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
798 return false;
799 }
800
Artem Serov0e329082018-06-12 10:23:27 +0100801 if (analysis_info->GetNumberOfInvariantExits() == 0) {
Artem Serov72411e62017-10-19 16:18:07 +0100802 return false;
803 }
804
Artem Serov0e329082018-06-12 10:23:27 +0100805 if (generate_code) {
806 // Perform peeling.
807 PeelUnrollSimpleHelper helper(loop_info);
808 helper.DoPeeling();
Artem Serov72411e62017-10-19 16:18:07 +0100809
Artem Serov0e329082018-06-12 10:23:27 +0100810 // Statically evaluate loop check after peeling for loop invariant condition.
811 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
812 for (auto entry : *hir_map) {
813 HInstruction* copy = entry.second;
814 if (copy->IsIf()) {
815 TryToEvaluateIfCondition(copy->AsIf(), graph_);
816 }
Artem Serov72411e62017-10-19 16:18:07 +0100817 }
818 }
819
820 return true;
821}
822
Artem Serov18ba1da2018-05-16 19:06:32 +0100823bool HLoopOptimization::TryFullUnrolling(LoopAnalysisInfo* analysis_info, bool generate_code) {
824 // Fully unroll loops with a known and small trip count.
825 int64_t trip_count = analysis_info->GetTripCount();
826 if (!arch_loop_helper_->IsLoopPeelingEnabled() ||
827 trip_count == LoopAnalysisInfo::kUnknownTripCount ||
828 !arch_loop_helper_->IsFullUnrollingBeneficial(analysis_info)) {
829 return false;
830 }
831
832 if (generate_code) {
833 // Peeling of the N first iterations (where N equals to the trip count) will effectively
834 // eliminate the loop: after peeling we will have N sequential iterations copied into the loop
835 // preheader and the original loop. The trip count of this loop will be 0 as the sequential
836 // iterations are executed first and there are exactly N of them. Thus we can statically
837 // evaluate the loop exit condition to 'false' and fully eliminate it.
838 //
839 // Here is an example of full unrolling of a loop with a trip count 2:
840 //
841 // loop_cond_1
842 // loop_body_1 <- First iteration.
843 // |
844 // \ v
845 // ==\ loop_cond_2
846 // ==/ loop_body_2 <- Second iteration.
847 // / |
848 // <- v <-
849 // loop_cond \ loop_cond \ <- This cond is always false.
850 // loop_body _/ loop_body _/
851 //
852 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
853 PeelByCount(loop_info, trip_count);
854 HIf* loop_hif = loop_info->GetHeader()->GetLastInstruction()->AsIf();
855 int32_t constant = loop_info->Contains(*loop_hif->IfTrueSuccessor()) ? 0 : 1;
856 loop_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
857 }
858
859 return true;
860}
861
Artem Serov0e329082018-06-12 10:23:27 +0100862bool HLoopOptimization::TryPeelingAndUnrolling(LoopNode* node) {
863 // Don't run peeling/unrolling if compiler_options_ is nullptr (i.e., running under tests)
864 // as InstructionSet is needed.
865 if (compiler_options_ == nullptr) {
866 return false;
867 }
868
869 HLoopInformation* loop_info = node->loop_info;
870 int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
871 LoopAnalysisInfo analysis_info(loop_info);
872 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
873
874 if (analysis_info.HasInstructionsPreventingScalarOpts() ||
875 arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
876 return false;
877 }
878
Artem Serov18ba1da2018-05-16 19:06:32 +0100879 if (!TryFullUnrolling(&analysis_info, /*generate_code*/ false) &&
880 !TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
Artem Serov0e329082018-06-12 10:23:27 +0100881 !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false)) {
882 return false;
883 }
884
885 // Run 'IsLoopClonable' the last as it might be time-consuming.
886 if (!PeelUnrollHelper::IsLoopClonable(loop_info)) {
887 return false;
888 }
889
Artem Serov18ba1da2018-05-16 19:06:32 +0100890 return TryFullUnrolling(&analysis_info) ||
891 TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
Artem Serov0e329082018-06-12 10:23:27 +0100892 TryUnrollingForBranchPenaltyReduction(&analysis_info);
893}
894
Aart Bikf8f5a162017-02-06 15:35:29 -0800895//
896// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
897// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
898// Intel Press, June, 2004 (http://www.aartbik.com/).
899//
900
Aart Bik14a68b42017-06-08 14:06:58 -0700901bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800902 // Reset vector bookkeeping.
903 vector_length_ = 0;
904 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700905 vector_static_peeling_factor_ = 0;
906 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800907 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800908 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800909
910 // Phis in the loop-body prevent vectorization.
911 if (!block->GetPhis().IsEmpty()) {
912 return false;
913 }
914
915 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
916 // occurrence, which allows passing down attributes down the use tree.
917 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
918 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
919 return false; // failure to vectorize a left-hand-side
920 }
921 }
922
Aart Bik38a3f212017-10-20 17:02:21 -0700923 // Prepare alignment analysis:
924 // (1) find desired alignment (SIMD vector size in bytes).
925 // (2) initialize static loop peeling votes (peeling factor that will
926 // make one particular reference aligned), never to exceed (1).
927 // (3) variable to record how many references share same alignment.
928 // (4) variable to record suitable candidate for dynamic loop peeling.
929 uint32_t desired_alignment = GetVectorSizeInBytes();
930 DCHECK_LE(desired_alignment, 16u);
931 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
932 uint32_t max_num_same_alignment = 0;
933 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800934
935 // Data dependence analysis. Find each pair of references with same type, where
936 // at least one is a write. Each such pair denotes a possible data dependence.
937 // This analysis exploits the property that differently typed arrays cannot be
938 // aliased, as well as the property that references either point to the same
939 // array or to two completely disjoint arrays, i.e., no partial aliasing.
940 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700941 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800942 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700943 uint32_t num_same_alignment = 0;
944 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800945 for (auto j = i; ++j != vector_refs_->end(); ) {
946 if (i->type == j->type && (i->lhs || j->lhs)) {
947 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
948 HInstruction* a = i->base;
949 HInstruction* b = j->base;
950 HInstruction* x = i->offset;
951 HInstruction* y = j->offset;
952 if (a == b) {
953 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
954 // Conservatively assume a loop-carried data dependence otherwise, and reject.
955 if (x != y) {
956 return false;
957 }
Aart Bik38a3f212017-10-20 17:02:21 -0700958 // Count the number of references that have the same alignment (since
959 // base and offset are the same) and where at least one is a write, so
960 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
961 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800962 } else {
963 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
964 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
965 // generating an explicit a != b disambiguation runtime test on the two references.
966 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700967 // To avoid excessive overhead, we only accept one a != b test.
968 if (vector_runtime_test_a_ == nullptr) {
969 // First test found.
970 vector_runtime_test_a_ = a;
971 vector_runtime_test_b_ = b;
972 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
973 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
974 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800975 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800976 }
977 }
978 }
979 }
Aart Bik38a3f212017-10-20 17:02:21 -0700980 // Update information for finding suitable alignment strategy:
981 // (1) update votes for static loop peeling,
982 // (2) update suitable candidate for dynamic loop peeling.
983 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
984 if (alignment.Base() >= desired_alignment) {
985 // If the array/string object has a known, sufficient alignment, use the
986 // initial offset to compute the static loop peeling vote (this always
987 // works, since elements have natural alignment).
988 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
989 uint32_t vote = (offset == 0)
990 ? 0
991 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
992 DCHECK_LT(vote, 16u);
993 ++peeling_votes[vote];
994 } else if (BaseAlignment() >= desired_alignment &&
995 num_same_alignment > max_num_same_alignment) {
996 // Otherwise, if the array/string object has a known, sufficient alignment
997 // for just the base but with an unknown offset, record the candidate with
998 // the most occurrences for dynamic loop peeling (again, the peeling always
999 // works, since elements have natural alignment).
1000 max_num_same_alignment = num_same_alignment;
1001 peeling_candidate = &(*i);
1002 }
1003 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -08001004
Aart Bik38a3f212017-10-20 17:02:21 -07001005 // Find a suitable alignment strategy.
1006 SetAlignmentStrategy(peeling_votes, peeling_candidate);
1007
1008 // Does vectorization seem profitable?
1009 if (!IsVectorizationProfitable(trip_count)) {
1010 return false;
1011 }
Aart Bik14a68b42017-06-08 14:06:58 -07001012
Aart Bikf8f5a162017-02-06 15:35:29 -08001013 // Success!
1014 return true;
1015}
1016
1017void HLoopOptimization::Vectorize(LoopNode* node,
1018 HBasicBlock* block,
1019 HBasicBlock* exit,
1020 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001021 HBasicBlock* header = node->loop_info->GetHeader();
1022 HBasicBlock* preheader = node->loop_info->GetPreHeader();
1023
Aart Bik14a68b42017-06-08 14:06:58 -07001024 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +01001025 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
1026 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -07001027 uint32_t chunk = vector_length_ * unroll;
1028
Aart Bik38a3f212017-10-20 17:02:21 -07001029 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
1030
Aart Bik14a68b42017-06-08 14:06:58 -07001031 // A cleanup loop is needed, at least, for any unknown trip count or
1032 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -07001033 bool needs_cleanup = trip_count == 0 ||
1034 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001035
1036 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -07001037 HPhi* main_phi = nullptr;
1038 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -08001039 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -07001040 vector_header_ = header;
1041 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -08001042
Aart Bikdbbac8f2017-09-01 13:06:08 -07001043 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001044 DataType::Type induc_type = main_phi->GetType();
1045 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
1046 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -07001047
Aart Bik38a3f212017-10-20 17:02:21 -07001048 // Generate the trip count for static or dynamic loop peeling, if needed:
1049 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001050 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001051 if (vector_static_peeling_factor_ != 0) {
1052 // Static loop peeling for SIMD alignment (using the most suitable
1053 // fixed peeling factor found during prior alignment analysis).
1054 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1055 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1056 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1057 // Dynamic loop peeling for SIMD alignment (using the most suitable
1058 // candidate found during prior alignment analysis):
1059 // rem = offset % ALIGN; // adjusted as #elements
1060 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1061 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1062 uint32_t align = GetVectorSizeInBytes() >> shift;
1063 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1064 vector_dynamic_peeling_candidate_->is_string_char_at);
1065 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1066 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1067 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1068 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1069 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1070 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1071 induc_type, graph_->GetConstant(induc_type, align), rem));
1072 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1073 rem, graph_->GetConstant(induc_type, 0)));
1074 ptc = Insert(preheader, new (global_allocator_) HSelect(
1075 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1076 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001077 }
1078
1079 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001080 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001081 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001082 // vtc = stc - (stc - ptc) % chunk;
1083 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001084 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1085 HInstruction* vtc = stc;
1086 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001087 DCHECK(IsPowerOfTwo(chunk));
1088 HInstruction* diff = stc;
1089 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001090 if (trip_count == 0) {
1091 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1092 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1093 }
Aart Bik14a68b42017-06-08 14:06:58 -07001094 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1095 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001096 HInstruction* rem = Insert(
1097 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001098 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001099 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001100 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1101 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001102 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001103
1104 // Generate runtime disambiguation test:
1105 // vtc = a != b ? vtc : 0;
1106 if (vector_runtime_test_a_ != nullptr) {
1107 HInstruction* rt = Insert(
1108 preheader,
1109 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1110 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001111 new (global_allocator_)
1112 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001113 needs_cleanup = true;
1114 }
1115
Aart Bik38a3f212017-10-20 17:02:21 -07001116 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001117 // for ( ; i < ptc; i += 1)
1118 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001119 //
1120 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1121 // moved around during suspend checks, since all analysis was based on
1122 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001123 if (ptc != nullptr) {
1124 vector_mode_ = kSequential;
1125 GenerateNewLoop(node,
1126 block,
1127 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1128 vector_index_,
1129 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001130 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001131 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001132 }
1133
1134 // Generate vector loop, possibly further unrolled:
1135 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001136 // <vectorized-loop-body>
1137 vector_mode_ = kVector;
1138 GenerateNewLoop(node,
1139 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001140 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1141 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001142 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001143 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001144 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001145 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1146
1147 // Generate cleanup loop, if needed:
1148 // for ( ; i < stc; i += 1)
1149 // <loop-body>
1150 if (needs_cleanup) {
1151 vector_mode_ = kSequential;
1152 GenerateNewLoop(node,
1153 block,
1154 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001155 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001156 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001157 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001158 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001159 }
1160
Aart Bik0148de42017-09-05 09:25:01 -07001161 // Link reductions to their final uses.
1162 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1163 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001164 HInstruction* phi = i->first;
1165 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1166 // Deal with regular uses.
1167 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1168 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1169 }
1170 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001171 }
1172 }
1173
Aart Bikf8f5a162017-02-06 15:35:29 -08001174 // Remove the original loop by disconnecting the body block
1175 // and removing all instructions from the header.
1176 block->DisconnectAndDelete();
1177 while (!header->GetFirstInstruction()->IsGoto()) {
1178 header->RemoveInstruction(header->GetFirstInstruction());
1179 }
Aart Bikb29f6842017-07-28 15:58:41 -07001180
Aart Bik14a68b42017-06-08 14:06:58 -07001181 // Update loop hierarchy: the old header now resides in the same outer loop
1182 // as the old preheader. Note that we don't bother putting sequential
1183 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001184 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1185 node->loop_info = vloop;
1186}
1187
1188void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1189 HBasicBlock* block,
1190 HBasicBlock* new_preheader,
1191 HInstruction* lo,
1192 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001193 HInstruction* step,
1194 uint32_t unroll) {
1195 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001196 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001197 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001198 vector_preheader_ = new_preheader,
1199 vector_header_ = vector_preheader_->GetSingleSuccessor();
1200 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001201 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1202 kNoRegNumber,
1203 0,
1204 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001205 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001206 // for (i = lo; i < hi; i += step)
1207 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001208 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1209 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001210 vector_header_->AddInstruction(cond);
1211 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001212 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001213 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001214 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001215 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001216 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001217 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1218 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1219 DCHECK(vectorized_def);
1220 }
1221 // Generate body from the instruction map, but in original program order.
1222 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1223 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1224 auto i = vector_map_->find(it.Current());
1225 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1226 Insert(vector_body_, i->second);
1227 // Deal with instructions that need an environment, such as the scalar intrinsics.
1228 if (i->second->NeedsEnvironment()) {
1229 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1230 }
1231 }
1232 }
Aart Bik0148de42017-09-05 09:25:01 -07001233 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001234 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1235 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001236 }
Aart Bik0148de42017-09-05 09:25:01 -07001237 // Finalize phi inputs for the reductions (if any).
1238 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1239 if (!i->first->IsPhi()) {
1240 DCHECK(i->second->IsPhi());
1241 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1242 }
1243 }
Aart Bikb29f6842017-07-28 15:58:41 -07001244 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001245 phi->AddInput(lo);
1246 phi->AddInput(vector_index_);
1247 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001248}
1249
Aart Bikf8f5a162017-02-06 15:35:29 -08001250bool HLoopOptimization::VectorizeDef(LoopNode* node,
1251 HInstruction* instruction,
1252 bool generate_code) {
1253 // Accept a left-hand-side array base[index] for
1254 // (1) supported vector type,
1255 // (2) loop-invariant base,
1256 // (3) unit stride index,
1257 // (4) vectorizable right-hand-side value.
1258 uint64_t restrictions = kNone;
1259 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001260 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001261 HInstruction* base = instruction->InputAt(0);
1262 HInstruction* index = instruction->InputAt(1);
1263 HInstruction* value = instruction->InputAt(2);
1264 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001265 // For narrow types, explicit type conversion may have been
1266 // optimized way, so set the no hi bits restriction here.
1267 if (DataType::Size(type) <= 2) {
1268 restrictions |= kNoHiBits;
1269 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001270 if (TrySetVectorType(type, &restrictions) &&
1271 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001272 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001273 VectorizeUse(node, value, generate_code, type, restrictions)) {
1274 if (generate_code) {
1275 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001276 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001277 } else {
1278 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1279 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001280 return true;
1281 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001282 return false;
1283 }
Aart Bik0148de42017-09-05 09:25:01 -07001284 // Accept a left-hand-side reduction for
1285 // (1) supported vector type,
1286 // (2) vectorizable right-hand-side value.
1287 auto redit = reductions_->find(instruction);
1288 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001289 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001290 // Recognize SAD idiom or direct reduction.
1291 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1292 (TrySetVectorType(type, &restrictions) &&
1293 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001294 if (generate_code) {
1295 HInstruction* new_red = vector_map_->Get(instruction);
1296 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1297 vector_permanent_map_->Overwrite(redit->second, new_red);
1298 }
1299 return true;
1300 }
1301 return false;
1302 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001303 // Branch back okay.
1304 if (instruction->IsGoto()) {
1305 return true;
1306 }
1307 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1308 // Note that actual uses are inspected during right-hand-side tree traversal.
1309 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1310}
1311
Aart Bikf8f5a162017-02-06 15:35:29 -08001312bool HLoopOptimization::VectorizeUse(LoopNode* node,
1313 HInstruction* instruction,
1314 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001315 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001316 uint64_t restrictions) {
1317 // Accept anything for which code has already been generated.
1318 if (generate_code) {
1319 if (vector_map_->find(instruction) != vector_map_->end()) {
1320 return true;
1321 }
1322 }
1323 // Continue the right-hand-side tree traversal, passing in proper
1324 // types and vector restrictions along the way. During code generation,
1325 // all new nodes are drawn from the global allocator.
1326 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1327 // Accept invariant use, using scalar expansion.
1328 if (generate_code) {
1329 GenerateVecInv(instruction, type);
1330 }
1331 return true;
1332 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001333 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001334 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1335 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001336 return false;
1337 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001338 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001339 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001340 // (2) loop-invariant base,
1341 // (3) unit stride index,
1342 // (4) vectorizable right-hand-side value.
1343 HInstruction* base = instruction->InputAt(0);
1344 HInstruction* index = instruction->InputAt(1);
1345 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001346 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001347 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001348 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001349 if (generate_code) {
1350 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001351 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001352 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001353 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001354 }
1355 return true;
1356 }
Aart Bik0148de42017-09-05 09:25:01 -07001357 } else if (instruction->IsPhi()) {
1358 // Accept particular phi operations.
1359 if (reductions_->find(instruction) != reductions_->end()) {
1360 // Deal with vector restrictions.
1361 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1362 return false;
1363 }
1364 // Accept a reduction.
1365 if (generate_code) {
1366 GenerateVecReductionPhi(instruction->AsPhi());
1367 }
1368 return true;
1369 }
1370 // TODO: accept right-hand-side induction?
1371 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001372 } else if (instruction->IsTypeConversion()) {
1373 // Accept particular type conversions.
1374 HTypeConversion* conversion = instruction->AsTypeConversion();
1375 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001376 DataType::Type from = conversion->GetInputType();
1377 DataType::Type to = conversion->GetResultType();
1378 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001379 uint32_t size_vec = DataType::Size(type);
1380 uint32_t size_from = DataType::Size(from);
1381 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001382 // Accept an integral conversion
1383 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1384 // (1b) widening from at least vector type, and
1385 // (2) vectorizable operand.
1386 if ((size_to < size_from &&
1387 size_to == size_vec &&
1388 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1389 (size_to >= size_from &&
1390 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001391 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001392 if (generate_code) {
1393 if (vector_mode_ == kVector) {
1394 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1395 } else {
1396 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1397 }
1398 }
1399 return true;
1400 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001401 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001402 DCHECK_EQ(to, type);
1403 // Accept int to float conversion for
1404 // (1) supported int,
1405 // (2) vectorizable operand.
1406 if (TrySetVectorType(from, &restrictions) &&
1407 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1408 if (generate_code) {
1409 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1410 }
1411 return true;
1412 }
1413 }
1414 return false;
1415 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1416 // Accept unary operator for vectorizable operand.
1417 HInstruction* opa = instruction->InputAt(0);
1418 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1419 if (generate_code) {
1420 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1421 }
1422 return true;
1423 }
1424 } else if (instruction->IsAdd() || instruction->IsSub() ||
1425 instruction->IsMul() || instruction->IsDiv() ||
1426 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1427 // Deal with vector restrictions.
1428 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1429 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1430 return false;
1431 }
1432 // Accept binary operator for vectorizable operands.
1433 HInstruction* opa = instruction->InputAt(0);
1434 HInstruction* opb = instruction->InputAt(1);
1435 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1436 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1437 if (generate_code) {
1438 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1439 }
1440 return true;
1441 }
1442 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001443 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001444 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1445 return true;
1446 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001447 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001448 HInstruction* opa = instruction->InputAt(0);
1449 HInstruction* opb = instruction->InputAt(1);
1450 HInstruction* r = opa;
1451 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001452 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1453 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1454 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001455 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1456 // Shifts right need extra care to account for higher order bits.
1457 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1458 if (instruction->IsShr() &&
1459 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1460 return false; // reject, unless all operands are sign-extension narrower
1461 } else if (instruction->IsUShr() &&
1462 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1463 return false; // reject, unless all operands are zero-extension narrower
1464 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001465 }
1466 // Accept shift operator for vectorizable/invariant operands.
1467 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001468 DCHECK(r != nullptr);
1469 if (generate_code && vector_mode_ != kVector) { // de-idiom
1470 r = opa;
1471 }
Aart Bik50e20d52017-05-05 14:07:29 -07001472 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001473 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001474 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001475 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001476 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001477 if (0 <= distance && distance < max_distance) {
1478 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001479 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001480 }
1481 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001482 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001483 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001484 } else if (instruction->IsAbs()) {
1485 // Deal with vector restrictions.
1486 HInstruction* opa = instruction->InputAt(0);
1487 HInstruction* r = opa;
1488 bool is_unsigned = false;
1489 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1490 return false;
1491 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1492 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1493 return false; // reject, unless operand is sign-extension narrower
1494 }
1495 // Accept ABS(x) for vectorizable operand.
1496 DCHECK(r != nullptr);
1497 if (generate_code && vector_mode_ != kVector) { // de-idiom
1498 r = opa;
1499 }
1500 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1501 if (generate_code) {
1502 GenerateVecOp(instruction,
1503 vector_map_->Get(r),
1504 nullptr,
1505 HVecOperation::ToProperType(type, is_unsigned));
1506 }
1507 return true;
1508 }
Aart Bik281c6812016-08-26 11:31:48 -07001509 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001510 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001511}
1512
Aart Bik38a3f212017-10-20 17:02:21 -07001513uint32_t HLoopOptimization::GetVectorSizeInBytes() {
Vladimir Markoa0431112018-06-25 09:32:54 +01001514 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001515 case InstructionSet::kArm:
1516 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001517 return 8; // 64-bit SIMD
1518 default:
1519 return 16; // 128-bit SIMD
1520 }
1521}
1522
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001523bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001524 const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
1525 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001526 case InstructionSet::kArm:
1527 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001528 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001529 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001530 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001531 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001532 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001533 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001534 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001535 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001536 case DataType::Type::kUint16:
1537 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001538 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001539 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001540 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001541 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001542 return TrySetVectorLength(2);
1543 default:
1544 break;
1545 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001546 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001547 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001548 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001549 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001550 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001551 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001552 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001553 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001554 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001555 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001556 case DataType::Type::kUint16:
1557 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001558 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001559 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001560 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001561 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001562 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001563 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001564 *restrictions |= kNoDiv | kNoMul;
Aart Bikf8f5a162017-02-06 15:35:29 -08001565 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001566 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001567 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001568 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001569 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001570 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001571 return TrySetVectorLength(2);
1572 default:
1573 return false;
1574 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001575 case InstructionSet::kX86:
1576 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001577 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001578 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1579 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001580 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001581 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001582 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001583 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001584 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001585 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001586 case DataType::Type::kUint16:
1587 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001588 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001589 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001590 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001591 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001592 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001593 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001594 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001595 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001596 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001597 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001598 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001599 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001600 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001601 return TrySetVectorLength(2);
1602 default:
1603 break;
1604 } // switch type
1605 }
1606 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001607 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001608 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1609 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001610 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001611 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001612 case DataType::Type::kInt8:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001613 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001614 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001615 case DataType::Type::kUint16:
1616 case DataType::Type::kInt16:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001617 *restrictions |= kNoDiv | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001618 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001619 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001620 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001621 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001622 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001623 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001624 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001625 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001626 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001627 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001628 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001629 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001630 return TrySetVectorLength(2);
1631 default:
1632 break;
1633 } // switch type
1634 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001635 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001636 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001637 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1638 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001639 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001640 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001641 case DataType::Type::kInt8:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001642 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001643 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001644 case DataType::Type::kUint16:
1645 case DataType::Type::kInt16:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001646 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001647 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001648 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001649 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001650 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001651 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001652 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001653 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001654 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001655 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001656 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001657 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001658 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001659 return TrySetVectorLength(2);
1660 default:
1661 break;
1662 } // switch type
1663 }
1664 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001665 default:
1666 return false;
1667 } // switch instruction set
1668}
1669
1670bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1671 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1672 // First time set?
1673 if (vector_length_ == 0) {
1674 vector_length_ = length;
1675 }
1676 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1677 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1678 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1679 return vector_length_ == length;
1680}
1681
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001682void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001683 if (vector_map_->find(org) == vector_map_->end()) {
1684 // In scalar code, just use a self pass-through for scalar invariants
1685 // (viz. expression remains itself).
1686 if (vector_mode_ == kSequential) {
1687 vector_map_->Put(org, org);
1688 return;
1689 }
1690 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001691 HInstruction* vector = nullptr;
1692 auto it = vector_permanent_map_->find(org);
1693 if (it != vector_permanent_map_->end()) {
1694 vector = it->second; // reuse during unrolling
1695 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001696 // Generates ReplicateScalar( (optional_type_conv) org ).
1697 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001698 DataType::Type input_type = input->GetType();
1699 if (type != input_type && (type == DataType::Type::kInt64 ||
1700 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001701 input = Insert(vector_preheader_,
1702 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1703 }
1704 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001705 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001706 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1707 }
1708 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001709 }
1710}
1711
1712void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1713 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001714 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001715 int64_t value = 0;
1716 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001717 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001718 if (org->IsPhi()) {
1719 Insert(vector_body_, subscript); // lacks layout placeholder
1720 }
1721 }
1722 vector_map_->Put(org, subscript);
1723 }
1724}
1725
1726void HLoopOptimization::GenerateVecMem(HInstruction* org,
1727 HInstruction* opa,
1728 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001729 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001730 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001731 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001732 HInstruction* vector = nullptr;
1733 if (vector_mode_ == kVector) {
1734 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001735 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001736 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001737 if (opb != nullptr) {
1738 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001739 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001740 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001741 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001742 vector = new (global_allocator_) HVecLoad(global_allocator_,
1743 base,
1744 opa,
1745 type,
1746 org->GetSideEffects(),
1747 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001748 is_string_char_at,
1749 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001750 }
Aart Bik38a3f212017-10-20 17:02:21 -07001751 // Known (forced/adjusted/original) alignment?
1752 if (vector_dynamic_peeling_candidate_ != nullptr) {
1753 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1754 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1755 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1756 vector->AsVecMemoryOperation()->SetAlignment( // forced
1757 Alignment(GetVectorSizeInBytes(), 0));
1758 }
1759 } else {
1760 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1761 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001762 }
1763 } else {
1764 // Scalar store or load.
1765 DCHECK(vector_mode_ == kSequential);
1766 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001767 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001768 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001769 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001770 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001771 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1772 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001773 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001774 }
1775 }
1776 vector_map_->Put(org, vector);
1777}
1778
Aart Bik0148de42017-09-05 09:25:01 -07001779void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1780 DCHECK(reductions_->find(phi) != reductions_->end());
1781 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1782 HInstruction* vector = nullptr;
1783 if (vector_mode_ == kSequential) {
1784 HPhi* new_phi = new (global_allocator_) HPhi(
1785 global_allocator_, kNoRegNumber, 0, phi->GetType());
1786 vector_header_->AddPhi(new_phi);
1787 vector = new_phi;
1788 } else {
1789 // Link vector reduction back to prior unrolled update, or a first phi.
1790 auto it = vector_permanent_map_->find(phi);
1791 if (it != vector_permanent_map_->end()) {
1792 vector = it->second;
1793 } else {
1794 HPhi* new_phi = new (global_allocator_) HPhi(
1795 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1796 vector_header_->AddPhi(new_phi);
1797 vector = new_phi;
1798 }
1799 }
1800 vector_map_->Put(phi, vector);
1801}
1802
1803void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1804 HInstruction* new_phi = vector_map_->Get(phi);
1805 HInstruction* new_init = reductions_->Get(phi);
1806 HInstruction* new_red = vector_map_->Get(reduction);
1807 // Link unrolled vector loop back to new phi.
1808 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1809 DCHECK(new_phi->IsVecOperation());
1810 }
1811 // Prepare the new initialization.
1812 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001813 // Generate a [initial, 0, .., 0] vector for add or
1814 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001815 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001816 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001817 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001818 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001819 if (kind == HVecReduce::ReductionKind::kSum) {
1820 new_init = Insert(vector_preheader_,
1821 new (global_allocator_) HVecSetScalars(global_allocator_,
1822 &new_init,
1823 type,
1824 vector_length,
1825 1,
1826 kNoDexPc));
1827 } else {
1828 new_init = Insert(vector_preheader_,
1829 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1830 new_init,
1831 type,
1832 vector_length,
1833 kNoDexPc));
1834 }
Aart Bik0148de42017-09-05 09:25:01 -07001835 } else {
1836 new_init = ReduceAndExtractIfNeeded(new_init);
1837 }
1838 // Set the phi inputs.
1839 DCHECK(new_phi->IsPhi());
1840 new_phi->AsPhi()->AddInput(new_init);
1841 new_phi->AsPhi()->AddInput(new_red);
1842 // New feed value for next phi (safe mutation in iteration).
1843 reductions_->find(phi)->second = new_phi;
1844}
1845
1846HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1847 if (instruction->IsPhi()) {
1848 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001849 if (HVecOperation::ReturnsSIMDValue(input)) {
1850 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001851 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001852 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001853 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001854 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001855 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1856 // Generate a vector reduction and scalar extract
1857 // x = REDUCE( [x_1, .., x_n] )
1858 // y = x_1
1859 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001860 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001861 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001862 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1863 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001864 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001865 exit->InsertInstructionAfter(instruction, reduce);
1866 }
1867 }
1868 return instruction;
1869}
1870
Aart Bikf8f5a162017-02-06 15:35:29 -08001871#define GENERATE_VEC(x, y) \
1872 if (vector_mode_ == kVector) { \
1873 vector = (x); \
1874 } else { \
1875 DCHECK(vector_mode_ == kSequential); \
1876 vector = (y); \
1877 } \
1878 break;
1879
1880void HLoopOptimization::GenerateVecOp(HInstruction* org,
1881 HInstruction* opa,
1882 HInstruction* opb,
Aart Bik3f08e9b2018-05-01 13:42:03 -07001883 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001884 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001885 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001886 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001887 switch (org->GetKind()) {
1888 case HInstruction::kNeg:
1889 DCHECK(opb == nullptr);
1890 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001891 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1892 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001893 case HInstruction::kNot:
1894 DCHECK(opb == nullptr);
1895 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001896 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1897 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001898 case HInstruction::kBooleanNot:
1899 DCHECK(opb == nullptr);
1900 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001901 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1902 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001903 case HInstruction::kTypeConversion:
1904 DCHECK(opb == nullptr);
1905 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001906 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1907 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001908 case HInstruction::kAdd:
1909 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001910 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1911 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001912 case HInstruction::kSub:
1913 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001914 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1915 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001916 case HInstruction::kMul:
1917 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001918 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1919 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001920 case HInstruction::kDiv:
1921 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001922 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1923 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001924 case HInstruction::kAnd:
1925 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001926 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1927 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001928 case HInstruction::kOr:
1929 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001930 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1931 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001932 case HInstruction::kXor:
1933 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001934 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1935 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001936 case HInstruction::kShl:
1937 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001938 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1939 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001940 case HInstruction::kShr:
1941 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001942 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1943 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001944 case HInstruction::kUShr:
1945 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001946 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1947 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001948 case HInstruction::kAbs:
1949 DCHECK(opb == nullptr);
1950 GENERATE_VEC(
1951 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1952 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001953 default:
1954 break;
1955 } // switch
1956 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1957 vector_map_->Put(org, vector);
1958}
1959
1960#undef GENERATE_VEC
1961
1962//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001963// Vectorization idioms.
1964//
1965
1966// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001967// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1968// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001969// Provided that the operands are promoted to a wider form to do the arithmetic and
1970// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1971// implementation that operates directly in narrower form (plus one extra bit).
1972// TODO: current version recognizes implicit byte/short/char widening only;
1973// explicit widening from int to long could be added later.
1974bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1975 HInstruction* instruction,
1976 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001977 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001978 uint64_t restrictions) {
1979 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001980 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001981 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001982 if ((instruction->IsShr() ||
1983 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001984 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001985 // Test for (a + b + c) >> 1 for optional constant c.
1986 HInstruction* a = nullptr;
1987 HInstruction* b = nullptr;
1988 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001989 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07001990 // Accept c == 1 (rounded) or c == 0 (not rounded).
1991 bool is_rounded = false;
1992 if (c == 1) {
1993 is_rounded = true;
1994 } else if (c != 0) {
1995 return false;
1996 }
1997 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001998 HInstruction* r = nullptr;
1999 HInstruction* s = nullptr;
2000 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07002001 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07002002 return false;
2003 }
2004 // Deal with vector restrictions.
2005 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
2006 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
2007 return false;
2008 }
2009 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
2010 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002011 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07002012 if (generate_code && vector_mode_ != kVector) { // de-idiom
2013 r = instruction->InputAt(0);
2014 s = instruction->InputAt(1);
2015 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07002016 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
2017 VectorizeUse(node, s, generate_code, type, restrictions)) {
2018 if (generate_code) {
2019 if (vector_mode_ == kVector) {
2020 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
2021 global_allocator_,
2022 vector_map_->Get(r),
2023 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08002024 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07002025 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01002026 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07002027 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07002028 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002029 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07002030 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07002031 }
2032 }
2033 return true;
2034 }
2035 }
2036 }
2037 return false;
2038}
2039
Aart Bikdbbac8f2017-09-01 13:06:08 -07002040// Method recognizes the following idiom:
2041// q += ABS(a - b) for signed operands a, b
2042// Provided that the operands have the same type or are promoted to a wider form.
2043// Since this may involve a vector length change, the idiom is handled by going directly
2044// to a sad-accumulate node (rather than relying combining finer grained nodes later).
2045// TODO: unsigned SAD too?
2046bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
2047 HInstruction* instruction,
2048 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002049 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002050 uint64_t restrictions) {
2051 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2052 // are done in the same precision (either int or long).
2053 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002054 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002055 return false;
2056 }
2057 HInstruction* q = instruction->InputAt(0);
2058 HInstruction* v = instruction->InputAt(1);
2059 HInstruction* a = nullptr;
2060 HInstruction* b = nullptr;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002061 if (v->IsAbs() &&
2062 v->GetType() == reduction_type &&
2063 IsSubConst2(graph_, v->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2064 DCHECK(a != nullptr && b != nullptr);
2065 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002066 return false;
2067 }
2068 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2069 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002070 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002071 HInstruction* r = a;
2072 HInstruction* s = b;
2073 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002074 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002075 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2076 sub_type = b->GetType();
2077 }
2078 if (a->IsTypeConversion() &&
2079 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2080 sub_type = a->InputAt(0)->GetType();
2081 }
2082 if (b->IsTypeConversion() &&
2083 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2084 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002085 }
2086 if (reduction_type != sub_type &&
2087 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2088 return false;
2089 }
2090 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002091 if (!TrySetVectorType(sub_type, &restrictions) ||
2092 HasVectorRestrictions(restrictions, kNoSAD) ||
2093 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002094 return false;
2095 }
2096 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2097 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002098 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002099 if (generate_code && vector_mode_ != kVector) { // de-idiom
2100 r = s = v->InputAt(0);
2101 }
2102 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2103 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2104 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2105 if (generate_code) {
2106 if (vector_mode_ == kVector) {
2107 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2108 global_allocator_,
2109 vector_map_->Get(q),
2110 vector_map_->Get(r),
2111 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002112 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002113 GetOtherVL(reduction_type, sub_type, vector_length_),
2114 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002115 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2116 } else {
2117 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2118 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2119 }
2120 }
2121 return true;
2122 }
2123 return false;
2124}
2125
Aart Bikf3e61ee2017-04-12 17:09:20 -07002126//
Aart Bik14a68b42017-06-08 14:06:58 -07002127// Vectorization heuristics.
2128//
2129
Aart Bik38a3f212017-10-20 17:02:21 -07002130Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2131 DataType::Type type,
2132 bool is_string_char_at,
2133 uint32_t peeling) {
2134 // Combine the alignment and hidden offset that is guaranteed by
2135 // the Android runtime with a known starting index adjusted as bytes.
2136 int64_t value = 0;
2137 if (IsInt64AndGet(offset, /*out*/ &value)) {
2138 uint32_t start_offset =
2139 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2140 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2141 }
2142 // Otherwise, the Android runtime guarantees at least natural alignment.
2143 return Alignment(DataType::Size(type), 0);
2144}
2145
2146void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2147 const ArrayReference* peeling_candidate) {
2148 // Current heuristic: pick the best static loop peeling factor, if any,
2149 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2150 uint32_t max_vote = 0;
2151 for (int32_t i = 0; i < 16; i++) {
2152 if (peeling_votes[i] > max_vote) {
2153 max_vote = peeling_votes[i];
2154 vector_static_peeling_factor_ = i;
2155 }
2156 }
2157 if (max_vote == 0) {
2158 vector_dynamic_peeling_candidate_ = peeling_candidate;
2159 }
2160}
2161
2162uint32_t HLoopOptimization::MaxNumberPeeled() {
2163 if (vector_dynamic_peeling_candidate_ != nullptr) {
2164 return vector_length_ - 1u; // worst-case
2165 }
2166 return vector_static_peeling_factor_; // known exactly
2167}
2168
Aart Bik14a68b42017-06-08 14:06:58 -07002169bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002170 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002171 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002172 // TODO: trip count is really unsigned entity, provided the guarding test
2173 // is satisfied; deal with this more carefully later
2174 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002175 if (vector_length_ == 0) {
2176 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002177 } else if (trip_count < 0) {
2178 return false; // guard against non-taken/large
2179 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002180 return false; // insufficient iterations
2181 }
2182 return true;
2183}
2184
Aart Bik14a68b42017-06-08 14:06:58 -07002185//
Aart Bikf8f5a162017-02-06 15:35:29 -08002186// Helpers.
2187//
2188
2189bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002190 // Start with empty phi induction.
2191 iset_->clear();
2192
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002193 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2194 // smart enough to follow strongly connected components (and it's probably not worth
2195 // it to make it so). See b/33775412.
2196 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2197 return false;
2198 }
Aart Bikb29f6842017-07-28 15:58:41 -07002199
2200 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002201 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2202 if (set != nullptr) {
2203 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002204 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002205 // each instruction is removable and, when restrict uses are requested, other than for phi,
2206 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002207 if (!i->IsInBlock()) {
2208 continue;
2209 } else if (!i->IsRemovable()) {
2210 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002211 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002212 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002213 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2214 if (set->find(use.GetUser()) == set->end()) {
2215 return false;
2216 }
2217 }
2218 }
Aart Bike3dedc52016-11-02 17:50:27 -07002219 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002220 }
Aart Bikcc42be02016-10-20 16:14:16 -07002221 return true;
2222 }
2223 return false;
2224}
2225
Aart Bikb29f6842017-07-28 15:58:41 -07002226bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002227 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002228 // Only unclassified phi cycles are candidates for reductions.
2229 if (induction_range_.IsClassified(phi)) {
2230 return false;
2231 }
2232 // Accept operations like x = x + .., provided that the phi and the reduction are
2233 // used exactly once inside the loop, and by each other.
2234 HInputsRef inputs = phi->GetInputs();
2235 if (inputs.size() == 2) {
2236 HInstruction* reduction = inputs[1];
2237 if (HasReductionFormat(reduction, phi)) {
2238 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002239 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002240 bool single_use_inside_loop =
2241 // Reduction update only used by phi.
2242 reduction->GetUses().HasExactlyOneElement() &&
2243 !reduction->HasEnvironmentUses() &&
2244 // Reduction update is only use of phi inside the loop.
2245 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2246 iset_->size() == 1;
2247 iset_->clear(); // leave the way you found it
2248 if (single_use_inside_loop) {
2249 // Link reduction back, and start recording feed value.
2250 reductions_->Put(reduction, phi);
2251 reductions_->Put(phi, phi->InputAt(0));
2252 return true;
2253 }
2254 }
2255 }
2256 return false;
2257}
2258
2259bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2260 // Start with empty phi induction and reductions.
2261 iset_->clear();
2262 reductions_->clear();
2263
2264 // Scan the phis to find the following (the induction structure has already
2265 // been optimized, so we don't need to worry about trivial cases):
2266 // (1) optional reductions in loop,
2267 // (2) the main induction, used in loop control.
2268 HPhi* phi = nullptr;
2269 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2270 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2271 continue;
2272 } else if (phi == nullptr) {
2273 // Found the first candidate for main induction.
2274 phi = it.Current()->AsPhi();
2275 } else {
2276 return false;
2277 }
2278 }
2279
2280 // Then test for a typical loopheader:
2281 // s: SuspendCheck
2282 // c: Condition(phi, bound)
2283 // i: If(c)
2284 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002285 HInstruction* s = block->GetFirstInstruction();
2286 if (s != nullptr && s->IsSuspendCheck()) {
2287 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002288 if (c != nullptr &&
2289 c->IsCondition() &&
2290 c->GetUses().HasExactlyOneElement() && // only used for termination
2291 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002292 HInstruction* i = c->GetNext();
2293 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2294 iset_->insert(c);
2295 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002296 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002297 return true;
2298 }
2299 }
2300 }
2301 }
2302 return false;
2303}
2304
2305bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002306 if (!block->GetPhis().IsEmpty()) {
2307 return false;
2308 }
2309 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2310 HInstruction* instruction = it.Current();
2311 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2312 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002313 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002314 }
2315 return true;
2316}
2317
2318bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2319 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002320 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002321 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2322 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2323 return true;
2324 }
Aart Bikcc42be02016-10-20 16:14:16 -07002325 }
2326 return false;
2327}
2328
Aart Bik482095d2016-10-10 15:39:10 -07002329bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002330 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002331 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002332 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002333 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002334 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2335 HInstruction* user = use.GetUser();
2336 if (iset_->find(user) == iset_->end()) { // not excluded?
2337 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002338 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002339 // If collect_loop_uses is set, simply keep adding those uses to the set.
2340 // Otherwise, reject uses inside the loop that were not already in the set.
2341 if (collect_loop_uses) {
2342 iset_->insert(user);
2343 continue;
2344 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002345 return false;
2346 }
2347 ++*use_count;
2348 }
2349 }
2350 return true;
2351}
2352
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002353bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2354 HInstruction* instruction,
2355 HBasicBlock* block) {
2356 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002357 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002358 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002359 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002360 const HUseList<HInstruction*>& uses = instruction->GetUses();
2361 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2362 HInstruction* user = it->GetUser();
2363 size_t index = it->GetIndex();
2364 ++it; // increment before replacing
2365 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002366 if (kIsDebugBuild) {
2367 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2368 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2369 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2370 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002371 user->ReplaceInput(replacement, index);
2372 induction_range_.Replace(user, instruction, replacement); // update induction
2373 }
2374 }
Aart Bikb29f6842017-07-28 15:58:41 -07002375 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002376 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2377 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2378 HEnvironment* user = it->GetUser();
2379 size_t index = it->GetIndex();
2380 ++it; // increment before replacing
2381 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002382 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002383 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002384 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2385 user->RemoveAsUserOfInput(index);
2386 user->SetRawEnvAt(index, replacement);
2387 replacement->AddEnvUseAt(user, index);
2388 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002389 }
2390 }
Aart Bik807868e2016-11-03 17:51:43 -07002391 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002392 }
Aart Bik807868e2016-11-03 17:51:43 -07002393 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002394}
2395
Aart Bikf8f5a162017-02-06 15:35:29 -08002396bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2397 HInstruction* instruction,
2398 HBasicBlock* block,
2399 bool collect_loop_uses) {
2400 // Assigning the last value is always successful if there are no uses.
2401 // Otherwise, it succeeds in a no early-exit loop by generating the
2402 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002403 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002404 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2405 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002406 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002407}
2408
Aart Bik6b69e0a2017-01-11 10:20:43 -08002409void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2410 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2411 HInstruction* instruction = i.Current();
2412 if (instruction->IsDeadAndRemovable()) {
2413 simplified_ = true;
2414 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2415 }
2416 }
2417}
2418
Aart Bik14a68b42017-06-08 14:06:58 -07002419bool HLoopOptimization::CanRemoveCycle() {
2420 for (HInstruction* i : *iset_) {
2421 // We can never remove instructions that have environment
2422 // uses when we compile 'debuggable'.
2423 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2424 return false;
2425 }
2426 // A deoptimization should never have an environment input removed.
2427 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2428 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2429 return false;
2430 }
2431 }
2432 }
2433 return true;
2434}
2435
Aart Bik281c6812016-08-26 11:31:48 -07002436} // namespace art