blob: 440cd3351eaf747b428ed03f2527f928e268a8b4 [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
Aart Bik281c6812016-08-26 11:31:48 -0700425//
Aart Bikb29f6842017-07-28 15:58:41 -0700426// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700427//
428
429HLoopOptimization::HLoopOptimization(HGraph* graph,
Vladimir Markoa0431112018-06-25 09:32:54 +0100430 const CompilerOptions* compiler_options,
Aart Bikb92cc332017-09-06 15:53:17 -0700431 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800432 OptimizingCompilerStats* stats,
433 const char* name)
434 : HOptimization(graph, name, stats),
Vladimir Markoa0431112018-06-25 09:32:54 +0100435 compiler_options_(compiler_options),
Aart Bik281c6812016-08-26 11:31:48 -0700436 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700437 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100438 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700439 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700440 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700441 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700442 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800443 simplified_(false),
444 vector_length_(0),
445 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700446 vector_static_peeling_factor_(0),
447 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700448 vector_runtime_test_a_(nullptr),
449 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700450 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100451 vector_permanent_map_(nullptr),
452 vector_mode_(kSequential),
453 vector_preheader_(nullptr),
454 vector_header_(nullptr),
455 vector_body_(nullptr),
Artem Serov121f2032017-10-23 19:19:06 +0100456 vector_index_(nullptr),
Vladimir Markoa0431112018-06-25 09:32:54 +0100457 arch_loop_helper_(ArchNoOptsLoopHelper::Create(compiler_options_ != nullptr
458 ? compiler_options_->GetInstructionSet()
Artem Serov121f2032017-10-23 19:19:06 +0100459 : InstructionSet::kNone,
460 global_allocator_)) {
Aart Bik281c6812016-08-26 11:31:48 -0700461}
462
Aart Bik24773202018-04-26 10:28:51 -0700463bool HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800464 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700465 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800466 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik24773202018-04-26 10:28:51 -0700467 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700468 }
469
Vladimir Markoca6fff82017-10-03 14:49:14 +0100470 // Phase-local allocator.
471 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700472 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100473
Aart Bik96202302016-10-04 17:33:56 -0700474 // Perform loop optimizations.
Aart Bik24773202018-04-26 10:28:51 -0700475 bool didLoopOpt = LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800476 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800477 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800478 }
479
Aart Bik96202302016-10-04 17:33:56 -0700480 // Detach.
481 loop_allocator_ = nullptr;
482 last_loop_ = top_loop_ = nullptr;
Aart Bik24773202018-04-26 10:28:51 -0700483
484 return didLoopOpt;
Aart Bik96202302016-10-04 17:33:56 -0700485}
486
Aart Bikb29f6842017-07-28 15:58:41 -0700487//
488// Loop setup and traversal.
489//
490
Aart Bik24773202018-04-26 10:28:51 -0700491bool HLoopOptimization::LocalRun() {
492 bool didLoopOpt = false;
Aart Bik96202302016-10-04 17:33:56 -0700493 // Build the linear order using the phase-local allocator. This step enables building
494 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100495 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
496 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700497
Aart Bik281c6812016-08-26 11:31:48 -0700498 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700499 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700500 if (block->IsLoopHeader()) {
501 AddLoop(block->GetLoopInformation());
502 }
503 }
Aart Bik96202302016-10-04 17:33:56 -0700504
Aart Bik8c4a8542016-10-06 11:36:57 -0700505 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800506 // temporary data structures using the phase-local allocator. All new HIR
507 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700508 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100509 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
510 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700511 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100512 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
513 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800514 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100515 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700516 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800517 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700518 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700519 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800520 vector_refs_ = &refs;
521 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700522 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800523 // Traverse.
Aart Bik24773202018-04-26 10:28:51 -0700524 didLoopOpt = TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800525 // Detach.
526 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700527 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800528 vector_refs_ = nullptr;
529 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700530 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700531 }
Aart Bik24773202018-04-26 10:28:51 -0700532 return didLoopOpt;
Aart Bik281c6812016-08-26 11:31:48 -0700533}
534
535void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
536 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800537 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700538 if (last_loop_ == nullptr) {
539 // First loop.
540 DCHECK(top_loop_ == nullptr);
541 last_loop_ = top_loop_ = node;
542 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
543 // Inner loop.
544 node->outer = last_loop_;
545 DCHECK(last_loop_->inner == nullptr);
546 last_loop_ = last_loop_->inner = node;
547 } else {
548 // Subsequent loop.
549 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
550 last_loop_ = last_loop_->outer;
551 }
552 node->outer = last_loop_->outer;
553 node->previous = last_loop_;
554 DCHECK(last_loop_->next == nullptr);
555 last_loop_ = last_loop_->next = node;
556 }
557}
558
559void HLoopOptimization::RemoveLoop(LoopNode* node) {
560 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700561 DCHECK(node->inner == nullptr);
562 if (node->previous != nullptr) {
563 // Within sequence.
564 node->previous->next = node->next;
565 if (node->next != nullptr) {
566 node->next->previous = node->previous;
567 }
568 } else {
569 // First of sequence.
570 if (node->outer != nullptr) {
571 node->outer->inner = node->next;
572 } else {
573 top_loop_ = node->next;
574 }
575 if (node->next != nullptr) {
576 node->next->outer = node->outer;
577 node->next->previous = nullptr;
578 }
579 }
Aart Bik281c6812016-08-26 11:31:48 -0700580}
581
Aart Bikb29f6842017-07-28 15:58:41 -0700582bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
583 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700584 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700585 // Visit inner loops first. Recompute induction information for this
586 // loop if the induction of any inner loop has changed.
587 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700588 induction_range_.ReVisit(node->loop_info);
Aart Bika8360cd2018-05-02 16:07:51 -0700589 changed = true;
Aart Bik482095d2016-10-10 15:39:10 -0700590 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800591 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800592 // Note that since each simplification consists of eliminating code (without
593 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800594 do {
595 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800596 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800597 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700598 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800599 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800600 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700601 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700602 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700603 }
Aart Bik281c6812016-08-26 11:31:48 -0700604 }
Aart Bikb29f6842017-07-28 15:58:41 -0700605 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700606}
607
Aart Bikf8f5a162017-02-06 15:35:29 -0800608//
609// Optimization.
610//
611
Aart Bik281c6812016-08-26 11:31:48 -0700612void HLoopOptimization::SimplifyInduction(LoopNode* node) {
613 HBasicBlock* header = node->loop_info->GetHeader();
614 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700615 // Scan the phis in the header to find opportunities to simplify an induction
616 // cycle that is only used outside the loop. Replace these uses, if any, with
617 // the last value and remove the induction cycle.
618 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
619 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700620 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
621 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800622 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
623 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700624 // Note that it's ok to have replaced uses after the loop with the last value, without
625 // being able to remove the cycle. Environment uses (which are the reason we may not be
626 // able to remove the cycle) within the loop will still hold the right value. We must
627 // have tried first, however, to replace outside uses.
628 if (CanRemoveCycle()) {
629 simplified_ = true;
630 for (HInstruction* i : *iset_) {
631 RemoveFromCycle(i);
632 }
633 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700634 }
Aart Bik482095d2016-10-10 15:39:10 -0700635 }
636 }
637}
638
639void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800640 // Iterate over all basic blocks in the loop-body.
641 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
642 HBasicBlock* block = it.Current();
643 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800644 RemoveDeadInstructions(block->GetPhis());
645 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800646 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800647 if (block->GetPredecessors().size() == 1 &&
648 block->GetSuccessors().size() == 1 &&
649 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800650 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800651 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800652 } else if (block->GetSuccessors().size() == 2) {
653 // Trivial if block can be bypassed to either branch.
654 HBasicBlock* succ0 = block->GetSuccessors()[0];
655 HBasicBlock* succ1 = block->GetSuccessors()[1];
656 HBasicBlock* meet0 = nullptr;
657 HBasicBlock* meet1 = nullptr;
658 if (succ0 != succ1 &&
659 IsGotoBlock(succ0, &meet0) &&
660 IsGotoBlock(succ1, &meet1) &&
661 meet0 == meet1 && // meets again
662 meet0 != block && // no self-loop
663 meet0->GetPhis().IsEmpty()) { // not used for merging
664 simplified_ = true;
665 succ0->DisconnectAndDelete();
666 if (block->Dominates(meet0)) {
667 block->RemoveDominatedBlock(meet0);
668 succ1->AddDominatedBlock(meet0);
669 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700670 }
Aart Bik482095d2016-10-10 15:39:10 -0700671 }
Aart Bik281c6812016-08-26 11:31:48 -0700672 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800673 }
Aart Bik281c6812016-08-26 11:31:48 -0700674}
675
Artem Serov121f2032017-10-23 19:19:06 +0100676bool HLoopOptimization::TryOptimizeInnerLoopFinite(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700677 HBasicBlock* header = node->loop_info->GetHeader();
678 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700679 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800680 int64_t trip_count = 0;
681 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700682 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700683 }
Aart Bik281c6812016-08-26 11:31:48 -0700684 // Ensure there is only a single loop-body (besides the header).
685 HBasicBlock* body = nullptr;
686 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
687 if (it.Current() != header) {
688 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700689 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700690 }
691 body = it.Current();
692 }
693 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700694 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700695 // Ensure there is only a single exit point.
696 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700697 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700698 }
699 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
700 ? header->GetSuccessors()[1]
701 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700702 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700703 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700704 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700705 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800706 // Detect either an empty loop (no side effects other than plain iteration) or
707 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
708 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700709 HPhi* main_phi = nullptr;
710 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800711 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700712 if (reductions_->empty() && // TODO: possible with some effort
713 (is_empty || trip_count == 1) &&
714 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800715 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800716 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700717 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800718 preheader->MergeInstructionsWith(body);
719 }
720 body->DisconnectAndDelete();
721 exit->RemovePredecessor(header);
722 header->RemoveSuccessor(exit);
723 header->RemoveDominatedBlock(exit);
724 header->DisconnectAndDelete();
725 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800726 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800727 preheader->AddDominatedBlock(exit);
728 exit->SetDominator(preheader);
729 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700730 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800731 }
732 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800733 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700734 if (kEnableVectorization &&
735 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700736 ShouldVectorize(node, body, trip_count) &&
737 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
738 Vectorize(node, body, exit, trip_count);
739 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700740 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700741 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800742 }
Aart Bikb29f6842017-07-28 15:58:41 -0700743 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800744}
745
Artem Serov121f2032017-10-23 19:19:06 +0100746bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Artem Serov0e329082018-06-12 10:23:27 +0100747 return TryOptimizeInnerLoopFinite(node) || TryPeelingAndUnrolling(node);
Artem Serov121f2032017-10-23 19:19:06 +0100748}
749
Artem Serov121f2032017-10-23 19:19:06 +0100750
Artem Serov121f2032017-10-23 19:19:06 +0100751
752//
Artem Serov0e329082018-06-12 10:23:27 +0100753// Scalar loop peeling and unrolling: generic part methods.
Artem Serov121f2032017-10-23 19:19:06 +0100754//
755
Artem Serov0e329082018-06-12 10:23:27 +0100756bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopAnalysisInfo* analysis_info,
757 bool generate_code) {
758 if (analysis_info->GetNumberOfExits() > 1) {
Artem Serov121f2032017-10-23 19:19:06 +0100759 return false;
760 }
761
Artem Serov0e329082018-06-12 10:23:27 +0100762 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(analysis_info);
763 if (unrolling_factor == LoopAnalysisInfo::kNoUnrollingFactor) {
Artem Serov121f2032017-10-23 19:19:06 +0100764 return false;
765 }
766
Artem Serov0e329082018-06-12 10:23:27 +0100767 if (generate_code) {
768 // TODO: support other unrolling factors.
769 DCHECK_EQ(unrolling_factor, 2u);
770
771 // Perform unrolling.
772 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
773 PeelUnrollSimpleHelper helper(loop_info);
774 helper.DoUnrolling();
775
776 // Remove the redundant loop check after unrolling.
777 HIf* copy_hif =
778 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
779 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
780 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
Artem Serov121f2032017-10-23 19:19:06 +0100781 }
Artem Serov121f2032017-10-23 19:19:06 +0100782 return true;
783}
784
Artem Serov0e329082018-06-12 10:23:27 +0100785bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopAnalysisInfo* analysis_info,
786 bool generate_code) {
787 HLoopInformation* loop_info = analysis_info->GetLoopInfo();
Artem Serov72411e62017-10-19 16:18:07 +0100788 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
789 return false;
790 }
791
Artem Serov0e329082018-06-12 10:23:27 +0100792 if (analysis_info->GetNumberOfInvariantExits() == 0) {
Artem Serov72411e62017-10-19 16:18:07 +0100793 return false;
794 }
795
Artem Serov0e329082018-06-12 10:23:27 +0100796 if (generate_code) {
797 // Perform peeling.
798 PeelUnrollSimpleHelper helper(loop_info);
799 helper.DoPeeling();
Artem Serov72411e62017-10-19 16:18:07 +0100800
Artem Serov0e329082018-06-12 10:23:27 +0100801 // Statically evaluate loop check after peeling for loop invariant condition.
802 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
803 for (auto entry : *hir_map) {
804 HInstruction* copy = entry.second;
805 if (copy->IsIf()) {
806 TryToEvaluateIfCondition(copy->AsIf(), graph_);
807 }
Artem Serov72411e62017-10-19 16:18:07 +0100808 }
809 }
810
811 return true;
812}
813
Artem Serov0e329082018-06-12 10:23:27 +0100814bool HLoopOptimization::TryPeelingAndUnrolling(LoopNode* node) {
815 // Don't run peeling/unrolling if compiler_options_ is nullptr (i.e., running under tests)
816 // as InstructionSet is needed.
817 if (compiler_options_ == nullptr) {
818 return false;
819 }
820
821 HLoopInformation* loop_info = node->loop_info;
822 int64_t trip_count = LoopAnalysis::GetLoopTripCount(loop_info, &induction_range_);
823 LoopAnalysisInfo analysis_info(loop_info);
824 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &analysis_info, trip_count);
825
826 if (analysis_info.HasInstructionsPreventingScalarOpts() ||
827 arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&analysis_info)) {
828 return false;
829 }
830
831 if (!TryPeelingForLoopInvariantExitsElimination(&analysis_info, /*generate_code*/ false) &&
832 !TryUnrollingForBranchPenaltyReduction(&analysis_info, /*generate_code*/ false)) {
833 return false;
834 }
835
836 // Run 'IsLoopClonable' the last as it might be time-consuming.
837 if (!PeelUnrollHelper::IsLoopClonable(loop_info)) {
838 return false;
839 }
840
841 return TryPeelingForLoopInvariantExitsElimination(&analysis_info) ||
842 TryUnrollingForBranchPenaltyReduction(&analysis_info);
843}
844
Aart Bikf8f5a162017-02-06 15:35:29 -0800845//
846// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
847// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
848// Intel Press, June, 2004 (http://www.aartbik.com/).
849//
850
Aart Bik14a68b42017-06-08 14:06:58 -0700851bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800852 // Reset vector bookkeeping.
853 vector_length_ = 0;
854 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700855 vector_static_peeling_factor_ = 0;
856 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800857 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800858 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800859
860 // Phis in the loop-body prevent vectorization.
861 if (!block->GetPhis().IsEmpty()) {
862 return false;
863 }
864
865 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
866 // occurrence, which allows passing down attributes down the use tree.
867 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
868 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
869 return false; // failure to vectorize a left-hand-side
870 }
871 }
872
Aart Bik38a3f212017-10-20 17:02:21 -0700873 // Prepare alignment analysis:
874 // (1) find desired alignment (SIMD vector size in bytes).
875 // (2) initialize static loop peeling votes (peeling factor that will
876 // make one particular reference aligned), never to exceed (1).
877 // (3) variable to record how many references share same alignment.
878 // (4) variable to record suitable candidate for dynamic loop peeling.
879 uint32_t desired_alignment = GetVectorSizeInBytes();
880 DCHECK_LE(desired_alignment, 16u);
881 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
882 uint32_t max_num_same_alignment = 0;
883 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800884
885 // Data dependence analysis. Find each pair of references with same type, where
886 // at least one is a write. Each such pair denotes a possible data dependence.
887 // This analysis exploits the property that differently typed arrays cannot be
888 // aliased, as well as the property that references either point to the same
889 // array or to two completely disjoint arrays, i.e., no partial aliasing.
890 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700891 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800892 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700893 uint32_t num_same_alignment = 0;
894 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800895 for (auto j = i; ++j != vector_refs_->end(); ) {
896 if (i->type == j->type && (i->lhs || j->lhs)) {
897 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
898 HInstruction* a = i->base;
899 HInstruction* b = j->base;
900 HInstruction* x = i->offset;
901 HInstruction* y = j->offset;
902 if (a == b) {
903 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
904 // Conservatively assume a loop-carried data dependence otherwise, and reject.
905 if (x != y) {
906 return false;
907 }
Aart Bik38a3f212017-10-20 17:02:21 -0700908 // Count the number of references that have the same alignment (since
909 // base and offset are the same) and where at least one is a write, so
910 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
911 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800912 } else {
913 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
914 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
915 // generating an explicit a != b disambiguation runtime test on the two references.
916 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700917 // To avoid excessive overhead, we only accept one a != b test.
918 if (vector_runtime_test_a_ == nullptr) {
919 // First test found.
920 vector_runtime_test_a_ = a;
921 vector_runtime_test_b_ = b;
922 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
923 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
924 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800925 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800926 }
927 }
928 }
929 }
Aart Bik38a3f212017-10-20 17:02:21 -0700930 // Update information for finding suitable alignment strategy:
931 // (1) update votes for static loop peeling,
932 // (2) update suitable candidate for dynamic loop peeling.
933 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
934 if (alignment.Base() >= desired_alignment) {
935 // If the array/string object has a known, sufficient alignment, use the
936 // initial offset to compute the static loop peeling vote (this always
937 // works, since elements have natural alignment).
938 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
939 uint32_t vote = (offset == 0)
940 ? 0
941 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
942 DCHECK_LT(vote, 16u);
943 ++peeling_votes[vote];
944 } else if (BaseAlignment() >= desired_alignment &&
945 num_same_alignment > max_num_same_alignment) {
946 // Otherwise, if the array/string object has a known, sufficient alignment
947 // for just the base but with an unknown offset, record the candidate with
948 // the most occurrences for dynamic loop peeling (again, the peeling always
949 // works, since elements have natural alignment).
950 max_num_same_alignment = num_same_alignment;
951 peeling_candidate = &(*i);
952 }
953 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -0800954
Aart Bik38a3f212017-10-20 17:02:21 -0700955 // Find a suitable alignment strategy.
956 SetAlignmentStrategy(peeling_votes, peeling_candidate);
957
958 // Does vectorization seem profitable?
959 if (!IsVectorizationProfitable(trip_count)) {
960 return false;
961 }
Aart Bik14a68b42017-06-08 14:06:58 -0700962
Aart Bikf8f5a162017-02-06 15:35:29 -0800963 // Success!
964 return true;
965}
966
967void HLoopOptimization::Vectorize(LoopNode* node,
968 HBasicBlock* block,
969 HBasicBlock* exit,
970 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800971 HBasicBlock* header = node->loop_info->GetHeader();
972 HBasicBlock* preheader = node->loop_info->GetPreHeader();
973
Aart Bik14a68b42017-06-08 14:06:58 -0700974 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +0100975 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
976 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -0700977 uint32_t chunk = vector_length_ * unroll;
978
Aart Bik38a3f212017-10-20 17:02:21 -0700979 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
980
Aart Bik14a68b42017-06-08 14:06:58 -0700981 // A cleanup loop is needed, at least, for any unknown trip count or
982 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -0700983 bool needs_cleanup = trip_count == 0 ||
984 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800985
986 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700987 HPhi* main_phi = nullptr;
988 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800989 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700990 vector_header_ = header;
991 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800992
Aart Bikdbbac8f2017-09-01 13:06:08 -0700993 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100994 DataType::Type induc_type = main_phi->GetType();
995 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
996 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700997
Aart Bik38a3f212017-10-20 17:02:21 -0700998 // Generate the trip count for static or dynamic loop peeling, if needed:
999 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -07001000 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -07001001 if (vector_static_peeling_factor_ != 0) {
1002 // Static loop peeling for SIMD alignment (using the most suitable
1003 // fixed peeling factor found during prior alignment analysis).
1004 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1005 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1006 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1007 // Dynamic loop peeling for SIMD alignment (using the most suitable
1008 // candidate found during prior alignment analysis):
1009 // rem = offset % ALIGN; // adjusted as #elements
1010 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1011 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1012 uint32_t align = GetVectorSizeInBytes() >> shift;
1013 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1014 vector_dynamic_peeling_candidate_->is_string_char_at);
1015 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1016 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1017 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1018 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1019 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1020 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1021 induc_type, graph_->GetConstant(induc_type, align), rem));
1022 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1023 rem, graph_->GetConstant(induc_type, 0)));
1024 ptc = Insert(preheader, new (global_allocator_) HSelect(
1025 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1026 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001027 }
1028
1029 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001030 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001031 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001032 // vtc = stc - (stc - ptc) % chunk;
1033 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001034 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1035 HInstruction* vtc = stc;
1036 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001037 DCHECK(IsPowerOfTwo(chunk));
1038 HInstruction* diff = stc;
1039 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001040 if (trip_count == 0) {
1041 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1042 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1043 }
Aart Bik14a68b42017-06-08 14:06:58 -07001044 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1045 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001046 HInstruction* rem = Insert(
1047 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001048 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001049 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001050 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1051 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001052 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001053
1054 // Generate runtime disambiguation test:
1055 // vtc = a != b ? vtc : 0;
1056 if (vector_runtime_test_a_ != nullptr) {
1057 HInstruction* rt = Insert(
1058 preheader,
1059 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1060 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001061 new (global_allocator_)
1062 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001063 needs_cleanup = true;
1064 }
1065
Aart Bik38a3f212017-10-20 17:02:21 -07001066 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001067 // for ( ; i < ptc; i += 1)
1068 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001069 //
1070 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1071 // moved around during suspend checks, since all analysis was based on
1072 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001073 if (ptc != nullptr) {
1074 vector_mode_ = kSequential;
1075 GenerateNewLoop(node,
1076 block,
1077 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1078 vector_index_,
1079 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001080 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001081 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001082 }
1083
1084 // Generate vector loop, possibly further unrolled:
1085 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001086 // <vectorized-loop-body>
1087 vector_mode_ = kVector;
1088 GenerateNewLoop(node,
1089 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001090 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1091 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001092 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001093 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001094 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001095 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1096
1097 // Generate cleanup loop, if needed:
1098 // for ( ; i < stc; i += 1)
1099 // <loop-body>
1100 if (needs_cleanup) {
1101 vector_mode_ = kSequential;
1102 GenerateNewLoop(node,
1103 block,
1104 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001105 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001106 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001107 graph_->GetConstant(induc_type, 1),
Artem Serov0e329082018-06-12 10:23:27 +01001108 LoopAnalysisInfo::kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001109 }
1110
Aart Bik0148de42017-09-05 09:25:01 -07001111 // Link reductions to their final uses.
1112 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1113 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001114 HInstruction* phi = i->first;
1115 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1116 // Deal with regular uses.
1117 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1118 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1119 }
1120 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001121 }
1122 }
1123
Aart Bikf8f5a162017-02-06 15:35:29 -08001124 // Remove the original loop by disconnecting the body block
1125 // and removing all instructions from the header.
1126 block->DisconnectAndDelete();
1127 while (!header->GetFirstInstruction()->IsGoto()) {
1128 header->RemoveInstruction(header->GetFirstInstruction());
1129 }
Aart Bikb29f6842017-07-28 15:58:41 -07001130
Aart Bik14a68b42017-06-08 14:06:58 -07001131 // Update loop hierarchy: the old header now resides in the same outer loop
1132 // as the old preheader. Note that we don't bother putting sequential
1133 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001134 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1135 node->loop_info = vloop;
1136}
1137
1138void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1139 HBasicBlock* block,
1140 HBasicBlock* new_preheader,
1141 HInstruction* lo,
1142 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001143 HInstruction* step,
1144 uint32_t unroll) {
1145 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001146 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001147 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001148 vector_preheader_ = new_preheader,
1149 vector_header_ = vector_preheader_->GetSingleSuccessor();
1150 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001151 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1152 kNoRegNumber,
1153 0,
1154 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001155 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001156 // for (i = lo; i < hi; i += step)
1157 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001158 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1159 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001160 vector_header_->AddInstruction(cond);
1161 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001162 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001163 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001164 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001165 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001166 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001167 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1168 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1169 DCHECK(vectorized_def);
1170 }
1171 // Generate body from the instruction map, but in original program order.
1172 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1173 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1174 auto i = vector_map_->find(it.Current());
1175 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1176 Insert(vector_body_, i->second);
1177 // Deal with instructions that need an environment, such as the scalar intrinsics.
1178 if (i->second->NeedsEnvironment()) {
1179 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1180 }
1181 }
1182 }
Aart Bik0148de42017-09-05 09:25:01 -07001183 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001184 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1185 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001186 }
Aart Bik0148de42017-09-05 09:25:01 -07001187 // Finalize phi inputs for the reductions (if any).
1188 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1189 if (!i->first->IsPhi()) {
1190 DCHECK(i->second->IsPhi());
1191 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1192 }
1193 }
Aart Bikb29f6842017-07-28 15:58:41 -07001194 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001195 phi->AddInput(lo);
1196 phi->AddInput(vector_index_);
1197 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001198}
1199
Aart Bikf8f5a162017-02-06 15:35:29 -08001200bool HLoopOptimization::VectorizeDef(LoopNode* node,
1201 HInstruction* instruction,
1202 bool generate_code) {
1203 // Accept a left-hand-side array base[index] for
1204 // (1) supported vector type,
1205 // (2) loop-invariant base,
1206 // (3) unit stride index,
1207 // (4) vectorizable right-hand-side value.
1208 uint64_t restrictions = kNone;
1209 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001210 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001211 HInstruction* base = instruction->InputAt(0);
1212 HInstruction* index = instruction->InputAt(1);
1213 HInstruction* value = instruction->InputAt(2);
1214 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001215 // For narrow types, explicit type conversion may have been
1216 // optimized way, so set the no hi bits restriction here.
1217 if (DataType::Size(type) <= 2) {
1218 restrictions |= kNoHiBits;
1219 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001220 if (TrySetVectorType(type, &restrictions) &&
1221 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001222 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001223 VectorizeUse(node, value, generate_code, type, restrictions)) {
1224 if (generate_code) {
1225 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001226 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001227 } else {
1228 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1229 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001230 return true;
1231 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001232 return false;
1233 }
Aart Bik0148de42017-09-05 09:25:01 -07001234 // Accept a left-hand-side reduction for
1235 // (1) supported vector type,
1236 // (2) vectorizable right-hand-side value.
1237 auto redit = reductions_->find(instruction);
1238 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001239 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001240 // Recognize SAD idiom or direct reduction.
1241 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1242 (TrySetVectorType(type, &restrictions) &&
1243 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001244 if (generate_code) {
1245 HInstruction* new_red = vector_map_->Get(instruction);
1246 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1247 vector_permanent_map_->Overwrite(redit->second, new_red);
1248 }
1249 return true;
1250 }
1251 return false;
1252 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001253 // Branch back okay.
1254 if (instruction->IsGoto()) {
1255 return true;
1256 }
1257 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1258 // Note that actual uses are inspected during right-hand-side tree traversal.
1259 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1260}
1261
Aart Bikf8f5a162017-02-06 15:35:29 -08001262bool HLoopOptimization::VectorizeUse(LoopNode* node,
1263 HInstruction* instruction,
1264 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001265 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001266 uint64_t restrictions) {
1267 // Accept anything for which code has already been generated.
1268 if (generate_code) {
1269 if (vector_map_->find(instruction) != vector_map_->end()) {
1270 return true;
1271 }
1272 }
1273 // Continue the right-hand-side tree traversal, passing in proper
1274 // types and vector restrictions along the way. During code generation,
1275 // all new nodes are drawn from the global allocator.
1276 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1277 // Accept invariant use, using scalar expansion.
1278 if (generate_code) {
1279 GenerateVecInv(instruction, type);
1280 }
1281 return true;
1282 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001283 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001284 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1285 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001286 return false;
1287 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001288 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001289 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001290 // (2) loop-invariant base,
1291 // (3) unit stride index,
1292 // (4) vectorizable right-hand-side value.
1293 HInstruction* base = instruction->InputAt(0);
1294 HInstruction* index = instruction->InputAt(1);
1295 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001296 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001297 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001298 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001299 if (generate_code) {
1300 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001301 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001302 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001303 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001304 }
1305 return true;
1306 }
Aart Bik0148de42017-09-05 09:25:01 -07001307 } else if (instruction->IsPhi()) {
1308 // Accept particular phi operations.
1309 if (reductions_->find(instruction) != reductions_->end()) {
1310 // Deal with vector restrictions.
1311 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1312 return false;
1313 }
1314 // Accept a reduction.
1315 if (generate_code) {
1316 GenerateVecReductionPhi(instruction->AsPhi());
1317 }
1318 return true;
1319 }
1320 // TODO: accept right-hand-side induction?
1321 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001322 } else if (instruction->IsTypeConversion()) {
1323 // Accept particular type conversions.
1324 HTypeConversion* conversion = instruction->AsTypeConversion();
1325 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001326 DataType::Type from = conversion->GetInputType();
1327 DataType::Type to = conversion->GetResultType();
1328 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001329 uint32_t size_vec = DataType::Size(type);
1330 uint32_t size_from = DataType::Size(from);
1331 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001332 // Accept an integral conversion
1333 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1334 // (1b) widening from at least vector type, and
1335 // (2) vectorizable operand.
1336 if ((size_to < size_from &&
1337 size_to == size_vec &&
1338 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1339 (size_to >= size_from &&
1340 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001341 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001342 if (generate_code) {
1343 if (vector_mode_ == kVector) {
1344 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1345 } else {
1346 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1347 }
1348 }
1349 return true;
1350 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001351 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001352 DCHECK_EQ(to, type);
1353 // Accept int to float conversion for
1354 // (1) supported int,
1355 // (2) vectorizable operand.
1356 if (TrySetVectorType(from, &restrictions) &&
1357 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1358 if (generate_code) {
1359 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1360 }
1361 return true;
1362 }
1363 }
1364 return false;
1365 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1366 // Accept unary operator for vectorizable operand.
1367 HInstruction* opa = instruction->InputAt(0);
1368 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1369 if (generate_code) {
1370 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1371 }
1372 return true;
1373 }
1374 } else if (instruction->IsAdd() || instruction->IsSub() ||
1375 instruction->IsMul() || instruction->IsDiv() ||
1376 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1377 // Deal with vector restrictions.
1378 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1379 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1380 return false;
1381 }
1382 // Accept binary operator for vectorizable operands.
1383 HInstruction* opa = instruction->InputAt(0);
1384 HInstruction* opb = instruction->InputAt(1);
1385 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1386 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1387 if (generate_code) {
1388 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1389 }
1390 return true;
1391 }
1392 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001393 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001394 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1395 return true;
1396 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001397 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001398 HInstruction* opa = instruction->InputAt(0);
1399 HInstruction* opb = instruction->InputAt(1);
1400 HInstruction* r = opa;
1401 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001402 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1403 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1404 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001405 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1406 // Shifts right need extra care to account for higher order bits.
1407 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1408 if (instruction->IsShr() &&
1409 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1410 return false; // reject, unless all operands are sign-extension narrower
1411 } else if (instruction->IsUShr() &&
1412 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1413 return false; // reject, unless all operands are zero-extension narrower
1414 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001415 }
1416 // Accept shift operator for vectorizable/invariant operands.
1417 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001418 DCHECK(r != nullptr);
1419 if (generate_code && vector_mode_ != kVector) { // de-idiom
1420 r = opa;
1421 }
Aart Bik50e20d52017-05-05 14:07:29 -07001422 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001423 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001424 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001425 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001426 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001427 if (0 <= distance && distance < max_distance) {
1428 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001429 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001430 }
1431 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001432 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001433 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001434 } else if (instruction->IsAbs()) {
1435 // Deal with vector restrictions.
1436 HInstruction* opa = instruction->InputAt(0);
1437 HInstruction* r = opa;
1438 bool is_unsigned = false;
1439 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1440 return false;
1441 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1442 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1443 return false; // reject, unless operand is sign-extension narrower
1444 }
1445 // Accept ABS(x) for vectorizable operand.
1446 DCHECK(r != nullptr);
1447 if (generate_code && vector_mode_ != kVector) { // de-idiom
1448 r = opa;
1449 }
1450 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1451 if (generate_code) {
1452 GenerateVecOp(instruction,
1453 vector_map_->Get(r),
1454 nullptr,
1455 HVecOperation::ToProperType(type, is_unsigned));
1456 }
1457 return true;
1458 }
Aart Bik281c6812016-08-26 11:31:48 -07001459 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001460 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001461}
1462
Aart Bik38a3f212017-10-20 17:02:21 -07001463uint32_t HLoopOptimization::GetVectorSizeInBytes() {
Vladimir Markoa0431112018-06-25 09:32:54 +01001464 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001465 case InstructionSet::kArm:
1466 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001467 return 8; // 64-bit SIMD
1468 default:
1469 return 16; // 128-bit SIMD
1470 }
1471}
1472
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001473bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Vladimir Markoa0431112018-06-25 09:32:54 +01001474 const InstructionSetFeatures* features = compiler_options_->GetInstructionSetFeatures();
1475 switch (compiler_options_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001476 case InstructionSet::kArm:
1477 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001478 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001479 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001480 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001481 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001482 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001483 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001484 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001485 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001486 case DataType::Type::kUint16:
1487 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001488 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001489 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001490 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001491 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001492 return TrySetVectorLength(2);
1493 default:
1494 break;
1495 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001496 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001497 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001498 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001499 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001500 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001501 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001502 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001503 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001504 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001505 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001506 case DataType::Type::kUint16:
1507 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001508 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001509 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001510 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001511 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001512 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001513 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001514 *restrictions |= kNoDiv | kNoMul;
Aart Bikf8f5a162017-02-06 15:35:29 -08001515 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001516 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001517 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001518 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001519 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001520 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001521 return TrySetVectorLength(2);
1522 default:
1523 return false;
1524 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001525 case InstructionSet::kX86:
1526 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001527 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001528 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1529 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001530 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001531 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001532 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001533 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001534 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001535 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001536 case DataType::Type::kUint16:
1537 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001538 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001539 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001540 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001541 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001542 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001543 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001544 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001545 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001546 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001547 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001548 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001549 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001550 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001551 return TrySetVectorLength(2);
1552 default:
1553 break;
1554 } // switch type
1555 }
1556 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001557 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001558 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1559 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001560 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001561 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001562 case DataType::Type::kInt8:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001563 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001564 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001565 case DataType::Type::kUint16:
1566 case DataType::Type::kInt16:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001567 *restrictions |= kNoDiv | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001568 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001569 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001570 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001571 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001572 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001573 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001574 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001575 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001576 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001577 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001578 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001579 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001580 return TrySetVectorLength(2);
1581 default:
1582 break;
1583 } // switch type
1584 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001585 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001586 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001587 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1588 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001589 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001590 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001591 case DataType::Type::kInt8:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001592 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001593 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001594 case DataType::Type::kUint16:
1595 case DataType::Type::kInt16:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001596 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001597 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001598 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001599 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001600 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001601 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001602 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001603 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001604 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001605 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001606 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001607 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001608 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001609 return TrySetVectorLength(2);
1610 default:
1611 break;
1612 } // switch type
1613 }
1614 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001615 default:
1616 return false;
1617 } // switch instruction set
1618}
1619
1620bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1621 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1622 // First time set?
1623 if (vector_length_ == 0) {
1624 vector_length_ = length;
1625 }
1626 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1627 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1628 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1629 return vector_length_ == length;
1630}
1631
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001632void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001633 if (vector_map_->find(org) == vector_map_->end()) {
1634 // In scalar code, just use a self pass-through for scalar invariants
1635 // (viz. expression remains itself).
1636 if (vector_mode_ == kSequential) {
1637 vector_map_->Put(org, org);
1638 return;
1639 }
1640 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001641 HInstruction* vector = nullptr;
1642 auto it = vector_permanent_map_->find(org);
1643 if (it != vector_permanent_map_->end()) {
1644 vector = it->second; // reuse during unrolling
1645 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001646 // Generates ReplicateScalar( (optional_type_conv) org ).
1647 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001648 DataType::Type input_type = input->GetType();
1649 if (type != input_type && (type == DataType::Type::kInt64 ||
1650 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001651 input = Insert(vector_preheader_,
1652 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1653 }
1654 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001655 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001656 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1657 }
1658 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001659 }
1660}
1661
1662void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1663 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001664 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001665 int64_t value = 0;
1666 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001667 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001668 if (org->IsPhi()) {
1669 Insert(vector_body_, subscript); // lacks layout placeholder
1670 }
1671 }
1672 vector_map_->Put(org, subscript);
1673 }
1674}
1675
1676void HLoopOptimization::GenerateVecMem(HInstruction* org,
1677 HInstruction* opa,
1678 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001679 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001680 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001681 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001682 HInstruction* vector = nullptr;
1683 if (vector_mode_ == kVector) {
1684 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001685 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001686 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001687 if (opb != nullptr) {
1688 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001689 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001690 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001691 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001692 vector = new (global_allocator_) HVecLoad(global_allocator_,
1693 base,
1694 opa,
1695 type,
1696 org->GetSideEffects(),
1697 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001698 is_string_char_at,
1699 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001700 }
Aart Bik38a3f212017-10-20 17:02:21 -07001701 // Known (forced/adjusted/original) alignment?
1702 if (vector_dynamic_peeling_candidate_ != nullptr) {
1703 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1704 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1705 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1706 vector->AsVecMemoryOperation()->SetAlignment( // forced
1707 Alignment(GetVectorSizeInBytes(), 0));
1708 }
1709 } else {
1710 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1711 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001712 }
1713 } else {
1714 // Scalar store or load.
1715 DCHECK(vector_mode_ == kSequential);
1716 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001717 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001718 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001719 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001720 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001721 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1722 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001723 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001724 }
1725 }
1726 vector_map_->Put(org, vector);
1727}
1728
Aart Bik0148de42017-09-05 09:25:01 -07001729void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1730 DCHECK(reductions_->find(phi) != reductions_->end());
1731 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1732 HInstruction* vector = nullptr;
1733 if (vector_mode_ == kSequential) {
1734 HPhi* new_phi = new (global_allocator_) HPhi(
1735 global_allocator_, kNoRegNumber, 0, phi->GetType());
1736 vector_header_->AddPhi(new_phi);
1737 vector = new_phi;
1738 } else {
1739 // Link vector reduction back to prior unrolled update, or a first phi.
1740 auto it = vector_permanent_map_->find(phi);
1741 if (it != vector_permanent_map_->end()) {
1742 vector = it->second;
1743 } else {
1744 HPhi* new_phi = new (global_allocator_) HPhi(
1745 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1746 vector_header_->AddPhi(new_phi);
1747 vector = new_phi;
1748 }
1749 }
1750 vector_map_->Put(phi, vector);
1751}
1752
1753void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1754 HInstruction* new_phi = vector_map_->Get(phi);
1755 HInstruction* new_init = reductions_->Get(phi);
1756 HInstruction* new_red = vector_map_->Get(reduction);
1757 // Link unrolled vector loop back to new phi.
1758 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1759 DCHECK(new_phi->IsVecOperation());
1760 }
1761 // Prepare the new initialization.
1762 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001763 // Generate a [initial, 0, .., 0] vector for add or
1764 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001765 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001766 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001767 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001768 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001769 if (kind == HVecReduce::ReductionKind::kSum) {
1770 new_init = Insert(vector_preheader_,
1771 new (global_allocator_) HVecSetScalars(global_allocator_,
1772 &new_init,
1773 type,
1774 vector_length,
1775 1,
1776 kNoDexPc));
1777 } else {
1778 new_init = Insert(vector_preheader_,
1779 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1780 new_init,
1781 type,
1782 vector_length,
1783 kNoDexPc));
1784 }
Aart Bik0148de42017-09-05 09:25:01 -07001785 } else {
1786 new_init = ReduceAndExtractIfNeeded(new_init);
1787 }
1788 // Set the phi inputs.
1789 DCHECK(new_phi->IsPhi());
1790 new_phi->AsPhi()->AddInput(new_init);
1791 new_phi->AsPhi()->AddInput(new_red);
1792 // New feed value for next phi (safe mutation in iteration).
1793 reductions_->find(phi)->second = new_phi;
1794}
1795
1796HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1797 if (instruction->IsPhi()) {
1798 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001799 if (HVecOperation::ReturnsSIMDValue(input)) {
1800 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001801 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001802 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001803 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001804 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001805 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1806 // Generate a vector reduction and scalar extract
1807 // x = REDUCE( [x_1, .., x_n] )
1808 // y = x_1
1809 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001810 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001811 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001812 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1813 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001814 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001815 exit->InsertInstructionAfter(instruction, reduce);
1816 }
1817 }
1818 return instruction;
1819}
1820
Aart Bikf8f5a162017-02-06 15:35:29 -08001821#define GENERATE_VEC(x, y) \
1822 if (vector_mode_ == kVector) { \
1823 vector = (x); \
1824 } else { \
1825 DCHECK(vector_mode_ == kSequential); \
1826 vector = (y); \
1827 } \
1828 break;
1829
1830void HLoopOptimization::GenerateVecOp(HInstruction* org,
1831 HInstruction* opa,
1832 HInstruction* opb,
Aart Bik3f08e9b2018-05-01 13:42:03 -07001833 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001834 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001835 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001836 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001837 switch (org->GetKind()) {
1838 case HInstruction::kNeg:
1839 DCHECK(opb == nullptr);
1840 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001841 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1842 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001843 case HInstruction::kNot:
1844 DCHECK(opb == nullptr);
1845 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001846 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1847 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001848 case HInstruction::kBooleanNot:
1849 DCHECK(opb == nullptr);
1850 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001851 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1852 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001853 case HInstruction::kTypeConversion:
1854 DCHECK(opb == nullptr);
1855 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001856 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1857 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001858 case HInstruction::kAdd:
1859 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001860 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1861 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001862 case HInstruction::kSub:
1863 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001864 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1865 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001866 case HInstruction::kMul:
1867 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001868 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1869 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001870 case HInstruction::kDiv:
1871 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001872 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1873 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001874 case HInstruction::kAnd:
1875 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001876 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1877 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001878 case HInstruction::kOr:
1879 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001880 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1881 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001882 case HInstruction::kXor:
1883 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001884 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1885 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001886 case HInstruction::kShl:
1887 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001888 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1889 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001890 case HInstruction::kShr:
1891 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001892 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1893 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001894 case HInstruction::kUShr:
1895 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001896 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1897 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001898 case HInstruction::kAbs:
1899 DCHECK(opb == nullptr);
1900 GENERATE_VEC(
1901 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1902 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001903 default:
1904 break;
1905 } // switch
1906 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1907 vector_map_->Put(org, vector);
1908}
1909
1910#undef GENERATE_VEC
1911
1912//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001913// Vectorization idioms.
1914//
1915
1916// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001917// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1918// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001919// Provided that the operands are promoted to a wider form to do the arithmetic and
1920// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1921// implementation that operates directly in narrower form (plus one extra bit).
1922// TODO: current version recognizes implicit byte/short/char widening only;
1923// explicit widening from int to long could be added later.
1924bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1925 HInstruction* instruction,
1926 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001927 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001928 uint64_t restrictions) {
1929 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001930 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001931 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001932 if ((instruction->IsShr() ||
1933 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001934 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001935 // Test for (a + b + c) >> 1 for optional constant c.
1936 HInstruction* a = nullptr;
1937 HInstruction* b = nullptr;
1938 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001939 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07001940 // Accept c == 1 (rounded) or c == 0 (not rounded).
1941 bool is_rounded = false;
1942 if (c == 1) {
1943 is_rounded = true;
1944 } else if (c != 0) {
1945 return false;
1946 }
1947 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001948 HInstruction* r = nullptr;
1949 HInstruction* s = nullptr;
1950 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001951 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001952 return false;
1953 }
1954 // Deal with vector restrictions.
1955 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1956 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1957 return false;
1958 }
1959 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1960 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001961 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001962 if (generate_code && vector_mode_ != kVector) { // de-idiom
1963 r = instruction->InputAt(0);
1964 s = instruction->InputAt(1);
1965 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001966 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1967 VectorizeUse(node, s, generate_code, type, restrictions)) {
1968 if (generate_code) {
1969 if (vector_mode_ == kVector) {
1970 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1971 global_allocator_,
1972 vector_map_->Get(r),
1973 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08001974 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07001975 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001976 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001977 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07001978 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001979 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001980 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001981 }
1982 }
1983 return true;
1984 }
1985 }
1986 }
1987 return false;
1988}
1989
Aart Bikdbbac8f2017-09-01 13:06:08 -07001990// Method recognizes the following idiom:
1991// q += ABS(a - b) for signed operands a, b
1992// Provided that the operands have the same type or are promoted to a wider form.
1993// Since this may involve a vector length change, the idiom is handled by going directly
1994// to a sad-accumulate node (rather than relying combining finer grained nodes later).
1995// TODO: unsigned SAD too?
1996bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
1997 HInstruction* instruction,
1998 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001999 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07002000 uint64_t restrictions) {
2001 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2002 // are done in the same precision (either int or long).
2003 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002004 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002005 return false;
2006 }
2007 HInstruction* q = instruction->InputAt(0);
2008 HInstruction* v = instruction->InputAt(1);
2009 HInstruction* a = nullptr;
2010 HInstruction* b = nullptr;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002011 if (v->IsAbs() &&
2012 v->GetType() == reduction_type &&
2013 IsSubConst2(graph_, v->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2014 DCHECK(a != nullptr && b != nullptr);
2015 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002016 return false;
2017 }
2018 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2019 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002020 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002021 HInstruction* r = a;
2022 HInstruction* s = b;
2023 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002024 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002025 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2026 sub_type = b->GetType();
2027 }
2028 if (a->IsTypeConversion() &&
2029 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2030 sub_type = a->InputAt(0)->GetType();
2031 }
2032 if (b->IsTypeConversion() &&
2033 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2034 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002035 }
2036 if (reduction_type != sub_type &&
2037 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2038 return false;
2039 }
2040 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002041 if (!TrySetVectorType(sub_type, &restrictions) ||
2042 HasVectorRestrictions(restrictions, kNoSAD) ||
2043 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002044 return false;
2045 }
2046 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2047 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002048 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002049 if (generate_code && vector_mode_ != kVector) { // de-idiom
2050 r = s = v->InputAt(0);
2051 }
2052 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2053 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2054 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2055 if (generate_code) {
2056 if (vector_mode_ == kVector) {
2057 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2058 global_allocator_,
2059 vector_map_->Get(q),
2060 vector_map_->Get(r),
2061 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002062 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002063 GetOtherVL(reduction_type, sub_type, vector_length_),
2064 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002065 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2066 } else {
2067 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2068 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2069 }
2070 }
2071 return true;
2072 }
2073 return false;
2074}
2075
Aart Bikf3e61ee2017-04-12 17:09:20 -07002076//
Aart Bik14a68b42017-06-08 14:06:58 -07002077// Vectorization heuristics.
2078//
2079
Aart Bik38a3f212017-10-20 17:02:21 -07002080Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2081 DataType::Type type,
2082 bool is_string_char_at,
2083 uint32_t peeling) {
2084 // Combine the alignment and hidden offset that is guaranteed by
2085 // the Android runtime with a known starting index adjusted as bytes.
2086 int64_t value = 0;
2087 if (IsInt64AndGet(offset, /*out*/ &value)) {
2088 uint32_t start_offset =
2089 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2090 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2091 }
2092 // Otherwise, the Android runtime guarantees at least natural alignment.
2093 return Alignment(DataType::Size(type), 0);
2094}
2095
2096void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2097 const ArrayReference* peeling_candidate) {
2098 // Current heuristic: pick the best static loop peeling factor, if any,
2099 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2100 uint32_t max_vote = 0;
2101 for (int32_t i = 0; i < 16; i++) {
2102 if (peeling_votes[i] > max_vote) {
2103 max_vote = peeling_votes[i];
2104 vector_static_peeling_factor_ = i;
2105 }
2106 }
2107 if (max_vote == 0) {
2108 vector_dynamic_peeling_candidate_ = peeling_candidate;
2109 }
2110}
2111
2112uint32_t HLoopOptimization::MaxNumberPeeled() {
2113 if (vector_dynamic_peeling_candidate_ != nullptr) {
2114 return vector_length_ - 1u; // worst-case
2115 }
2116 return vector_static_peeling_factor_; // known exactly
2117}
2118
Aart Bik14a68b42017-06-08 14:06:58 -07002119bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002120 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002121 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002122 // TODO: trip count is really unsigned entity, provided the guarding test
2123 // is satisfied; deal with this more carefully later
2124 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002125 if (vector_length_ == 0) {
2126 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002127 } else if (trip_count < 0) {
2128 return false; // guard against non-taken/large
2129 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002130 return false; // insufficient iterations
2131 }
2132 return true;
2133}
2134
Aart Bik14a68b42017-06-08 14:06:58 -07002135//
Aart Bikf8f5a162017-02-06 15:35:29 -08002136// Helpers.
2137//
2138
2139bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002140 // Start with empty phi induction.
2141 iset_->clear();
2142
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002143 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2144 // smart enough to follow strongly connected components (and it's probably not worth
2145 // it to make it so). See b/33775412.
2146 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2147 return false;
2148 }
Aart Bikb29f6842017-07-28 15:58:41 -07002149
2150 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002151 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2152 if (set != nullptr) {
2153 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002154 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002155 // each instruction is removable and, when restrict uses are requested, other than for phi,
2156 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002157 if (!i->IsInBlock()) {
2158 continue;
2159 } else if (!i->IsRemovable()) {
2160 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002161 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002162 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002163 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2164 if (set->find(use.GetUser()) == set->end()) {
2165 return false;
2166 }
2167 }
2168 }
Aart Bike3dedc52016-11-02 17:50:27 -07002169 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002170 }
Aart Bikcc42be02016-10-20 16:14:16 -07002171 return true;
2172 }
2173 return false;
2174}
2175
Aart Bikb29f6842017-07-28 15:58:41 -07002176bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002177 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002178 // Only unclassified phi cycles are candidates for reductions.
2179 if (induction_range_.IsClassified(phi)) {
2180 return false;
2181 }
2182 // Accept operations like x = x + .., provided that the phi and the reduction are
2183 // used exactly once inside the loop, and by each other.
2184 HInputsRef inputs = phi->GetInputs();
2185 if (inputs.size() == 2) {
2186 HInstruction* reduction = inputs[1];
2187 if (HasReductionFormat(reduction, phi)) {
2188 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002189 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002190 bool single_use_inside_loop =
2191 // Reduction update only used by phi.
2192 reduction->GetUses().HasExactlyOneElement() &&
2193 !reduction->HasEnvironmentUses() &&
2194 // Reduction update is only use of phi inside the loop.
2195 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2196 iset_->size() == 1;
2197 iset_->clear(); // leave the way you found it
2198 if (single_use_inside_loop) {
2199 // Link reduction back, and start recording feed value.
2200 reductions_->Put(reduction, phi);
2201 reductions_->Put(phi, phi->InputAt(0));
2202 return true;
2203 }
2204 }
2205 }
2206 return false;
2207}
2208
2209bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2210 // Start with empty phi induction and reductions.
2211 iset_->clear();
2212 reductions_->clear();
2213
2214 // Scan the phis to find the following (the induction structure has already
2215 // been optimized, so we don't need to worry about trivial cases):
2216 // (1) optional reductions in loop,
2217 // (2) the main induction, used in loop control.
2218 HPhi* phi = nullptr;
2219 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2220 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2221 continue;
2222 } else if (phi == nullptr) {
2223 // Found the first candidate for main induction.
2224 phi = it.Current()->AsPhi();
2225 } else {
2226 return false;
2227 }
2228 }
2229
2230 // Then test for a typical loopheader:
2231 // s: SuspendCheck
2232 // c: Condition(phi, bound)
2233 // i: If(c)
2234 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002235 HInstruction* s = block->GetFirstInstruction();
2236 if (s != nullptr && s->IsSuspendCheck()) {
2237 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002238 if (c != nullptr &&
2239 c->IsCondition() &&
2240 c->GetUses().HasExactlyOneElement() && // only used for termination
2241 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002242 HInstruction* i = c->GetNext();
2243 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2244 iset_->insert(c);
2245 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002246 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002247 return true;
2248 }
2249 }
2250 }
2251 }
2252 return false;
2253}
2254
2255bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002256 if (!block->GetPhis().IsEmpty()) {
2257 return false;
2258 }
2259 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2260 HInstruction* instruction = it.Current();
2261 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2262 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002263 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002264 }
2265 return true;
2266}
2267
2268bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2269 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002270 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002271 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2272 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2273 return true;
2274 }
Aart Bikcc42be02016-10-20 16:14:16 -07002275 }
2276 return false;
2277}
2278
Aart Bik482095d2016-10-10 15:39:10 -07002279bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002280 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002281 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002282 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002283 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002284 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2285 HInstruction* user = use.GetUser();
2286 if (iset_->find(user) == iset_->end()) { // not excluded?
2287 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002288 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002289 // If collect_loop_uses is set, simply keep adding those uses to the set.
2290 // Otherwise, reject uses inside the loop that were not already in the set.
2291 if (collect_loop_uses) {
2292 iset_->insert(user);
2293 continue;
2294 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002295 return false;
2296 }
2297 ++*use_count;
2298 }
2299 }
2300 return true;
2301}
2302
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002303bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2304 HInstruction* instruction,
2305 HBasicBlock* block) {
2306 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002307 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002308 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002309 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002310 const HUseList<HInstruction*>& uses = instruction->GetUses();
2311 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2312 HInstruction* user = it->GetUser();
2313 size_t index = it->GetIndex();
2314 ++it; // increment before replacing
2315 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002316 if (kIsDebugBuild) {
2317 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2318 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2319 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2320 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002321 user->ReplaceInput(replacement, index);
2322 induction_range_.Replace(user, instruction, replacement); // update induction
2323 }
2324 }
Aart Bikb29f6842017-07-28 15:58:41 -07002325 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002326 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2327 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2328 HEnvironment* user = it->GetUser();
2329 size_t index = it->GetIndex();
2330 ++it; // increment before replacing
2331 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002332 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002333 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002334 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2335 user->RemoveAsUserOfInput(index);
2336 user->SetRawEnvAt(index, replacement);
2337 replacement->AddEnvUseAt(user, index);
2338 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002339 }
2340 }
Aart Bik807868e2016-11-03 17:51:43 -07002341 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002342 }
Aart Bik807868e2016-11-03 17:51:43 -07002343 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002344}
2345
Aart Bikf8f5a162017-02-06 15:35:29 -08002346bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2347 HInstruction* instruction,
2348 HBasicBlock* block,
2349 bool collect_loop_uses) {
2350 // Assigning the last value is always successful if there are no uses.
2351 // Otherwise, it succeeds in a no early-exit loop by generating the
2352 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002353 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002354 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2355 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002356 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002357}
2358
Aart Bik6b69e0a2017-01-11 10:20:43 -08002359void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2360 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2361 HInstruction* instruction = i.Current();
2362 if (instruction->IsDeadAndRemovable()) {
2363 simplified_ = true;
2364 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2365 }
2366 }
2367}
2368
Aart Bik14a68b42017-06-08 14:06:58 -07002369bool HLoopOptimization::CanRemoveCycle() {
2370 for (HInstruction* i : *iset_) {
2371 // We can never remove instructions that have environment
2372 // uses when we compile 'debuggable'.
2373 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2374 return false;
2375 }
2376 // A deoptimization should never have an environment input removed.
2377 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2378 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2379 return false;
2380 }
2381 }
2382 }
2383 return true;
2384}
2385
Aart Bik281c6812016-08-26 11:31:48 -07002386} // namespace art