blob: eda6bd1e86f389ea681d00d47f03b03f957251fb [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"
Aart Bik92685a82017-03-06 11:13:43 -080026#include "driver/compiler_driver.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,
Aart Bik92685a82017-03-06 11:13:43 -0800430 CompilerDriver* compiler_driver,
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),
Aart Bik92685a82017-03-06 11:13:43 -0800435 compiler_driver_(compiler_driver),
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),
Artem Serovcf43fb62018-02-15 14:43:48 +0000457 arch_loop_helper_(ArchNoOptsLoopHelper::Create(compiler_driver_ != nullptr
Artem Serov121f2032017-10-23 19:19:06 +0100458 ? compiler_driver_->GetInstructionSet()
459 : 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) {
747 return TryOptimizeInnerLoopFinite(node) ||
Artem Serov72411e62017-10-19 16:18:07 +0100748 TryPeelingForLoopInvariantExitsElimination(node) ||
Artem Serov121f2032017-10-23 19:19:06 +0100749 TryUnrollingForBranchPenaltyReduction(node);
750}
751
Artem Serov121f2032017-10-23 19:19:06 +0100752
Artem Serov121f2032017-10-23 19:19:06 +0100753
754//
755// Loop unrolling: generic part methods.
756//
757
Artem Serov72411e62017-10-19 16:18:07 +0100758bool HLoopOptimization::TryUnrollingForBranchPenaltyReduction(LoopNode* node) {
Artem Serov121f2032017-10-23 19:19:06 +0100759 // Don't run peeling/unrolling if compiler_driver_ is nullptr (i.e., running under tests)
760 // as InstructionSet is needed.
Artem Serovcf43fb62018-02-15 14:43:48 +0000761 if (compiler_driver_ == nullptr) {
Artem Serov121f2032017-10-23 19:19:06 +0100762 return false;
763 }
764
Artem Serov72411e62017-10-19 16:18:07 +0100765 HLoopInformation* loop_info = node->loop_info;
Artem Serov121f2032017-10-23 19:19:06 +0100766 int64_t trip_count = 0;
767 // Only unroll loops with a known tripcount.
768 if (!induction_range_.HasKnownTripCount(loop_info, &trip_count)) {
769 return false;
770 }
771
772 uint32_t unrolling_factor = arch_loop_helper_->GetScalarUnrollingFactor(loop_info, trip_count);
773 if (unrolling_factor == kNoUnrollingFactor) {
774 return false;
775 }
776
777 LoopAnalysisInfo loop_analysis_info(loop_info);
778 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &loop_analysis_info);
779
780 // Check "IsLoopClonable" last as it can be time-consuming.
Artem Serovcf43fb62018-02-15 14:43:48 +0000781 if (loop_analysis_info.HasInstructionsPreventingScalarUnrolling() ||
782 arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&loop_analysis_info) ||
Artem Serov121f2032017-10-23 19:19:06 +0100783 (loop_analysis_info.GetNumberOfExits() > 1) ||
Artem Serov121f2032017-10-23 19:19:06 +0100784 !PeelUnrollHelper::IsLoopClonable(loop_info)) {
785 return false;
786 }
787
788 // TODO: support other unrolling factors.
789 DCHECK_EQ(unrolling_factor, 2u);
790
791 // Perform unrolling.
Artem Serov72411e62017-10-19 16:18:07 +0100792 PeelUnrollSimpleHelper helper(loop_info);
793 helper.DoUnrolling();
Artem Serov121f2032017-10-23 19:19:06 +0100794
795 // Remove the redundant loop check after unrolling.
Artem Serov72411e62017-10-19 16:18:07 +0100796 HIf* copy_hif =
797 helper.GetBasicBlockMap()->Get(loop_info->GetHeader())->GetLastInstruction()->AsIf();
Artem Serov121f2032017-10-23 19:19:06 +0100798 int32_t constant = loop_info->Contains(*copy_hif->IfTrueSuccessor()) ? 1 : 0;
799 copy_hif->ReplaceInput(graph_->GetIntConstant(constant), 0u);
800
801 return true;
802}
803
Artem Serov72411e62017-10-19 16:18:07 +0100804bool HLoopOptimization::TryPeelingForLoopInvariantExitsElimination(LoopNode* node) {
805 // Don't run peeling/unrolling if compiler_driver_ is nullptr (i.e., running under tests)
806 // as InstructionSet is needed.
Artem Serovcf43fb62018-02-15 14:43:48 +0000807 if (compiler_driver_ == nullptr) {
Artem Serov72411e62017-10-19 16:18:07 +0100808 return false;
809 }
810
811 HLoopInformation* loop_info = node->loop_info;
812 // Check 'IsLoopClonable' the last as it might be time-consuming.
813 if (!arch_loop_helper_->IsLoopPeelingEnabled()) {
814 return false;
815 }
816
817 LoopAnalysisInfo loop_analysis_info(loop_info);
818 LoopAnalysis::CalculateLoopBasicProperties(loop_info, &loop_analysis_info);
819
820 // Check "IsLoopClonable" last as it can be time-consuming.
Artem Serovcf43fb62018-02-15 14:43:48 +0000821 if (loop_analysis_info.HasInstructionsPreventingScalarPeeling() ||
822 arch_loop_helper_->IsLoopNonBeneficialForScalarOpts(&loop_analysis_info) ||
Artem Serov72411e62017-10-19 16:18:07 +0100823 !LoopAnalysis::HasLoopAtLeastOneInvariantExit(loop_info) ||
824 !PeelUnrollHelper::IsLoopClonable(loop_info)) {
825 return false;
826 }
827
828 // Perform peeling.
829 PeelUnrollSimpleHelper helper(loop_info);
830 helper.DoPeeling();
831
832 const SuperblockCloner::HInstructionMap* hir_map = helper.GetInstructionMap();
833 for (auto entry : *hir_map) {
834 HInstruction* copy = entry.second;
835 if (copy->IsIf()) {
836 TryToEvaluateIfCondition(copy->AsIf(), graph_);
837 }
838 }
839
840 return true;
841}
842
Aart Bikf8f5a162017-02-06 15:35:29 -0800843//
844// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
845// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
846// Intel Press, June, 2004 (http://www.aartbik.com/).
847//
848
Aart Bik14a68b42017-06-08 14:06:58 -0700849bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800850 // Reset vector bookkeeping.
851 vector_length_ = 0;
852 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700853 vector_static_peeling_factor_ = 0;
854 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800855 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800856 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800857
858 // Phis in the loop-body prevent vectorization.
859 if (!block->GetPhis().IsEmpty()) {
860 return false;
861 }
862
863 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
864 // occurrence, which allows passing down attributes down the use tree.
865 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
866 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
867 return false; // failure to vectorize a left-hand-side
868 }
869 }
870
Aart Bik38a3f212017-10-20 17:02:21 -0700871 // Prepare alignment analysis:
872 // (1) find desired alignment (SIMD vector size in bytes).
873 // (2) initialize static loop peeling votes (peeling factor that will
874 // make one particular reference aligned), never to exceed (1).
875 // (3) variable to record how many references share same alignment.
876 // (4) variable to record suitable candidate for dynamic loop peeling.
877 uint32_t desired_alignment = GetVectorSizeInBytes();
878 DCHECK_LE(desired_alignment, 16u);
879 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
880 uint32_t max_num_same_alignment = 0;
881 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800882
883 // Data dependence analysis. Find each pair of references with same type, where
884 // at least one is a write. Each such pair denotes a possible data dependence.
885 // This analysis exploits the property that differently typed arrays cannot be
886 // aliased, as well as the property that references either point to the same
887 // array or to two completely disjoint arrays, i.e., no partial aliasing.
888 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700889 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800890 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700891 uint32_t num_same_alignment = 0;
892 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800893 for (auto j = i; ++j != vector_refs_->end(); ) {
894 if (i->type == j->type && (i->lhs || j->lhs)) {
895 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
896 HInstruction* a = i->base;
897 HInstruction* b = j->base;
898 HInstruction* x = i->offset;
899 HInstruction* y = j->offset;
900 if (a == b) {
901 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
902 // Conservatively assume a loop-carried data dependence otherwise, and reject.
903 if (x != y) {
904 return false;
905 }
Aart Bik38a3f212017-10-20 17:02:21 -0700906 // Count the number of references that have the same alignment (since
907 // base and offset are the same) and where at least one is a write, so
908 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
909 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800910 } else {
911 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
912 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
913 // generating an explicit a != b disambiguation runtime test on the two references.
914 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700915 // To avoid excessive overhead, we only accept one a != b test.
916 if (vector_runtime_test_a_ == nullptr) {
917 // First test found.
918 vector_runtime_test_a_ = a;
919 vector_runtime_test_b_ = b;
920 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
921 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
922 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800923 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800924 }
925 }
926 }
927 }
Aart Bik38a3f212017-10-20 17:02:21 -0700928 // Update information for finding suitable alignment strategy:
929 // (1) update votes for static loop peeling,
930 // (2) update suitable candidate for dynamic loop peeling.
931 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
932 if (alignment.Base() >= desired_alignment) {
933 // If the array/string object has a known, sufficient alignment, use the
934 // initial offset to compute the static loop peeling vote (this always
935 // works, since elements have natural alignment).
936 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
937 uint32_t vote = (offset == 0)
938 ? 0
939 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
940 DCHECK_LT(vote, 16u);
941 ++peeling_votes[vote];
942 } else if (BaseAlignment() >= desired_alignment &&
943 num_same_alignment > max_num_same_alignment) {
944 // Otherwise, if the array/string object has a known, sufficient alignment
945 // for just the base but with an unknown offset, record the candidate with
946 // the most occurrences for dynamic loop peeling (again, the peeling always
947 // works, since elements have natural alignment).
948 max_num_same_alignment = num_same_alignment;
949 peeling_candidate = &(*i);
950 }
951 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -0800952
Aart Bik38a3f212017-10-20 17:02:21 -0700953 // Find a suitable alignment strategy.
954 SetAlignmentStrategy(peeling_votes, peeling_candidate);
955
956 // Does vectorization seem profitable?
957 if (!IsVectorizationProfitable(trip_count)) {
958 return false;
959 }
Aart Bik14a68b42017-06-08 14:06:58 -0700960
Aart Bikf8f5a162017-02-06 15:35:29 -0800961 // Success!
962 return true;
963}
964
965void HLoopOptimization::Vectorize(LoopNode* node,
966 HBasicBlock* block,
967 HBasicBlock* exit,
968 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800969 HBasicBlock* header = node->loop_info->GetHeader();
970 HBasicBlock* preheader = node->loop_info->GetPreHeader();
971
Aart Bik14a68b42017-06-08 14:06:58 -0700972 // Pick a loop unrolling factor for the vector loop.
Artem Serov121f2032017-10-23 19:19:06 +0100973 uint32_t unroll = arch_loop_helper_->GetSIMDUnrollingFactor(
974 block, trip_count, MaxNumberPeeled(), vector_length_);
Aart Bik14a68b42017-06-08 14:06:58 -0700975 uint32_t chunk = vector_length_ * unroll;
976
Aart Bik38a3f212017-10-20 17:02:21 -0700977 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
978
Aart Bik14a68b42017-06-08 14:06:58 -0700979 // A cleanup loop is needed, at least, for any unknown trip count or
980 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -0700981 bool needs_cleanup = trip_count == 0 ||
982 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800983
984 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700985 HPhi* main_phi = nullptr;
986 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800987 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700988 vector_header_ = header;
989 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800990
Aart Bikdbbac8f2017-09-01 13:06:08 -0700991 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100992 DataType::Type induc_type = main_phi->GetType();
993 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
994 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700995
Aart Bik38a3f212017-10-20 17:02:21 -0700996 // Generate the trip count for static or dynamic loop peeling, if needed:
997 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -0700998 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -0700999 if (vector_static_peeling_factor_ != 0) {
1000 // Static loop peeling for SIMD alignment (using the most suitable
1001 // fixed peeling factor found during prior alignment analysis).
1002 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
1003 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
1004 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
1005 // Dynamic loop peeling for SIMD alignment (using the most suitable
1006 // candidate found during prior alignment analysis):
1007 // rem = offset % ALIGN; // adjusted as #elements
1008 // ptc = rem == 0 ? 0 : (ALIGN - rem);
1009 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
1010 uint32_t align = GetVectorSizeInBytes() >> shift;
1011 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
1012 vector_dynamic_peeling_candidate_->is_string_char_at);
1013 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
1014 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
1015 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
1016 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
1017 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
1018 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
1019 induc_type, graph_->GetConstant(induc_type, align), rem));
1020 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
1021 rem, graph_->GetConstant(induc_type, 0)));
1022 ptc = Insert(preheader, new (global_allocator_) HSelect(
1023 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
1024 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -07001025 }
1026
1027 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -08001028 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -07001029 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -07001030 // vtc = stc - (stc - ptc) % chunk;
1031 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08001032 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
1033 HInstruction* vtc = stc;
1034 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -07001035 DCHECK(IsPowerOfTwo(chunk));
1036 HInstruction* diff = stc;
1037 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -07001038 if (trip_count == 0) {
1039 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
1040 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
1041 }
Aart Bik14a68b42017-06-08 14:06:58 -07001042 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
1043 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001044 HInstruction* rem = Insert(
1045 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -07001046 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001047 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001048 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
1049 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001050 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001051
1052 // Generate runtime disambiguation test:
1053 // vtc = a != b ? vtc : 0;
1054 if (vector_runtime_test_a_ != nullptr) {
1055 HInstruction* rt = Insert(
1056 preheader,
1057 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
1058 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001059 new (global_allocator_)
1060 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001061 needs_cleanup = true;
1062 }
1063
Aart Bik38a3f212017-10-20 17:02:21 -07001064 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -07001065 // for ( ; i < ptc; i += 1)
1066 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -07001067 //
1068 // NOTE: The alignment forced by the peeling loop is preserved even if data is
1069 // moved around during suspend checks, since all analysis was based on
1070 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -07001071 if (ptc != nullptr) {
1072 vector_mode_ = kSequential;
1073 GenerateNewLoop(node,
1074 block,
1075 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1076 vector_index_,
1077 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001078 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001079 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -07001080 }
1081
1082 // Generate vector loop, possibly further unrolled:
1083 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -08001084 // <vectorized-loop-body>
1085 vector_mode_ = kVector;
1086 GenerateNewLoop(node,
1087 block,
Aart Bik14a68b42017-06-08 14:06:58 -07001088 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
1089 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001090 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001091 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -07001092 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -08001093 HLoopInformation* vloop = vector_header_->GetLoopInformation();
1094
1095 // Generate cleanup loop, if needed:
1096 // for ( ; i < stc; i += 1)
1097 // <loop-body>
1098 if (needs_cleanup) {
1099 vector_mode_ = kSequential;
1100 GenerateNewLoop(node,
1101 block,
1102 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -07001103 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -08001104 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001105 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -07001106 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -08001107 }
1108
Aart Bik0148de42017-09-05 09:25:01 -07001109 // Link reductions to their final uses.
1110 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1111 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001112 HInstruction* phi = i->first;
1113 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
1114 // Deal with regular uses.
1115 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
1116 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
1117 }
1118 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -07001119 }
1120 }
1121
Aart Bikf8f5a162017-02-06 15:35:29 -08001122 // Remove the original loop by disconnecting the body block
1123 // and removing all instructions from the header.
1124 block->DisconnectAndDelete();
1125 while (!header->GetFirstInstruction()->IsGoto()) {
1126 header->RemoveInstruction(header->GetFirstInstruction());
1127 }
Aart Bikb29f6842017-07-28 15:58:41 -07001128
Aart Bik14a68b42017-06-08 14:06:58 -07001129 // Update loop hierarchy: the old header now resides in the same outer loop
1130 // as the old preheader. Note that we don't bother putting sequential
1131 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -08001132 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
1133 node->loop_info = vloop;
1134}
1135
1136void HLoopOptimization::GenerateNewLoop(LoopNode* node,
1137 HBasicBlock* block,
1138 HBasicBlock* new_preheader,
1139 HInstruction* lo,
1140 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -07001141 HInstruction* step,
1142 uint32_t unroll) {
1143 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001144 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001145 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -08001146 vector_preheader_ = new_preheader,
1147 vector_header_ = vector_preheader_->GetSingleSuccessor();
1148 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001149 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1150 kNoRegNumber,
1151 0,
1152 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001153 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001154 // for (i = lo; i < hi; i += step)
1155 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001156 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1157 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001158 vector_header_->AddInstruction(cond);
1159 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001160 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001161 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001162 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001163 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001164 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001165 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1166 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1167 DCHECK(vectorized_def);
1168 }
1169 // Generate body from the instruction map, but in original program order.
1170 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1171 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1172 auto i = vector_map_->find(it.Current());
1173 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1174 Insert(vector_body_, i->second);
1175 // Deal with instructions that need an environment, such as the scalar intrinsics.
1176 if (i->second->NeedsEnvironment()) {
1177 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1178 }
1179 }
1180 }
Aart Bik0148de42017-09-05 09:25:01 -07001181 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001182 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1183 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001184 }
Aart Bik0148de42017-09-05 09:25:01 -07001185 // Finalize phi inputs for the reductions (if any).
1186 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1187 if (!i->first->IsPhi()) {
1188 DCHECK(i->second->IsPhi());
1189 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1190 }
1191 }
Aart Bikb29f6842017-07-28 15:58:41 -07001192 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001193 phi->AddInput(lo);
1194 phi->AddInput(vector_index_);
1195 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001196}
1197
Aart Bikf8f5a162017-02-06 15:35:29 -08001198bool HLoopOptimization::VectorizeDef(LoopNode* node,
1199 HInstruction* instruction,
1200 bool generate_code) {
1201 // Accept a left-hand-side array base[index] for
1202 // (1) supported vector type,
1203 // (2) loop-invariant base,
1204 // (3) unit stride index,
1205 // (4) vectorizable right-hand-side value.
1206 uint64_t restrictions = kNone;
1207 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001208 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001209 HInstruction* base = instruction->InputAt(0);
1210 HInstruction* index = instruction->InputAt(1);
1211 HInstruction* value = instruction->InputAt(2);
1212 HInstruction* offset = nullptr;
Aart Bik6d057002018-04-09 15:39:58 -07001213 // For narrow types, explicit type conversion may have been
1214 // optimized way, so set the no hi bits restriction here.
1215 if (DataType::Size(type) <= 2) {
1216 restrictions |= kNoHiBits;
1217 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001218 if (TrySetVectorType(type, &restrictions) &&
1219 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001220 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001221 VectorizeUse(node, value, generate_code, type, restrictions)) {
1222 if (generate_code) {
1223 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001224 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001225 } else {
1226 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1227 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001228 return true;
1229 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001230 return false;
1231 }
Aart Bik0148de42017-09-05 09:25:01 -07001232 // Accept a left-hand-side reduction for
1233 // (1) supported vector type,
1234 // (2) vectorizable right-hand-side value.
1235 auto redit = reductions_->find(instruction);
1236 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001237 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001238 // Recognize SAD idiom or direct reduction.
1239 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1240 (TrySetVectorType(type, &restrictions) &&
1241 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001242 if (generate_code) {
1243 HInstruction* new_red = vector_map_->Get(instruction);
1244 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1245 vector_permanent_map_->Overwrite(redit->second, new_red);
1246 }
1247 return true;
1248 }
1249 return false;
1250 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001251 // Branch back okay.
1252 if (instruction->IsGoto()) {
1253 return true;
1254 }
1255 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1256 // Note that actual uses are inspected during right-hand-side tree traversal.
1257 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1258}
1259
Aart Bikf8f5a162017-02-06 15:35:29 -08001260bool HLoopOptimization::VectorizeUse(LoopNode* node,
1261 HInstruction* instruction,
1262 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001263 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001264 uint64_t restrictions) {
1265 // Accept anything for which code has already been generated.
1266 if (generate_code) {
1267 if (vector_map_->find(instruction) != vector_map_->end()) {
1268 return true;
1269 }
1270 }
1271 // Continue the right-hand-side tree traversal, passing in proper
1272 // types and vector restrictions along the way. During code generation,
1273 // all new nodes are drawn from the global allocator.
1274 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1275 // Accept invariant use, using scalar expansion.
1276 if (generate_code) {
1277 GenerateVecInv(instruction, type);
1278 }
1279 return true;
1280 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001281 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001282 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1283 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001284 return false;
1285 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001286 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001287 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001288 // (2) loop-invariant base,
1289 // (3) unit stride index,
1290 // (4) vectorizable right-hand-side value.
1291 HInstruction* base = instruction->InputAt(0);
1292 HInstruction* index = instruction->InputAt(1);
1293 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001294 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001295 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001296 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001297 if (generate_code) {
1298 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001299 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001300 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001301 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001302 }
1303 return true;
1304 }
Aart Bik0148de42017-09-05 09:25:01 -07001305 } else if (instruction->IsPhi()) {
1306 // Accept particular phi operations.
1307 if (reductions_->find(instruction) != reductions_->end()) {
1308 // Deal with vector restrictions.
1309 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1310 return false;
1311 }
1312 // Accept a reduction.
1313 if (generate_code) {
1314 GenerateVecReductionPhi(instruction->AsPhi());
1315 }
1316 return true;
1317 }
1318 // TODO: accept right-hand-side induction?
1319 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001320 } else if (instruction->IsTypeConversion()) {
1321 // Accept particular type conversions.
1322 HTypeConversion* conversion = instruction->AsTypeConversion();
1323 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001324 DataType::Type from = conversion->GetInputType();
1325 DataType::Type to = conversion->GetResultType();
1326 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001327 uint32_t size_vec = DataType::Size(type);
1328 uint32_t size_from = DataType::Size(from);
1329 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001330 // Accept an integral conversion
1331 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1332 // (1b) widening from at least vector type, and
1333 // (2) vectorizable operand.
1334 if ((size_to < size_from &&
1335 size_to == size_vec &&
1336 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1337 (size_to >= size_from &&
1338 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001339 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001340 if (generate_code) {
1341 if (vector_mode_ == kVector) {
1342 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1343 } else {
1344 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1345 }
1346 }
1347 return true;
1348 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001349 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001350 DCHECK_EQ(to, type);
1351 // Accept int to float conversion for
1352 // (1) supported int,
1353 // (2) vectorizable operand.
1354 if (TrySetVectorType(from, &restrictions) &&
1355 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1356 if (generate_code) {
1357 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1358 }
1359 return true;
1360 }
1361 }
1362 return false;
1363 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1364 // Accept unary operator for vectorizable operand.
1365 HInstruction* opa = instruction->InputAt(0);
1366 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1367 if (generate_code) {
1368 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1369 }
1370 return true;
1371 }
1372 } else if (instruction->IsAdd() || instruction->IsSub() ||
1373 instruction->IsMul() || instruction->IsDiv() ||
1374 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1375 // Deal with vector restrictions.
1376 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1377 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1378 return false;
1379 }
1380 // Accept binary operator for vectorizable operands.
1381 HInstruction* opa = instruction->InputAt(0);
1382 HInstruction* opb = instruction->InputAt(1);
1383 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1384 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1385 if (generate_code) {
1386 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1387 }
1388 return true;
1389 }
1390 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001391 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001392 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1393 return true;
1394 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001395 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001396 HInstruction* opa = instruction->InputAt(0);
1397 HInstruction* opb = instruction->InputAt(1);
1398 HInstruction* r = opa;
1399 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001400 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1401 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1402 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001403 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1404 // Shifts right need extra care to account for higher order bits.
1405 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1406 if (instruction->IsShr() &&
1407 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1408 return false; // reject, unless all operands are sign-extension narrower
1409 } else if (instruction->IsUShr() &&
1410 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1411 return false; // reject, unless all operands are zero-extension narrower
1412 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001413 }
1414 // Accept shift operator for vectorizable/invariant operands.
1415 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001416 DCHECK(r != nullptr);
1417 if (generate_code && vector_mode_ != kVector) { // de-idiom
1418 r = opa;
1419 }
Aart Bik50e20d52017-05-05 14:07:29 -07001420 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001421 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001422 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001423 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001424 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001425 if (0 <= distance && distance < max_distance) {
1426 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001427 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001428 }
1429 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001430 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001431 }
Aart Bik3b2a5952018-03-05 13:55:28 -08001432 } else if (instruction->IsAbs()) {
1433 // Deal with vector restrictions.
1434 HInstruction* opa = instruction->InputAt(0);
1435 HInstruction* r = opa;
1436 bool is_unsigned = false;
1437 if (HasVectorRestrictions(restrictions, kNoAbs)) {
1438 return false;
1439 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1440 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1441 return false; // reject, unless operand is sign-extension narrower
1442 }
1443 // Accept ABS(x) for vectorizable operand.
1444 DCHECK(r != nullptr);
1445 if (generate_code && vector_mode_ != kVector) { // de-idiom
1446 r = opa;
1447 }
1448 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
1449 if (generate_code) {
1450 GenerateVecOp(instruction,
1451 vector_map_->Get(r),
1452 nullptr,
1453 HVecOperation::ToProperType(type, is_unsigned));
1454 }
1455 return true;
1456 }
Aart Bik281c6812016-08-26 11:31:48 -07001457 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001458 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001459}
1460
Aart Bik38a3f212017-10-20 17:02:21 -07001461uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1462 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001463 case InstructionSet::kArm:
1464 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001465 return 8; // 64-bit SIMD
1466 default:
1467 return 16; // 128-bit SIMD
1468 }
1469}
1470
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001471bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001472 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1473 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001474 case InstructionSet::kArm:
1475 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001476 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001477 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001478 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001479 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001480 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001481 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001482 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001483 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001484 case DataType::Type::kUint16:
1485 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001486 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001487 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001488 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001489 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001490 return TrySetVectorLength(2);
1491 default:
1492 break;
1493 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001494 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001495 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001496 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001497 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001498 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001499 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001500 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001501 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001502 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001503 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001504 case DataType::Type::kUint16:
1505 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001506 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001507 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001508 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001509 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001510 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001511 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001512 *restrictions |= kNoDiv | kNoMul;
Aart Bikf8f5a162017-02-06 15:35:29 -08001513 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001514 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001515 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001516 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001517 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001518 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001519 return TrySetVectorLength(2);
1520 default:
1521 return false;
1522 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001523 case InstructionSet::kX86:
1524 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001525 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001526 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1527 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001528 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001529 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001530 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001531 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001532 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001533 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001534 case DataType::Type::kUint16:
1535 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001536 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001537 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001538 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001539 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001540 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001541 case DataType::Type::kInt64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001542 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001543 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001544 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001545 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001546 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001547 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001548 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001549 return TrySetVectorLength(2);
1550 default:
1551 break;
1552 } // switch type
1553 }
1554 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001555 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001556 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1557 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001558 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001559 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001560 case DataType::Type::kInt8:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001561 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001562 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001563 case DataType::Type::kUint16:
1564 case DataType::Type::kInt16:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001565 *restrictions |= kNoDiv | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001566 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001567 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001568 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001569 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001570 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001571 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001572 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001573 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001574 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001575 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001576 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001577 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001578 return TrySetVectorLength(2);
1579 default:
1580 break;
1581 } // switch type
1582 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001583 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001584 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001585 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1586 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001587 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001588 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001589 case DataType::Type::kInt8:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001590 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001591 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001592 case DataType::Type::kUint16:
1593 case DataType::Type::kInt16:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001594 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001595 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001596 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001597 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001598 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001599 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001600 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001601 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001602 case DataType::Type::kFloat32:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001603 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001604 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001605 case DataType::Type::kFloat64:
Aart Bik3f08e9b2018-05-01 13:42:03 -07001606 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001607 return TrySetVectorLength(2);
1608 default:
1609 break;
1610 } // switch type
1611 }
1612 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001613 default:
1614 return false;
1615 } // switch instruction set
1616}
1617
1618bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1619 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1620 // First time set?
1621 if (vector_length_ == 0) {
1622 vector_length_ = length;
1623 }
1624 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1625 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1626 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1627 return vector_length_ == length;
1628}
1629
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001630void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001631 if (vector_map_->find(org) == vector_map_->end()) {
1632 // In scalar code, just use a self pass-through for scalar invariants
1633 // (viz. expression remains itself).
1634 if (vector_mode_ == kSequential) {
1635 vector_map_->Put(org, org);
1636 return;
1637 }
1638 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001639 HInstruction* vector = nullptr;
1640 auto it = vector_permanent_map_->find(org);
1641 if (it != vector_permanent_map_->end()) {
1642 vector = it->second; // reuse during unrolling
1643 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001644 // Generates ReplicateScalar( (optional_type_conv) org ).
1645 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001646 DataType::Type input_type = input->GetType();
1647 if (type != input_type && (type == DataType::Type::kInt64 ||
1648 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001649 input = Insert(vector_preheader_,
1650 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1651 }
1652 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001653 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001654 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1655 }
1656 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001657 }
1658}
1659
1660void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1661 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001662 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001663 int64_t value = 0;
1664 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001665 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001666 if (org->IsPhi()) {
1667 Insert(vector_body_, subscript); // lacks layout placeholder
1668 }
1669 }
1670 vector_map_->Put(org, subscript);
1671 }
1672}
1673
1674void HLoopOptimization::GenerateVecMem(HInstruction* org,
1675 HInstruction* opa,
1676 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001677 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001678 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001679 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001680 HInstruction* vector = nullptr;
1681 if (vector_mode_ == kVector) {
1682 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001683 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001684 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001685 if (opb != nullptr) {
1686 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001687 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001688 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001689 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001690 vector = new (global_allocator_) HVecLoad(global_allocator_,
1691 base,
1692 opa,
1693 type,
1694 org->GetSideEffects(),
1695 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001696 is_string_char_at,
1697 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001698 }
Aart Bik38a3f212017-10-20 17:02:21 -07001699 // Known (forced/adjusted/original) alignment?
1700 if (vector_dynamic_peeling_candidate_ != nullptr) {
1701 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1702 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1703 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1704 vector->AsVecMemoryOperation()->SetAlignment( // forced
1705 Alignment(GetVectorSizeInBytes(), 0));
1706 }
1707 } else {
1708 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1709 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001710 }
1711 } else {
1712 // Scalar store or load.
1713 DCHECK(vector_mode_ == kSequential);
1714 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001715 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001716 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001717 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001718 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001719 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1720 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001721 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001722 }
1723 }
1724 vector_map_->Put(org, vector);
1725}
1726
Aart Bik0148de42017-09-05 09:25:01 -07001727void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1728 DCHECK(reductions_->find(phi) != reductions_->end());
1729 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1730 HInstruction* vector = nullptr;
1731 if (vector_mode_ == kSequential) {
1732 HPhi* new_phi = new (global_allocator_) HPhi(
1733 global_allocator_, kNoRegNumber, 0, phi->GetType());
1734 vector_header_->AddPhi(new_phi);
1735 vector = new_phi;
1736 } else {
1737 // Link vector reduction back to prior unrolled update, or a first phi.
1738 auto it = vector_permanent_map_->find(phi);
1739 if (it != vector_permanent_map_->end()) {
1740 vector = it->second;
1741 } else {
1742 HPhi* new_phi = new (global_allocator_) HPhi(
1743 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1744 vector_header_->AddPhi(new_phi);
1745 vector = new_phi;
1746 }
1747 }
1748 vector_map_->Put(phi, vector);
1749}
1750
1751void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1752 HInstruction* new_phi = vector_map_->Get(phi);
1753 HInstruction* new_init = reductions_->Get(phi);
1754 HInstruction* new_red = vector_map_->Get(reduction);
1755 // Link unrolled vector loop back to new phi.
1756 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1757 DCHECK(new_phi->IsVecOperation());
1758 }
1759 // Prepare the new initialization.
1760 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001761 // Generate a [initial, 0, .., 0] vector for add or
1762 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001763 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001764 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001765 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001766 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001767 if (kind == HVecReduce::ReductionKind::kSum) {
1768 new_init = Insert(vector_preheader_,
1769 new (global_allocator_) HVecSetScalars(global_allocator_,
1770 &new_init,
1771 type,
1772 vector_length,
1773 1,
1774 kNoDexPc));
1775 } else {
1776 new_init = Insert(vector_preheader_,
1777 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1778 new_init,
1779 type,
1780 vector_length,
1781 kNoDexPc));
1782 }
Aart Bik0148de42017-09-05 09:25:01 -07001783 } else {
1784 new_init = ReduceAndExtractIfNeeded(new_init);
1785 }
1786 // Set the phi inputs.
1787 DCHECK(new_phi->IsPhi());
1788 new_phi->AsPhi()->AddInput(new_init);
1789 new_phi->AsPhi()->AddInput(new_red);
1790 // New feed value for next phi (safe mutation in iteration).
1791 reductions_->find(phi)->second = new_phi;
1792}
1793
1794HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1795 if (instruction->IsPhi()) {
1796 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001797 if (HVecOperation::ReturnsSIMDValue(input)) {
1798 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001799 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001800 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001801 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001802 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001803 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1804 // Generate a vector reduction and scalar extract
1805 // x = REDUCE( [x_1, .., x_n] )
1806 // y = x_1
1807 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001808 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001809 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001810 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1811 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001812 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001813 exit->InsertInstructionAfter(instruction, reduce);
1814 }
1815 }
1816 return instruction;
1817}
1818
Aart Bikf8f5a162017-02-06 15:35:29 -08001819#define GENERATE_VEC(x, y) \
1820 if (vector_mode_ == kVector) { \
1821 vector = (x); \
1822 } else { \
1823 DCHECK(vector_mode_ == kSequential); \
1824 vector = (y); \
1825 } \
1826 break;
1827
1828void HLoopOptimization::GenerateVecOp(HInstruction* org,
1829 HInstruction* opa,
1830 HInstruction* opb,
Aart Bik3f08e9b2018-05-01 13:42:03 -07001831 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001832 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001833 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001834 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001835 switch (org->GetKind()) {
1836 case HInstruction::kNeg:
1837 DCHECK(opb == nullptr);
1838 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001839 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1840 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001841 case HInstruction::kNot:
1842 DCHECK(opb == nullptr);
1843 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001844 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1845 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001846 case HInstruction::kBooleanNot:
1847 DCHECK(opb == nullptr);
1848 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001849 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1850 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001851 case HInstruction::kTypeConversion:
1852 DCHECK(opb == nullptr);
1853 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001854 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1855 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001856 case HInstruction::kAdd:
1857 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001858 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1859 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001860 case HInstruction::kSub:
1861 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001862 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1863 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001864 case HInstruction::kMul:
1865 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001866 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1867 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001868 case HInstruction::kDiv:
1869 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001870 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1871 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001872 case HInstruction::kAnd:
1873 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001874 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1875 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001876 case HInstruction::kOr:
1877 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001878 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1879 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001880 case HInstruction::kXor:
1881 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001882 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1883 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001884 case HInstruction::kShl:
1885 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001886 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1887 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001888 case HInstruction::kShr:
1889 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001890 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1891 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001892 case HInstruction::kUShr:
1893 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001894 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1895 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bik3b2a5952018-03-05 13:55:28 -08001896 case HInstruction::kAbs:
1897 DCHECK(opb == nullptr);
1898 GENERATE_VEC(
1899 new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc),
1900 new (global_allocator_) HAbs(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001901 default:
1902 break;
1903 } // switch
1904 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1905 vector_map_->Put(org, vector);
1906}
1907
1908#undef GENERATE_VEC
1909
1910//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001911// Vectorization idioms.
1912//
1913
1914// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001915// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1916// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001917// Provided that the operands are promoted to a wider form to do the arithmetic and
1918// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1919// implementation that operates directly in narrower form (plus one extra bit).
1920// TODO: current version recognizes implicit byte/short/char widening only;
1921// explicit widening from int to long could be added later.
1922bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1923 HInstruction* instruction,
1924 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001925 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001926 uint64_t restrictions) {
1927 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001928 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001929 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001930 if ((instruction->IsShr() ||
1931 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001932 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001933 // Test for (a + b + c) >> 1 for optional constant c.
1934 HInstruction* a = nullptr;
1935 HInstruction* b = nullptr;
1936 int64_t c = 0;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001937 if (IsAddConst2(graph_, instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik5f805002017-05-16 16:42:41 -07001938 // Accept c == 1 (rounded) or c == 0 (not rounded).
1939 bool is_rounded = false;
1940 if (c == 1) {
1941 is_rounded = true;
1942 } else if (c != 0) {
1943 return false;
1944 }
1945 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001946 HInstruction* r = nullptr;
1947 HInstruction* s = nullptr;
1948 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001949 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001950 return false;
1951 }
1952 // Deal with vector restrictions.
1953 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1954 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1955 return false;
1956 }
1957 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1958 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00001959 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001960 if (generate_code && vector_mode_ != kVector) { // de-idiom
1961 r = instruction->InputAt(0);
1962 s = instruction->InputAt(1);
1963 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001964 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1965 VectorizeUse(node, s, generate_code, type, restrictions)) {
1966 if (generate_code) {
1967 if (vector_mode_ == kVector) {
1968 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1969 global_allocator_,
1970 vector_map_->Get(r),
1971 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08001972 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07001973 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001974 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001975 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07001976 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001977 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001978 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001979 }
1980 }
1981 return true;
1982 }
1983 }
1984 }
1985 return false;
1986}
1987
Aart Bikdbbac8f2017-09-01 13:06:08 -07001988// Method recognizes the following idiom:
1989// q += ABS(a - b) for signed operands a, b
1990// Provided that the operands have the same type or are promoted to a wider form.
1991// Since this may involve a vector length change, the idiom is handled by going directly
1992// to a sad-accumulate node (rather than relying combining finer grained nodes later).
1993// TODO: unsigned SAD too?
1994bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
1995 HInstruction* instruction,
1996 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001997 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001998 uint64_t restrictions) {
1999 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
2000 // are done in the same precision (either int or long).
2001 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002002 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002003 return false;
2004 }
2005 HInstruction* q = instruction->InputAt(0);
2006 HInstruction* v = instruction->InputAt(1);
2007 HInstruction* a = nullptr;
2008 HInstruction* b = nullptr;
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002009 if (v->IsAbs() &&
2010 v->GetType() == reduction_type &&
2011 IsSubConst2(graph_, v->InputAt(0), /*out*/ &a, /*out*/ &b)) {
2012 DCHECK(a != nullptr && b != nullptr);
2013 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002014 return false;
2015 }
2016 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
2017 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07002018 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07002019 HInstruction* r = a;
2020 HInstruction* s = b;
2021 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002022 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07002023 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
2024 sub_type = b->GetType();
2025 }
2026 if (a->IsTypeConversion() &&
2027 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2028 sub_type = a->InputAt(0)->GetType();
2029 }
2030 if (b->IsTypeConversion() &&
2031 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
2032 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07002033 }
2034 if (reduction_type != sub_type &&
2035 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
2036 return false;
2037 }
2038 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01002039 if (!TrySetVectorType(sub_type, &restrictions) ||
2040 HasVectorRestrictions(restrictions, kNoSAD) ||
2041 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07002042 return false;
2043 }
2044 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
2045 // idiomatic operation. Sequential code uses the original scalar expressions.
Nicolas Geoffraya3e23262018-03-28 11:15:12 +00002046 DCHECK(r != nullptr && s != nullptr);
Aart Bikdbbac8f2017-09-01 13:06:08 -07002047 if (generate_code && vector_mode_ != kVector) { // de-idiom
2048 r = s = v->InputAt(0);
2049 }
2050 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
2051 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
2052 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
2053 if (generate_code) {
2054 if (vector_mode_ == kVector) {
2055 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
2056 global_allocator_,
2057 vector_map_->Get(q),
2058 vector_map_->Get(r),
2059 vector_map_->Get(s),
Aart Bik3b2a5952018-03-05 13:55:28 -08002060 HVecOperation::ToProperType(reduction_type, is_unsigned),
Aart Bik46b6dbc2017-10-03 11:37:37 -07002061 GetOtherVL(reduction_type, sub_type, vector_length_),
2062 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07002063 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
2064 } else {
2065 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
2066 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
2067 }
2068 }
2069 return true;
2070 }
2071 return false;
2072}
2073
Aart Bikf3e61ee2017-04-12 17:09:20 -07002074//
Aart Bik14a68b42017-06-08 14:06:58 -07002075// Vectorization heuristics.
2076//
2077
Aart Bik38a3f212017-10-20 17:02:21 -07002078Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
2079 DataType::Type type,
2080 bool is_string_char_at,
2081 uint32_t peeling) {
2082 // Combine the alignment and hidden offset that is guaranteed by
2083 // the Android runtime with a known starting index adjusted as bytes.
2084 int64_t value = 0;
2085 if (IsInt64AndGet(offset, /*out*/ &value)) {
2086 uint32_t start_offset =
2087 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2088 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2089 }
2090 // Otherwise, the Android runtime guarantees at least natural alignment.
2091 return Alignment(DataType::Size(type), 0);
2092}
2093
2094void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2095 const ArrayReference* peeling_candidate) {
2096 // Current heuristic: pick the best static loop peeling factor, if any,
2097 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2098 uint32_t max_vote = 0;
2099 for (int32_t i = 0; i < 16; i++) {
2100 if (peeling_votes[i] > max_vote) {
2101 max_vote = peeling_votes[i];
2102 vector_static_peeling_factor_ = i;
2103 }
2104 }
2105 if (max_vote == 0) {
2106 vector_dynamic_peeling_candidate_ = peeling_candidate;
2107 }
2108}
2109
2110uint32_t HLoopOptimization::MaxNumberPeeled() {
2111 if (vector_dynamic_peeling_candidate_ != nullptr) {
2112 return vector_length_ - 1u; // worst-case
2113 }
2114 return vector_static_peeling_factor_; // known exactly
2115}
2116
Aart Bik14a68b42017-06-08 14:06:58 -07002117bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002118 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002119 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002120 // TODO: trip count is really unsigned entity, provided the guarding test
2121 // is satisfied; deal with this more carefully later
2122 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002123 if (vector_length_ == 0) {
2124 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002125 } else if (trip_count < 0) {
2126 return false; // guard against non-taken/large
2127 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002128 return false; // insufficient iterations
2129 }
2130 return true;
2131}
2132
Aart Bik14a68b42017-06-08 14:06:58 -07002133//
Aart Bikf8f5a162017-02-06 15:35:29 -08002134// Helpers.
2135//
2136
2137bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002138 // Start with empty phi induction.
2139 iset_->clear();
2140
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002141 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2142 // smart enough to follow strongly connected components (and it's probably not worth
2143 // it to make it so). See b/33775412.
2144 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2145 return false;
2146 }
Aart Bikb29f6842017-07-28 15:58:41 -07002147
2148 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002149 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2150 if (set != nullptr) {
2151 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002152 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002153 // each instruction is removable and, when restrict uses are requested, other than for phi,
2154 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002155 if (!i->IsInBlock()) {
2156 continue;
2157 } else if (!i->IsRemovable()) {
2158 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002159 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002160 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002161 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2162 if (set->find(use.GetUser()) == set->end()) {
2163 return false;
2164 }
2165 }
2166 }
Aart Bike3dedc52016-11-02 17:50:27 -07002167 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002168 }
Aart Bikcc42be02016-10-20 16:14:16 -07002169 return true;
2170 }
2171 return false;
2172}
2173
Aart Bikb29f6842017-07-28 15:58:41 -07002174bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002175 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002176 // Only unclassified phi cycles are candidates for reductions.
2177 if (induction_range_.IsClassified(phi)) {
2178 return false;
2179 }
2180 // Accept operations like x = x + .., provided that the phi and the reduction are
2181 // used exactly once inside the loop, and by each other.
2182 HInputsRef inputs = phi->GetInputs();
2183 if (inputs.size() == 2) {
2184 HInstruction* reduction = inputs[1];
2185 if (HasReductionFormat(reduction, phi)) {
2186 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002187 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002188 bool single_use_inside_loop =
2189 // Reduction update only used by phi.
2190 reduction->GetUses().HasExactlyOneElement() &&
2191 !reduction->HasEnvironmentUses() &&
2192 // Reduction update is only use of phi inside the loop.
2193 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2194 iset_->size() == 1;
2195 iset_->clear(); // leave the way you found it
2196 if (single_use_inside_loop) {
2197 // Link reduction back, and start recording feed value.
2198 reductions_->Put(reduction, phi);
2199 reductions_->Put(phi, phi->InputAt(0));
2200 return true;
2201 }
2202 }
2203 }
2204 return false;
2205}
2206
2207bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2208 // Start with empty phi induction and reductions.
2209 iset_->clear();
2210 reductions_->clear();
2211
2212 // Scan the phis to find the following (the induction structure has already
2213 // been optimized, so we don't need to worry about trivial cases):
2214 // (1) optional reductions in loop,
2215 // (2) the main induction, used in loop control.
2216 HPhi* phi = nullptr;
2217 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2218 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2219 continue;
2220 } else if (phi == nullptr) {
2221 // Found the first candidate for main induction.
2222 phi = it.Current()->AsPhi();
2223 } else {
2224 return false;
2225 }
2226 }
2227
2228 // Then test for a typical loopheader:
2229 // s: SuspendCheck
2230 // c: Condition(phi, bound)
2231 // i: If(c)
2232 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002233 HInstruction* s = block->GetFirstInstruction();
2234 if (s != nullptr && s->IsSuspendCheck()) {
2235 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002236 if (c != nullptr &&
2237 c->IsCondition() &&
2238 c->GetUses().HasExactlyOneElement() && // only used for termination
2239 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002240 HInstruction* i = c->GetNext();
2241 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2242 iset_->insert(c);
2243 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002244 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002245 return true;
2246 }
2247 }
2248 }
2249 }
2250 return false;
2251}
2252
2253bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002254 if (!block->GetPhis().IsEmpty()) {
2255 return false;
2256 }
2257 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2258 HInstruction* instruction = it.Current();
2259 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2260 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002261 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002262 }
2263 return true;
2264}
2265
2266bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2267 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002268 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002269 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2270 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2271 return true;
2272 }
Aart Bikcc42be02016-10-20 16:14:16 -07002273 }
2274 return false;
2275}
2276
Aart Bik482095d2016-10-10 15:39:10 -07002277bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002278 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002279 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002280 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002281 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002282 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2283 HInstruction* user = use.GetUser();
2284 if (iset_->find(user) == iset_->end()) { // not excluded?
2285 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002286 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002287 // If collect_loop_uses is set, simply keep adding those uses to the set.
2288 // Otherwise, reject uses inside the loop that were not already in the set.
2289 if (collect_loop_uses) {
2290 iset_->insert(user);
2291 continue;
2292 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002293 return false;
2294 }
2295 ++*use_count;
2296 }
2297 }
2298 return true;
2299}
2300
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002301bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2302 HInstruction* instruction,
2303 HBasicBlock* block) {
2304 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002305 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002306 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002307 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002308 const HUseList<HInstruction*>& uses = instruction->GetUses();
2309 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2310 HInstruction* user = it->GetUser();
2311 size_t index = it->GetIndex();
2312 ++it; // increment before replacing
2313 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002314 if (kIsDebugBuild) {
2315 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2316 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2317 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2318 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002319 user->ReplaceInput(replacement, index);
2320 induction_range_.Replace(user, instruction, replacement); // update induction
2321 }
2322 }
Aart Bikb29f6842017-07-28 15:58:41 -07002323 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002324 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2325 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2326 HEnvironment* user = it->GetUser();
2327 size_t index = it->GetIndex();
2328 ++it; // increment before replacing
2329 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002330 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002331 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002332 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2333 user->RemoveAsUserOfInput(index);
2334 user->SetRawEnvAt(index, replacement);
2335 replacement->AddEnvUseAt(user, index);
2336 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002337 }
2338 }
Aart Bik807868e2016-11-03 17:51:43 -07002339 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002340 }
Aart Bik807868e2016-11-03 17:51:43 -07002341 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002342}
2343
Aart Bikf8f5a162017-02-06 15:35:29 -08002344bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2345 HInstruction* instruction,
2346 HBasicBlock* block,
2347 bool collect_loop_uses) {
2348 // Assigning the last value is always successful if there are no uses.
2349 // Otherwise, it succeeds in a no early-exit loop by generating the
2350 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002351 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002352 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2353 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002354 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002355}
2356
Aart Bik6b69e0a2017-01-11 10:20:43 -08002357void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2358 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2359 HInstruction* instruction = i.Current();
2360 if (instruction->IsDeadAndRemovable()) {
2361 simplified_ = true;
2362 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2363 }
2364 }
2365}
2366
Aart Bik14a68b42017-06-08 14:06:58 -07002367bool HLoopOptimization::CanRemoveCycle() {
2368 for (HInstruction* i : *iset_) {
2369 // We can never remove instructions that have environment
2370 // uses when we compile 'debuggable'.
2371 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2372 return false;
2373 }
2374 // A deoptimization should never have an environment input removed.
2375 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2376 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2377 return false;
2378 }
2379 }
2380 }
2381 return true;
2382}
2383
Aart Bik281c6812016-08-26 11:31:48 -07002384} // namespace art