blob: 9f278a9f4e036c2fde7870df6e1b4ea1d657ae96 [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 Bik521b50f2017-09-09 10:44:45 -070036// No loop unrolling factor (just one copy of the loop-body).
37static constexpr uint32_t kNoUnrollingFactor = 1;
38
Aart Bik38a3f212017-10-20 17:02:21 -070039//
40// Static helpers.
41//
42
43// Base alignment for arrays/strings guaranteed by the Android runtime.
44static uint32_t BaseAlignment() {
45 return kObjectAlignment;
46}
47
48// Hidden offset for arrays/strings guaranteed by the Android runtime.
49static uint32_t HiddenOffset(DataType::Type type, bool is_string_char_at) {
50 return is_string_char_at
51 ? mirror::String::ValueOffset().Uint32Value()
52 : mirror::Array::DataOffset(DataType::Size(type)).Uint32Value();
53}
54
Aart Bik9abf8942016-10-14 09:49:42 -070055// Remove the instruction from the graph. A bit more elaborate than the usual
56// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070057static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070058 instruction->RemoveAsUserOfAllInputs();
59 instruction->RemoveEnvironmentUsers();
60 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
Artem Serov21c7e6f2017-07-27 16:04:42 +010061 RemoveEnvironmentUses(instruction);
62 ResetEnvironmentInputRecords(instruction);
Aart Bik281c6812016-08-26 11:31:48 -070063}
64
Aart Bik807868e2016-11-03 17:51:43 -070065// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070066static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
67 if (block->GetPredecessors().size() == 1 &&
68 block->GetSuccessors().size() == 1 &&
69 block->IsSingleGoto()) {
70 *succ = block->GetSingleSuccessor();
71 return true;
72 }
73 return false;
74}
75
Aart Bik807868e2016-11-03 17:51:43 -070076// Detect an early exit loop.
77static bool IsEarlyExit(HLoopInformation* loop_info) {
78 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
79 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
80 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
81 if (!loop_info->Contains(*successor)) {
82 return true;
83 }
84 }
85 }
86 return false;
87}
88
Aart Bik68ca7022017-09-26 16:44:23 -070089// Forward declaration.
90static bool IsZeroExtensionAndGet(HInstruction* instruction,
91 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070092 /*out*/ HInstruction** operand);
Aart Bik68ca7022017-09-26 16:44:23 -070093
Aart Bikdf011c32017-09-28 12:53:04 -070094// Detect a sign extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -070095// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -070096static bool IsSignExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010097 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -070098 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070099 // Accept any already wider constant that would be handled properly by sign
100 // extension when represented in the *width* of the given narrower data type
Aart Bik4d1a9d42017-10-19 14:40:55 -0700101 // (the fact that Uint8/Uint16 normally zero extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700102 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700103 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700104 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100105 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100106 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700107 if (IsInt<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700108 *operand = instruction;
109 return true;
110 }
111 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100112 case DataType::Type::kUint16:
113 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700114 if (IsInt<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700115 *operand = instruction;
116 return true;
117 }
118 return false;
119 default:
120 return false;
121 }
122 }
Aart Bikdf011c32017-09-28 12:53:04 -0700123 // An implicit widening conversion of any signed expression sign-extends.
124 if (instruction->GetType() == type) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700125 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100126 case DataType::Type::kInt8:
127 case DataType::Type::kInt16:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700128 *operand = instruction;
129 return true;
130 default:
131 return false;
132 }
133 }
Aart Bikdf011c32017-09-28 12:53:04 -0700134 // An explicit widening conversion of a signed expression sign-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700135 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700136 HInstruction* conv = instruction->InputAt(0);
137 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700138 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700139 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700140 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700141 if (type == from && (from == DataType::Type::kInt8 ||
142 from == DataType::Type::kInt16 ||
143 from == DataType::Type::kInt32)) {
144 *operand = conv;
145 return true;
146 }
147 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700148 case DataType::Type::kInt16:
149 return type == DataType::Type::kUint16 &&
150 from == DataType::Type::kUint16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700151 IsZeroExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700152 default:
153 return false;
154 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700155 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700156 return false;
157}
158
Aart Bikdf011c32017-09-28 12:53:04 -0700159// Detect a zero extension in instruction from the given type.
Aart Bikdbbac8f2017-09-01 13:06:08 -0700160// Returns the promoted operand on success.
Aart Bikf3e61ee2017-04-12 17:09:20 -0700161static bool IsZeroExtensionAndGet(HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100162 DataType::Type type,
Aart Bikdf011c32017-09-28 12:53:04 -0700163 /*out*/ HInstruction** operand) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700164 // Accept any already wider constant that would be handled properly by zero
165 // extension when represented in the *width* of the given narrower data type
Aart Bikdf011c32017-09-28 12:53:04 -0700166 // (the fact that Int8/Int16 normally sign extend does not matter here).
Aart Bikf3e61ee2017-04-12 17:09:20 -0700167 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700168 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700169 switch (type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100170 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100171 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700172 if (IsUint<8>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700173 *operand = instruction;
174 return true;
175 }
176 return false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100177 case DataType::Type::kUint16:
178 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -0700179 if (IsUint<16>(value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700180 *operand = instruction;
181 return true;
182 }
183 return false;
184 default:
185 return false;
186 }
187 }
Aart Bikdf011c32017-09-28 12:53:04 -0700188 // An implicit widening conversion of any unsigned expression zero-extends.
189 if (instruction->GetType() == type) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100190 switch (type) {
191 case DataType::Type::kUint8:
192 case DataType::Type::kUint16:
193 *operand = instruction;
194 return true;
195 default:
196 return false;
Aart Bikf3e61ee2017-04-12 17:09:20 -0700197 }
198 }
Aart Bikdf011c32017-09-28 12:53:04 -0700199 // An explicit widening conversion of an unsigned expression zero-extends.
Aart Bik68ca7022017-09-26 16:44:23 -0700200 if (instruction->IsTypeConversion()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700201 HInstruction* conv = instruction->InputAt(0);
202 DataType::Type from = conv->GetType();
Aart Bik68ca7022017-09-26 16:44:23 -0700203 switch (instruction->GetType()) {
Aart Bikdf011c32017-09-28 12:53:04 -0700204 case DataType::Type::kInt32:
Aart Bik68ca7022017-09-26 16:44:23 -0700205 case DataType::Type::kInt64:
Aart Bikdf011c32017-09-28 12:53:04 -0700206 if (type == from && from == DataType::Type::kUint16) {
207 *operand = conv;
208 return true;
209 }
210 return false;
Aart Bik68ca7022017-09-26 16:44:23 -0700211 case DataType::Type::kUint16:
212 return type == DataType::Type::kInt16 &&
213 from == DataType::Type::kInt16 &&
Aart Bikdf011c32017-09-28 12:53:04 -0700214 IsSignExtensionAndGet(instruction->InputAt(0), type, /*out*/ operand);
Aart Bik68ca7022017-09-26 16:44:23 -0700215 default:
216 return false;
217 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700218 }
Aart Bikf3e61ee2017-04-12 17:09:20 -0700219 return false;
220}
221
Aart Bik304c8a52017-05-23 11:01:13 -0700222// Detect situations with same-extension narrower operands.
223// Returns true on success and sets is_unsigned accordingly.
224static bool IsNarrowerOperands(HInstruction* a,
225 HInstruction* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100226 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700227 /*out*/ HInstruction** r,
228 /*out*/ HInstruction** s,
229 /*out*/ bool* is_unsigned) {
Aart Bik4d1a9d42017-10-19 14:40:55 -0700230 // Look for a matching sign extension.
231 DataType::Type stype = HVecOperation::ToSignedType(type);
232 if (IsSignExtensionAndGet(a, stype, r) && IsSignExtensionAndGet(b, stype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700233 *is_unsigned = false;
234 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700235 }
236 // Look for a matching zero extension.
237 DataType::Type utype = HVecOperation::ToUnsignedType(type);
238 if (IsZeroExtensionAndGet(a, utype, r) && IsZeroExtensionAndGet(b, utype, s)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700239 *is_unsigned = true;
240 return true;
241 }
242 return false;
243}
244
245// As above, single operand.
246static bool IsNarrowerOperand(HInstruction* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100247 DataType::Type type,
Aart Bik304c8a52017-05-23 11:01:13 -0700248 /*out*/ HInstruction** r,
249 /*out*/ bool* is_unsigned) {
Aart Bik4d1a9d42017-10-19 14:40:55 -0700250 // Look for a matching sign extension.
251 DataType::Type stype = HVecOperation::ToSignedType(type);
252 if (IsSignExtensionAndGet(a, stype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700253 *is_unsigned = false;
254 return true;
Aart Bik4d1a9d42017-10-19 14:40:55 -0700255 }
256 // Look for a matching zero extension.
257 DataType::Type utype = HVecOperation::ToUnsignedType(type);
258 if (IsZeroExtensionAndGet(a, utype, r)) {
Aart Bik304c8a52017-05-23 11:01:13 -0700259 *is_unsigned = true;
260 return true;
261 }
262 return false;
263}
264
Aart Bikdbbac8f2017-09-01 13:06:08 -0700265// Compute relative vector length based on type difference.
Aart Bik38a3f212017-10-20 17:02:21 -0700266static uint32_t GetOtherVL(DataType::Type other_type, DataType::Type vector_type, uint32_t vl) {
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100267 DCHECK(DataType::IsIntegralType(other_type));
268 DCHECK(DataType::IsIntegralType(vector_type));
269 DCHECK_GE(DataType::SizeShift(other_type), DataType::SizeShift(vector_type));
270 return vl >> (DataType::SizeShift(other_type) - DataType::SizeShift(vector_type));
Aart Bikdbbac8f2017-09-01 13:06:08 -0700271}
272
Aart Bik5f805002017-05-16 16:42:41 -0700273// Detect up to two instructions a and b, and an acccumulated constant c.
274static bool IsAddConstHelper(HInstruction* instruction,
275 /*out*/ HInstruction** a,
276 /*out*/ HInstruction** b,
277 /*out*/ int64_t* c,
278 int32_t depth) {
279 static constexpr int32_t kMaxDepth = 8; // don't search too deep
280 int64_t value = 0;
281 if (IsInt64AndGet(instruction, &value)) {
282 *c += value;
283 return true;
284 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
285 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
286 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
287 } else if (*a == nullptr) {
288 *a = instruction;
289 return true;
290 } else if (*b == nullptr) {
291 *b = instruction;
292 return true;
293 }
294 return false; // too many non-const operands
295}
296
297// Detect a + b + c for an optional constant c.
298static bool IsAddConst(HInstruction* instruction,
299 /*out*/ HInstruction** a,
300 /*out*/ HInstruction** b,
301 /*out*/ int64_t* c) {
302 if (instruction->IsAdd()) {
303 // Try to find a + b and accumulated c.
304 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
305 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
306 *b != nullptr) {
307 return true;
308 }
309 // Found a + b.
310 *a = instruction->InputAt(0);
311 *b = instruction->InputAt(1);
312 *c = 0;
313 return true;
314 }
315 return false;
316}
317
Aart Bikdf011c32017-09-28 12:53:04 -0700318// Detect a + c for constant c.
319static bool IsAddConst(HInstruction* instruction,
320 /*out*/ HInstruction** a,
321 /*out*/ int64_t* c) {
322 if (instruction->IsAdd()) {
323 if (IsInt64AndGet(instruction->InputAt(0), c)) {
324 *a = instruction->InputAt(1);
325 return true;
326 } else if (IsInt64AndGet(instruction->InputAt(1), c)) {
327 *a = instruction->InputAt(0);
328 return true;
329 }
330 }
331 return false;
332}
333
Aart Bikb29f6842017-07-28 15:58:41 -0700334// Detect reductions of the following forms,
Aart Bikb29f6842017-07-28 15:58:41 -0700335// x = x_phi + ..
336// x = x_phi - ..
Aart Bikb29f6842017-07-28 15:58:41 -0700337static bool HasReductionFormat(HInstruction* reduction, HInstruction* phi) {
338 if (reduction->IsAdd()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700339 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi) ||
340 (reduction->InputAt(0) != phi && reduction->InputAt(1) == phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700341 } else if (reduction->IsSub()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700342 return (reduction->InputAt(0) == phi && reduction->InputAt(1) != phi);
Aart Bikb29f6842017-07-28 15:58:41 -0700343 }
344 return false;
345}
346
Aart Bikdbbac8f2017-09-01 13:06:08 -0700347// Translates vector operation to reduction kind.
348static HVecReduce::ReductionKind GetReductionKind(HVecOperation* reduction) {
349 if (reduction->IsVecAdd() || reduction->IsVecSub() || reduction->IsVecSADAccumulate()) {
Aart Bik0148de42017-09-05 09:25:01 -0700350 return HVecReduce::kSum;
Aart Bik0148de42017-09-05 09:25:01 -0700351 }
Aart Bik38a3f212017-10-20 17:02:21 -0700352 LOG(FATAL) << "Unsupported SIMD reduction " << reduction->GetId();
Aart Bik0148de42017-09-05 09:25:01 -0700353 UNREACHABLE();
354}
355
Aart Bikf8f5a162017-02-06 15:35:29 -0800356// Test vector restrictions.
357static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
358 return (restrictions & tested) != 0;
359}
360
Aart Bikf3e61ee2017-04-12 17:09:20 -0700361// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800362static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
363 DCHECK(block != nullptr);
364 DCHECK(instruction != nullptr);
365 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
366 return instruction;
367}
368
Artem Serov21c7e6f2017-07-27 16:04:42 +0100369// Check that instructions from the induction sets are fully removed: have no uses
370// and no other instructions use them.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100371static bool CheckInductionSetFullyRemoved(ScopedArenaSet<HInstruction*>* iset) {
Artem Serov21c7e6f2017-07-27 16:04:42 +0100372 for (HInstruction* instr : *iset) {
373 if (instr->GetBlock() != nullptr ||
374 !instr->GetUses().empty() ||
375 !instr->GetEnvUses().empty() ||
376 HasEnvironmentUsedByOthers(instr)) {
377 return false;
378 }
379 }
Artem Serov21c7e6f2017-07-27 16:04:42 +0100380 return true;
381}
382
Aart Bik281c6812016-08-26 11:31:48 -0700383//
Aart Bikb29f6842017-07-28 15:58:41 -0700384// Public methods.
Aart Bik281c6812016-08-26 11:31:48 -0700385//
386
387HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800388 CompilerDriver* compiler_driver,
Aart Bikb92cc332017-09-06 15:53:17 -0700389 HInductionVarAnalysis* induction_analysis,
Aart Bik2ca10eb2017-11-15 15:17:53 -0800390 OptimizingCompilerStats* stats,
391 const char* name)
392 : HOptimization(graph, name, stats),
Aart Bik92685a82017-03-06 11:13:43 -0800393 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700394 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700395 loop_allocator_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100396 global_allocator_(graph_->GetAllocator()),
Aart Bik281c6812016-08-26 11:31:48 -0700397 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700398 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700399 iset_(nullptr),
Aart Bikb29f6842017-07-28 15:58:41 -0700400 reductions_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800401 simplified_(false),
402 vector_length_(0),
403 vector_refs_(nullptr),
Aart Bik38a3f212017-10-20 17:02:21 -0700404 vector_static_peeling_factor_(0),
405 vector_dynamic_peeling_candidate_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700406 vector_runtime_test_a_(nullptr),
407 vector_runtime_test_b_(nullptr),
Aart Bik0148de42017-09-05 09:25:01 -0700408 vector_map_(nullptr),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100409 vector_permanent_map_(nullptr),
410 vector_mode_(kSequential),
411 vector_preheader_(nullptr),
412 vector_header_(nullptr),
413 vector_body_(nullptr),
414 vector_index_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700415}
416
417void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800418 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700419 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800420 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700421 return;
422 }
423
Vladimir Markoca6fff82017-10-03 14:49:14 +0100424 // Phase-local allocator.
425 ScopedArenaAllocator allocator(graph_->GetArenaStack());
Aart Bik96202302016-10-04 17:33:56 -0700426 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100427
Aart Bik96202302016-10-04 17:33:56 -0700428 // Perform loop optimizations.
429 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800430 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800431 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800432 }
433
Aart Bik96202302016-10-04 17:33:56 -0700434 // Detach.
435 loop_allocator_ = nullptr;
436 last_loop_ = top_loop_ = nullptr;
437}
438
Aart Bikb29f6842017-07-28 15:58:41 -0700439//
440// Loop setup and traversal.
441//
442
Aart Bik96202302016-10-04 17:33:56 -0700443void HLoopOptimization::LocalRun() {
444 // Build the linear order using the phase-local allocator. This step enables building
445 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100446 ScopedArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
447 LinearizeGraph(graph_, &linear_order);
Aart Bik96202302016-10-04 17:33:56 -0700448
Aart Bik281c6812016-08-26 11:31:48 -0700449 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700450 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700451 if (block->IsLoopHeader()) {
452 AddLoop(block->GetLoopInformation());
453 }
454 }
Aart Bik96202302016-10-04 17:33:56 -0700455
Aart Bik8c4a8542016-10-06 11:36:57 -0700456 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800457 // temporary data structures using the phase-local allocator. All new HIR
458 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700459 if (top_loop_ != nullptr) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100460 ScopedArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
461 ScopedArenaSafeMap<HInstruction*, HInstruction*> reds(
Aart Bikb29f6842017-07-28 15:58:41 -0700462 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100463 ScopedArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
464 ScopedArenaSafeMap<HInstruction*, HInstruction*> map(
Aart Bikf8f5a162017-02-06 15:35:29 -0800465 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Vladimir Markoca6fff82017-10-03 14:49:14 +0100466 ScopedArenaSafeMap<HInstruction*, HInstruction*> perm(
Aart Bik0148de42017-09-05 09:25:01 -0700467 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800468 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700469 iset_ = &iset;
Aart Bikb29f6842017-07-28 15:58:41 -0700470 reductions_ = &reds;
Aart Bikf8f5a162017-02-06 15:35:29 -0800471 vector_refs_ = &refs;
472 vector_map_ = &map;
Aart Bik0148de42017-09-05 09:25:01 -0700473 vector_permanent_map_ = &perm;
Aart Bikf8f5a162017-02-06 15:35:29 -0800474 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700475 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800476 // Detach.
477 iset_ = nullptr;
Aart Bikb29f6842017-07-28 15:58:41 -0700478 reductions_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800479 vector_refs_ = nullptr;
480 vector_map_ = nullptr;
Aart Bik0148de42017-09-05 09:25:01 -0700481 vector_permanent_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700482 }
Aart Bik281c6812016-08-26 11:31:48 -0700483}
484
485void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
486 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800487 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700488 if (last_loop_ == nullptr) {
489 // First loop.
490 DCHECK(top_loop_ == nullptr);
491 last_loop_ = top_loop_ = node;
492 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
493 // Inner loop.
494 node->outer = last_loop_;
495 DCHECK(last_loop_->inner == nullptr);
496 last_loop_ = last_loop_->inner = node;
497 } else {
498 // Subsequent loop.
499 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
500 last_loop_ = last_loop_->outer;
501 }
502 node->outer = last_loop_->outer;
503 node->previous = last_loop_;
504 DCHECK(last_loop_->next == nullptr);
505 last_loop_ = last_loop_->next = node;
506 }
507}
508
509void HLoopOptimization::RemoveLoop(LoopNode* node) {
510 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700511 DCHECK(node->inner == nullptr);
512 if (node->previous != nullptr) {
513 // Within sequence.
514 node->previous->next = node->next;
515 if (node->next != nullptr) {
516 node->next->previous = node->previous;
517 }
518 } else {
519 // First of sequence.
520 if (node->outer != nullptr) {
521 node->outer->inner = node->next;
522 } else {
523 top_loop_ = node->next;
524 }
525 if (node->next != nullptr) {
526 node->next->outer = node->outer;
527 node->next->previous = nullptr;
528 }
529 }
Aart Bik281c6812016-08-26 11:31:48 -0700530}
531
Aart Bikb29f6842017-07-28 15:58:41 -0700532bool HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
533 bool changed = false;
Aart Bik281c6812016-08-26 11:31:48 -0700534 for ( ; node != nullptr; node = node->next) {
Aart Bikb29f6842017-07-28 15:58:41 -0700535 // Visit inner loops first. Recompute induction information for this
536 // loop if the induction of any inner loop has changed.
537 if (TraverseLoopsInnerToOuter(node->inner)) {
Aart Bik482095d2016-10-10 15:39:10 -0700538 induction_range_.ReVisit(node->loop_info);
539 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800540 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800541 // Note that since each simplification consists of eliminating code (without
542 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800543 do {
544 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800545 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800546 SimplifyBlocks(node);
Aart Bikb29f6842017-07-28 15:58:41 -0700547 changed = simplified_ || changed;
Aart Bikdf7822e2016-12-06 10:05:30 -0800548 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800549 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700550 if (node->inner == nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700551 changed = OptimizeInnerLoop(node) || changed;
Aart Bik9abf8942016-10-14 09:49:42 -0700552 }
Aart Bik281c6812016-08-26 11:31:48 -0700553 }
Aart Bikb29f6842017-07-28 15:58:41 -0700554 return changed;
Aart Bik281c6812016-08-26 11:31:48 -0700555}
556
Aart Bikf8f5a162017-02-06 15:35:29 -0800557//
558// Optimization.
559//
560
Aart Bik281c6812016-08-26 11:31:48 -0700561void HLoopOptimization::SimplifyInduction(LoopNode* node) {
562 HBasicBlock* header = node->loop_info->GetHeader();
563 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700564 // Scan the phis in the header to find opportunities to simplify an induction
565 // cycle that is only used outside the loop. Replace these uses, if any, with
566 // the last value and remove the induction cycle.
567 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
568 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700569 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
570 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800571 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
572 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik671e48a2017-08-09 13:16:56 -0700573 // Note that it's ok to have replaced uses after the loop with the last value, without
574 // being able to remove the cycle. Environment uses (which are the reason we may not be
575 // able to remove the cycle) within the loop will still hold the right value. We must
576 // have tried first, however, to replace outside uses.
577 if (CanRemoveCycle()) {
578 simplified_ = true;
579 for (HInstruction* i : *iset_) {
580 RemoveFromCycle(i);
581 }
582 DCHECK(CheckInductionSetFullyRemoved(iset_));
Aart Bik281c6812016-08-26 11:31:48 -0700583 }
Aart Bik482095d2016-10-10 15:39:10 -0700584 }
585 }
586}
587
588void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800589 // Iterate over all basic blocks in the loop-body.
590 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
591 HBasicBlock* block = it.Current();
592 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800593 RemoveDeadInstructions(block->GetPhis());
594 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800595 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800596 if (block->GetPredecessors().size() == 1 &&
597 block->GetSuccessors().size() == 1 &&
598 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800599 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800600 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800601 } else if (block->GetSuccessors().size() == 2) {
602 // Trivial if block can be bypassed to either branch.
603 HBasicBlock* succ0 = block->GetSuccessors()[0];
604 HBasicBlock* succ1 = block->GetSuccessors()[1];
605 HBasicBlock* meet0 = nullptr;
606 HBasicBlock* meet1 = nullptr;
607 if (succ0 != succ1 &&
608 IsGotoBlock(succ0, &meet0) &&
609 IsGotoBlock(succ1, &meet1) &&
610 meet0 == meet1 && // meets again
611 meet0 != block && // no self-loop
612 meet0->GetPhis().IsEmpty()) { // not used for merging
613 simplified_ = true;
614 succ0->DisconnectAndDelete();
615 if (block->Dominates(meet0)) {
616 block->RemoveDominatedBlock(meet0);
617 succ1->AddDominatedBlock(meet0);
618 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700619 }
Aart Bik482095d2016-10-10 15:39:10 -0700620 }
Aart Bik281c6812016-08-26 11:31:48 -0700621 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800622 }
Aart Bik281c6812016-08-26 11:31:48 -0700623}
624
Aart Bikb29f6842017-07-28 15:58:41 -0700625bool HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700626 HBasicBlock* header = node->loop_info->GetHeader();
627 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700628 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800629 int64_t trip_count = 0;
630 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
Aart Bikb29f6842017-07-28 15:58:41 -0700631 return false;
Aart Bik9abf8942016-10-14 09:49:42 -0700632 }
Aart Bik281c6812016-08-26 11:31:48 -0700633 // Ensure there is only a single loop-body (besides the header).
634 HBasicBlock* body = nullptr;
635 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
636 if (it.Current() != header) {
637 if (body != nullptr) {
Aart Bikb29f6842017-07-28 15:58:41 -0700638 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700639 }
640 body = it.Current();
641 }
642 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700643 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700644 // Ensure there is only a single exit point.
645 if (header->GetSuccessors().size() != 2) {
Aart Bikb29f6842017-07-28 15:58:41 -0700646 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700647 }
648 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
649 ? header->GetSuccessors()[1]
650 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700651 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700652 if (exit->GetPredecessors().size() != 1) {
Aart Bikb29f6842017-07-28 15:58:41 -0700653 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700654 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800655 // Detect either an empty loop (no side effects other than plain iteration) or
656 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
657 // with the last value and remove the loop, possibly after unrolling its body.
Aart Bikb29f6842017-07-28 15:58:41 -0700658 HPhi* main_phi = nullptr;
659 if (TrySetSimpleLoopHeader(header, &main_phi)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800660 bool is_empty = IsEmptyBody(body);
Aart Bikb29f6842017-07-28 15:58:41 -0700661 if (reductions_->empty() && // TODO: possible with some effort
662 (is_empty || trip_count == 1) &&
663 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800664 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800665 // Unroll the loop-body, which sees initial value of the index.
Aart Bikb29f6842017-07-28 15:58:41 -0700666 main_phi->ReplaceWith(main_phi->InputAt(0));
Aart Bik6b69e0a2017-01-11 10:20:43 -0800667 preheader->MergeInstructionsWith(body);
668 }
669 body->DisconnectAndDelete();
670 exit->RemovePredecessor(header);
671 header->RemoveSuccessor(exit);
672 header->RemoveDominatedBlock(exit);
673 header->DisconnectAndDelete();
674 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800675 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800676 preheader->AddDominatedBlock(exit);
677 exit->SetDominator(preheader);
678 RemoveLoop(node); // update hierarchy
Aart Bikb29f6842017-07-28 15:58:41 -0700679 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800680 }
681 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800682 // Vectorize loop, if possible and valid.
Aart Bikb29f6842017-07-28 15:58:41 -0700683 if (kEnableVectorization &&
684 TrySetSimpleLoopHeader(header, &main_phi) &&
Aart Bikb29f6842017-07-28 15:58:41 -0700685 ShouldVectorize(node, body, trip_count) &&
686 TryAssignLastValue(node->loop_info, main_phi, preheader, /*collect_loop_uses*/ true)) {
687 Vectorize(node, body, exit, trip_count);
688 graph_->SetHasSIMD(true); // flag SIMD usage
Aart Bik21b85922017-09-06 13:29:16 -0700689 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorized);
Aart Bikb29f6842017-07-28 15:58:41 -0700690 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800691 }
Aart Bikb29f6842017-07-28 15:58:41 -0700692 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800693}
694
695//
696// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
697// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
698// Intel Press, June, 2004 (http://www.aartbik.com/).
699//
700
Aart Bik14a68b42017-06-08 14:06:58 -0700701bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800702 // Reset vector bookkeeping.
703 vector_length_ = 0;
704 vector_refs_->clear();
Aart Bik38a3f212017-10-20 17:02:21 -0700705 vector_static_peeling_factor_ = 0;
706 vector_dynamic_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800707 vector_runtime_test_a_ =
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800708 vector_runtime_test_b_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800709
710 // Phis in the loop-body prevent vectorization.
711 if (!block->GetPhis().IsEmpty()) {
712 return false;
713 }
714
715 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
716 // occurrence, which allows passing down attributes down the use tree.
717 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
718 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
719 return false; // failure to vectorize a left-hand-side
720 }
721 }
722
Aart Bik38a3f212017-10-20 17:02:21 -0700723 // Prepare alignment analysis:
724 // (1) find desired alignment (SIMD vector size in bytes).
725 // (2) initialize static loop peeling votes (peeling factor that will
726 // make one particular reference aligned), never to exceed (1).
727 // (3) variable to record how many references share same alignment.
728 // (4) variable to record suitable candidate for dynamic loop peeling.
729 uint32_t desired_alignment = GetVectorSizeInBytes();
730 DCHECK_LE(desired_alignment, 16u);
731 uint32_t peeling_votes[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
732 uint32_t max_num_same_alignment = 0;
733 const ArrayReference* peeling_candidate = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800734
735 // Data dependence analysis. Find each pair of references with same type, where
736 // at least one is a write. Each such pair denotes a possible data dependence.
737 // This analysis exploits the property that differently typed arrays cannot be
738 // aliased, as well as the property that references either point to the same
739 // array or to two completely disjoint arrays, i.e., no partial aliasing.
740 // Other than a few simply heuristics, no detailed subscript analysis is done.
Aart Bik38a3f212017-10-20 17:02:21 -0700741 // The scan over references also prepares finding a suitable alignment strategy.
Aart Bikf8f5a162017-02-06 15:35:29 -0800742 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
Aart Bik38a3f212017-10-20 17:02:21 -0700743 uint32_t num_same_alignment = 0;
744 // Scan over all next references.
Aart Bikf8f5a162017-02-06 15:35:29 -0800745 for (auto j = i; ++j != vector_refs_->end(); ) {
746 if (i->type == j->type && (i->lhs || j->lhs)) {
747 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
748 HInstruction* a = i->base;
749 HInstruction* b = j->base;
750 HInstruction* x = i->offset;
751 HInstruction* y = j->offset;
752 if (a == b) {
753 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
754 // Conservatively assume a loop-carried data dependence otherwise, and reject.
755 if (x != y) {
756 return false;
757 }
Aart Bik38a3f212017-10-20 17:02:21 -0700758 // Count the number of references that have the same alignment (since
759 // base and offset are the same) and where at least one is a write, so
760 // e.g. a[i] = a[i] + b[i] counts a[i] but not b[i]).
761 num_same_alignment++;
Aart Bikf8f5a162017-02-06 15:35:29 -0800762 } else {
763 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
764 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
765 // generating an explicit a != b disambiguation runtime test on the two references.
766 if (x != y) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700767 // To avoid excessive overhead, we only accept one a != b test.
768 if (vector_runtime_test_a_ == nullptr) {
769 // First test found.
770 vector_runtime_test_a_ = a;
771 vector_runtime_test_b_ = b;
772 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
773 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
774 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800775 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800776 }
777 }
778 }
779 }
Aart Bik38a3f212017-10-20 17:02:21 -0700780 // Update information for finding suitable alignment strategy:
781 // (1) update votes for static loop peeling,
782 // (2) update suitable candidate for dynamic loop peeling.
783 Alignment alignment = ComputeAlignment(i->offset, i->type, i->is_string_char_at);
784 if (alignment.Base() >= desired_alignment) {
785 // If the array/string object has a known, sufficient alignment, use the
786 // initial offset to compute the static loop peeling vote (this always
787 // works, since elements have natural alignment).
788 uint32_t offset = alignment.Offset() & (desired_alignment - 1u);
789 uint32_t vote = (offset == 0)
790 ? 0
791 : ((desired_alignment - offset) >> DataType::SizeShift(i->type));
792 DCHECK_LT(vote, 16u);
793 ++peeling_votes[vote];
794 } else if (BaseAlignment() >= desired_alignment &&
795 num_same_alignment > max_num_same_alignment) {
796 // Otherwise, if the array/string object has a known, sufficient alignment
797 // for just the base but with an unknown offset, record the candidate with
798 // the most occurrences for dynamic loop peeling (again, the peeling always
799 // works, since elements have natural alignment).
800 max_num_same_alignment = num_same_alignment;
801 peeling_candidate = &(*i);
802 }
803 } // for i
Aart Bikf8f5a162017-02-06 15:35:29 -0800804
Aart Bik38a3f212017-10-20 17:02:21 -0700805 // Find a suitable alignment strategy.
806 SetAlignmentStrategy(peeling_votes, peeling_candidate);
807
808 // Does vectorization seem profitable?
809 if (!IsVectorizationProfitable(trip_count)) {
810 return false;
811 }
Aart Bik14a68b42017-06-08 14:06:58 -0700812
Aart Bikf8f5a162017-02-06 15:35:29 -0800813 // Success!
814 return true;
815}
816
817void HLoopOptimization::Vectorize(LoopNode* node,
818 HBasicBlock* block,
819 HBasicBlock* exit,
820 int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800821 HBasicBlock* header = node->loop_info->GetHeader();
822 HBasicBlock* preheader = node->loop_info->GetPreHeader();
823
Aart Bik14a68b42017-06-08 14:06:58 -0700824 // Pick a loop unrolling factor for the vector loop.
825 uint32_t unroll = GetUnrollingFactor(block, trip_count);
826 uint32_t chunk = vector_length_ * unroll;
827
Aart Bik38a3f212017-10-20 17:02:21 -0700828 DCHECK(trip_count == 0 || (trip_count >= MaxNumberPeeled() + chunk));
829
Aart Bik14a68b42017-06-08 14:06:58 -0700830 // A cleanup loop is needed, at least, for any unknown trip count or
831 // for a known trip count with remainder iterations after vectorization.
Aart Bik38a3f212017-10-20 17:02:21 -0700832 bool needs_cleanup = trip_count == 0 ||
833 ((trip_count - vector_static_peeling_factor_) % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800834
835 // Adjust vector bookkeeping.
Aart Bikb29f6842017-07-28 15:58:41 -0700836 HPhi* main_phi = nullptr;
837 bool is_simple_loop_header = TrySetSimpleLoopHeader(header, &main_phi); // refills sets
Aart Bikf8f5a162017-02-06 15:35:29 -0800838 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700839 vector_header_ = header;
840 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800841
Aart Bikdbbac8f2017-09-01 13:06:08 -0700842 // Loop induction type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100843 DataType::Type induc_type = main_phi->GetType();
844 DCHECK(induc_type == DataType::Type::kInt32 || induc_type == DataType::Type::kInt64)
845 << induc_type;
Aart Bikdbbac8f2017-09-01 13:06:08 -0700846
Aart Bik38a3f212017-10-20 17:02:21 -0700847 // Generate the trip count for static or dynamic loop peeling, if needed:
848 // ptc = <peeling factor>;
Aart Bik14a68b42017-06-08 14:06:58 -0700849 HInstruction* ptc = nullptr;
Aart Bik38a3f212017-10-20 17:02:21 -0700850 if (vector_static_peeling_factor_ != 0) {
851 // Static loop peeling for SIMD alignment (using the most suitable
852 // fixed peeling factor found during prior alignment analysis).
853 DCHECK(vector_dynamic_peeling_candidate_ == nullptr);
854 ptc = graph_->GetConstant(induc_type, vector_static_peeling_factor_);
855 } else if (vector_dynamic_peeling_candidate_ != nullptr) {
856 // Dynamic loop peeling for SIMD alignment (using the most suitable
857 // candidate found during prior alignment analysis):
858 // rem = offset % ALIGN; // adjusted as #elements
859 // ptc = rem == 0 ? 0 : (ALIGN - rem);
860 uint32_t shift = DataType::SizeShift(vector_dynamic_peeling_candidate_->type);
861 uint32_t align = GetVectorSizeInBytes() >> shift;
862 uint32_t hidden_offset = HiddenOffset(vector_dynamic_peeling_candidate_->type,
863 vector_dynamic_peeling_candidate_->is_string_char_at);
864 HInstruction* adjusted_offset = graph_->GetConstant(induc_type, hidden_offset >> shift);
865 HInstruction* offset = Insert(preheader, new (global_allocator_) HAdd(
866 induc_type, vector_dynamic_peeling_candidate_->offset, adjusted_offset));
867 HInstruction* rem = Insert(preheader, new (global_allocator_) HAnd(
868 induc_type, offset, graph_->GetConstant(induc_type, align - 1u)));
869 HInstruction* sub = Insert(preheader, new (global_allocator_) HSub(
870 induc_type, graph_->GetConstant(induc_type, align), rem));
871 HInstruction* cond = Insert(preheader, new (global_allocator_) HEqual(
872 rem, graph_->GetConstant(induc_type, 0)));
873 ptc = Insert(preheader, new (global_allocator_) HSelect(
874 cond, graph_->GetConstant(induc_type, 0), sub, kNoDexPc));
875 needs_cleanup = true; // don't know the exact amount
Aart Bik14a68b42017-06-08 14:06:58 -0700876 }
877
878 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800879 // stc = <trip-count>;
Aart Bik38a3f212017-10-20 17:02:21 -0700880 // ptc = min(stc, ptc);
Aart Bik14a68b42017-06-08 14:06:58 -0700881 // vtc = stc - (stc - ptc) % chunk;
882 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800883 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
884 HInstruction* vtc = stc;
885 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700886 DCHECK(IsPowerOfTwo(chunk));
887 HInstruction* diff = stc;
888 if (ptc != nullptr) {
Aart Bik38a3f212017-10-20 17:02:21 -0700889 if (trip_count == 0) {
890 HInstruction* cond = Insert(preheader, new (global_allocator_) HAboveOrEqual(stc, ptc));
891 ptc = Insert(preheader, new (global_allocator_) HSelect(cond, ptc, stc, kNoDexPc));
892 }
Aart Bik14a68b42017-06-08 14:06:58 -0700893 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
894 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800895 HInstruction* rem = Insert(
896 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700897 diff,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700898 graph_->GetConstant(induc_type, chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800899 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
900 }
Aart Bikdbbac8f2017-09-01 13:06:08 -0700901 vector_index_ = graph_->GetConstant(induc_type, 0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800902
903 // Generate runtime disambiguation test:
904 // vtc = a != b ? vtc : 0;
905 if (vector_runtime_test_a_ != nullptr) {
906 HInstruction* rt = Insert(
907 preheader,
908 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
909 vtc = Insert(preheader,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700910 new (global_allocator_)
911 HSelect(rt, vtc, graph_->GetConstant(induc_type, 0), kNoDexPc));
Aart Bikf8f5a162017-02-06 15:35:29 -0800912 needs_cleanup = true;
913 }
914
Aart Bik38a3f212017-10-20 17:02:21 -0700915 // Generate alignment peeling loop, if needed:
Aart Bik14a68b42017-06-08 14:06:58 -0700916 // for ( ; i < ptc; i += 1)
917 // <loop-body>
Aart Bik38a3f212017-10-20 17:02:21 -0700918 //
919 // NOTE: The alignment forced by the peeling loop is preserved even if data is
920 // moved around during suspend checks, since all analysis was based on
921 // nothing more than the Android runtime alignment conventions.
Aart Bik14a68b42017-06-08 14:06:58 -0700922 if (ptc != nullptr) {
923 vector_mode_ = kSequential;
924 GenerateNewLoop(node,
925 block,
926 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
927 vector_index_,
928 ptc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700929 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700930 kNoUnrollingFactor);
Aart Bik14a68b42017-06-08 14:06:58 -0700931 }
932
933 // Generate vector loop, possibly further unrolled:
934 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800935 // <vectorized-loop-body>
936 vector_mode_ = kVector;
937 GenerateNewLoop(node,
938 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700939 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
940 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800941 vtc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700942 graph_->GetConstant(induc_type, vector_length_), // increment per unroll
Aart Bik14a68b42017-06-08 14:06:58 -0700943 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800944 HLoopInformation* vloop = vector_header_->GetLoopInformation();
945
946 // Generate cleanup loop, if needed:
947 // for ( ; i < stc; i += 1)
948 // <loop-body>
949 if (needs_cleanup) {
950 vector_mode_ = kSequential;
951 GenerateNewLoop(node,
952 block,
953 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700954 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800955 stc,
Aart Bikdbbac8f2017-09-01 13:06:08 -0700956 graph_->GetConstant(induc_type, 1),
Aart Bik521b50f2017-09-09 10:44:45 -0700957 kNoUnrollingFactor);
Aart Bikf8f5a162017-02-06 15:35:29 -0800958 }
959
Aart Bik0148de42017-09-05 09:25:01 -0700960 // Link reductions to their final uses.
961 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
962 if (i->first->IsPhi()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -0700963 HInstruction* phi = i->first;
964 HInstruction* repl = ReduceAndExtractIfNeeded(i->second);
965 // Deal with regular uses.
966 for (const HUseListNode<HInstruction*>& use : phi->GetUses()) {
967 induction_range_.Replace(use.GetUser(), phi, repl); // update induction use
968 }
969 phi->ReplaceWith(repl);
Aart Bik0148de42017-09-05 09:25:01 -0700970 }
971 }
972
Aart Bikf8f5a162017-02-06 15:35:29 -0800973 // Remove the original loop by disconnecting the body block
974 // and removing all instructions from the header.
975 block->DisconnectAndDelete();
976 while (!header->GetFirstInstruction()->IsGoto()) {
977 header->RemoveInstruction(header->GetFirstInstruction());
978 }
Aart Bikb29f6842017-07-28 15:58:41 -0700979
Aart Bik14a68b42017-06-08 14:06:58 -0700980 // Update loop hierarchy: the old header now resides in the same outer loop
981 // as the old preheader. Note that we don't bother putting sequential
982 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800983 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
984 node->loop_info = vloop;
985}
986
987void HLoopOptimization::GenerateNewLoop(LoopNode* node,
988 HBasicBlock* block,
989 HBasicBlock* new_preheader,
990 HInstruction* lo,
991 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700992 HInstruction* step,
993 uint32_t unroll) {
994 DCHECK(unroll == 1 || vector_mode_ == kVector);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100995 DataType::Type induc_type = lo->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -0800996 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800997 vector_preheader_ = new_preheader,
998 vector_header_ = vector_preheader_->GetSingleSuccessor();
999 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -07001000 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
1001 kNoRegNumber,
1002 0,
1003 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -07001004 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -08001005 // for (i = lo; i < hi; i += step)
1006 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -07001007 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
1008 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -08001009 vector_header_->AddInstruction(cond);
1010 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -07001011 vector_index_ = phi;
Aart Bik0148de42017-09-05 09:25:01 -07001012 vector_permanent_map_->clear(); // preserved over unrolling
Aart Bik14a68b42017-06-08 14:06:58 -07001013 for (uint32_t u = 0; u < unroll; u++) {
Aart Bik14a68b42017-06-08 14:06:58 -07001014 // Generate instruction map.
Aart Bik0148de42017-09-05 09:25:01 -07001015 vector_map_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -07001016 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1017 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
1018 DCHECK(vectorized_def);
1019 }
1020 // Generate body from the instruction map, but in original program order.
1021 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
1022 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1023 auto i = vector_map_->find(it.Current());
1024 if (i != vector_map_->end() && !i->second->IsInBlock()) {
1025 Insert(vector_body_, i->second);
1026 // Deal with instructions that need an environment, such as the scalar intrinsics.
1027 if (i->second->NeedsEnvironment()) {
1028 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
1029 }
1030 }
1031 }
Aart Bik0148de42017-09-05 09:25:01 -07001032 // Generate the induction.
Aart Bik14a68b42017-06-08 14:06:58 -07001033 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
1034 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001035 }
Aart Bik0148de42017-09-05 09:25:01 -07001036 // Finalize phi inputs for the reductions (if any).
1037 for (auto i = reductions_->begin(); i != reductions_->end(); ++i) {
1038 if (!i->first->IsPhi()) {
1039 DCHECK(i->second->IsPhi());
1040 GenerateVecReductionPhiInputs(i->second->AsPhi(), i->first);
1041 }
1042 }
Aart Bikb29f6842017-07-28 15:58:41 -07001043 // Finalize phi inputs for the loop index.
Aart Bik14a68b42017-06-08 14:06:58 -07001044 phi->AddInput(lo);
1045 phi->AddInput(vector_index_);
1046 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -08001047}
1048
Aart Bikf8f5a162017-02-06 15:35:29 -08001049bool HLoopOptimization::VectorizeDef(LoopNode* node,
1050 HInstruction* instruction,
1051 bool generate_code) {
1052 // Accept a left-hand-side array base[index] for
1053 // (1) supported vector type,
1054 // (2) loop-invariant base,
1055 // (3) unit stride index,
1056 // (4) vectorizable right-hand-side value.
1057 uint64_t restrictions = kNone;
1058 if (instruction->IsArraySet()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001059 DataType::Type type = instruction->AsArraySet()->GetComponentType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001060 HInstruction* base = instruction->InputAt(0);
1061 HInstruction* index = instruction->InputAt(1);
1062 HInstruction* value = instruction->InputAt(2);
1063 HInstruction* offset = nullptr;
1064 if (TrySetVectorType(type, &restrictions) &&
1065 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001066 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001067 VectorizeUse(node, value, generate_code, type, restrictions)) {
1068 if (generate_code) {
1069 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001070 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001071 } else {
1072 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
1073 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001074 return true;
1075 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001076 return false;
1077 }
Aart Bik0148de42017-09-05 09:25:01 -07001078 // Accept a left-hand-side reduction for
1079 // (1) supported vector type,
1080 // (2) vectorizable right-hand-side value.
1081 auto redit = reductions_->find(instruction);
1082 if (redit != reductions_->end()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001083 DataType::Type type = instruction->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001084 // Recognize SAD idiom or direct reduction.
1085 if (VectorizeSADIdiom(node, instruction, generate_code, type, restrictions) ||
1086 (TrySetVectorType(type, &restrictions) &&
1087 VectorizeUse(node, instruction, generate_code, type, restrictions))) {
Aart Bik0148de42017-09-05 09:25:01 -07001088 if (generate_code) {
1089 HInstruction* new_red = vector_map_->Get(instruction);
1090 vector_permanent_map_->Put(new_red, vector_map_->Get(redit->second));
1091 vector_permanent_map_->Overwrite(redit->second, new_red);
1092 }
1093 return true;
1094 }
1095 return false;
1096 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001097 // Branch back okay.
1098 if (instruction->IsGoto()) {
1099 return true;
1100 }
1101 // Otherwise accept only expressions with no effects outside the immediate loop-body.
1102 // Note that actual uses are inspected during right-hand-side tree traversal.
1103 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
1104}
1105
Aart Bikf8f5a162017-02-06 15:35:29 -08001106bool HLoopOptimization::VectorizeUse(LoopNode* node,
1107 HInstruction* instruction,
1108 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001109 DataType::Type type,
Aart Bikf8f5a162017-02-06 15:35:29 -08001110 uint64_t restrictions) {
1111 // Accept anything for which code has already been generated.
1112 if (generate_code) {
1113 if (vector_map_->find(instruction) != vector_map_->end()) {
1114 return true;
1115 }
1116 }
1117 // Continue the right-hand-side tree traversal, passing in proper
1118 // types and vector restrictions along the way. During code generation,
1119 // all new nodes are drawn from the global allocator.
1120 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
1121 // Accept invariant use, using scalar expansion.
1122 if (generate_code) {
1123 GenerateVecInv(instruction, type);
1124 }
1125 return true;
1126 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001127 // Deal with vector restrictions.
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001128 bool is_string_char_at = instruction->AsArrayGet()->IsStringCharAt();
1129 if (is_string_char_at && HasVectorRestrictions(restrictions, kNoStringCharAt)) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001130 return false;
1131 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001132 // Accept a right-hand-side array base[index] for
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001133 // (1) matching vector type (exact match or signed/unsigned integral type of the same size),
Aart Bikf8f5a162017-02-06 15:35:29 -08001134 // (2) loop-invariant base,
1135 // (3) unit stride index,
1136 // (4) vectorizable right-hand-side value.
1137 HInstruction* base = instruction->InputAt(0);
1138 HInstruction* index = instruction->InputAt(1);
1139 HInstruction* offset = nullptr;
Aart Bik46b6dbc2017-10-03 11:37:37 -07001140 if (HVecOperation::ToSignedType(type) == HVecOperation::ToSignedType(instruction->GetType()) &&
Aart Bikf8f5a162017-02-06 15:35:29 -08001141 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -07001142 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001143 if (generate_code) {
1144 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -07001145 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -08001146 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001147 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false, is_string_char_at));
Aart Bikf8f5a162017-02-06 15:35:29 -08001148 }
1149 return true;
1150 }
Aart Bik0148de42017-09-05 09:25:01 -07001151 } else if (instruction->IsPhi()) {
1152 // Accept particular phi operations.
1153 if (reductions_->find(instruction) != reductions_->end()) {
1154 // Deal with vector restrictions.
1155 if (HasVectorRestrictions(restrictions, kNoReduction)) {
1156 return false;
1157 }
1158 // Accept a reduction.
1159 if (generate_code) {
1160 GenerateVecReductionPhi(instruction->AsPhi());
1161 }
1162 return true;
1163 }
1164 // TODO: accept right-hand-side induction?
1165 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001166 } else if (instruction->IsTypeConversion()) {
1167 // Accept particular type conversions.
1168 HTypeConversion* conversion = instruction->AsTypeConversion();
1169 HInstruction* opa = conversion->InputAt(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001170 DataType::Type from = conversion->GetInputType();
1171 DataType::Type to = conversion->GetResultType();
1172 if (DataType::IsIntegralType(from) && DataType::IsIntegralType(to)) {
Aart Bik38a3f212017-10-20 17:02:21 -07001173 uint32_t size_vec = DataType::Size(type);
1174 uint32_t size_from = DataType::Size(from);
1175 uint32_t size_to = DataType::Size(to);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001176 // Accept an integral conversion
1177 // (1a) narrowing into vector type, "wider" operations cannot bring in higher order bits, or
1178 // (1b) widening from at least vector type, and
1179 // (2) vectorizable operand.
1180 if ((size_to < size_from &&
1181 size_to == size_vec &&
1182 VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) ||
1183 (size_to >= size_from &&
1184 size_from >= size_vec &&
Aart Bik4d1a9d42017-10-19 14:40:55 -07001185 VectorizeUse(node, opa, generate_code, type, restrictions))) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001186 if (generate_code) {
1187 if (vector_mode_ == kVector) {
1188 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
1189 } else {
1190 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1191 }
1192 }
1193 return true;
1194 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001195 } else if (to == DataType::Type::kFloat32 && from == DataType::Type::kInt32) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001196 DCHECK_EQ(to, type);
1197 // Accept int to float conversion for
1198 // (1) supported int,
1199 // (2) vectorizable operand.
1200 if (TrySetVectorType(from, &restrictions) &&
1201 VectorizeUse(node, opa, generate_code, from, restrictions)) {
1202 if (generate_code) {
1203 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1204 }
1205 return true;
1206 }
1207 }
1208 return false;
1209 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
1210 // Accept unary operator for vectorizable operand.
1211 HInstruction* opa = instruction->InputAt(0);
1212 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
1213 if (generate_code) {
1214 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
1215 }
1216 return true;
1217 }
1218 } else if (instruction->IsAdd() || instruction->IsSub() ||
1219 instruction->IsMul() || instruction->IsDiv() ||
1220 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
1221 // Deal with vector restrictions.
1222 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
1223 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
1224 return false;
1225 }
1226 // Accept binary operator for vectorizable operands.
1227 HInstruction* opa = instruction->InputAt(0);
1228 HInstruction* opb = instruction->InputAt(1);
1229 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
1230 VectorizeUse(node, opb, generate_code, type, restrictions)) {
1231 if (generate_code) {
1232 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
1233 }
1234 return true;
1235 }
1236 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001237 // Recognize halving add idiom.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001238 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
1239 return true;
1240 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001241 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001242 HInstruction* opa = instruction->InputAt(0);
1243 HInstruction* opb = instruction->InputAt(1);
1244 HInstruction* r = opa;
1245 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001246 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
1247 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
1248 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -07001249 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
1250 // Shifts right need extra care to account for higher order bits.
1251 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
1252 if (instruction->IsShr() &&
1253 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1254 return false; // reject, unless all operands are sign-extension narrower
1255 } else if (instruction->IsUShr() &&
1256 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1257 return false; // reject, unless all operands are zero-extension narrower
1258 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001259 }
1260 // Accept shift operator for vectorizable/invariant operands.
1261 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001262 DCHECK(r != nullptr);
1263 if (generate_code && vector_mode_ != kVector) { // de-idiom
1264 r = opa;
1265 }
Aart Bik50e20d52017-05-05 14:07:29 -07001266 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001267 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001268 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001269 // Restrict shift distance to packed data type width.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001270 int64_t max_distance = DataType::Size(type) * 8;
Aart Bik65ffd8e2017-05-01 16:50:45 -07001271 if (0 <= distance && distance < max_distance) {
1272 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001273 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001274 }
1275 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001276 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001277 }
1278 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001279 // Accept particular intrinsics.
1280 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1281 switch (invoke->GetIntrinsic()) {
1282 case Intrinsics::kMathAbsInt:
1283 case Intrinsics::kMathAbsLong:
1284 case Intrinsics::kMathAbsFloat:
1285 case Intrinsics::kMathAbsDouble: {
1286 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001287 HInstruction* opa = instruction->InputAt(0);
1288 HInstruction* r = opa;
1289 bool is_unsigned = false;
1290 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001291 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001292 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1293 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1294 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001295 }
1296 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001297 DCHECK(r != nullptr);
1298 if (generate_code && vector_mode_ != kVector) { // de-idiom
1299 r = opa;
1300 }
1301 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001302 if (generate_code) {
Aart Bik66c158e2018-01-31 12:55:04 -08001303 GenerateVecOp(instruction,
1304 vector_map_->Get(r),
1305 nullptr,
1306 HVecOperation::ToProperType(type, is_unsigned));
Aart Bik6daebeb2017-04-03 14:35:41 -07001307 }
1308 return true;
1309 }
1310 return false;
1311 }
1312 default:
1313 return false;
1314 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001315 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001316 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001317}
1318
Aart Bik38a3f212017-10-20 17:02:21 -07001319uint32_t HLoopOptimization::GetVectorSizeInBytes() {
1320 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001321 case InstructionSet::kArm:
1322 case InstructionSet::kThumb2:
Aart Bik38a3f212017-10-20 17:02:21 -07001323 return 8; // 64-bit SIMD
1324 default:
1325 return 16; // 128-bit SIMD
1326 }
1327}
1328
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001329bool HLoopOptimization::TrySetVectorType(DataType::Type type, uint64_t* restrictions) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001330 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1331 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00001332 case InstructionSet::kArm:
1333 case InstructionSet::kThumb2:
Artem Serov8f7c4102017-06-21 11:21:37 +01001334 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001335 // ARM 32-bit always supports advanced SIMD (64-bit SIMD).
Artem Serov8f7c4102017-06-21 11:21:37 +01001336 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001337 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001338 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001339 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001340 *restrictions |= kNoDiv | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001341 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001342 case DataType::Type::kUint16:
1343 case DataType::Type::kInt16:
Aart Bik0148de42017-09-05 09:25:01 -07001344 *restrictions |= kNoDiv | kNoStringCharAt | kNoReduction;
Artem Serov8f7c4102017-06-21 11:21:37 +01001345 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001346 case DataType::Type::kInt32:
Artem Serov6e9b1372017-10-05 16:48:30 +01001347 *restrictions |= kNoDiv | kNoWideSAD;
Artem Serov8f7c4102017-06-21 11:21:37 +01001348 return TrySetVectorLength(2);
1349 default:
1350 break;
1351 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001352 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001353 case InstructionSet::kArm64:
Aart Bikf8f5a162017-02-06 15:35:29 -08001354 // Allow vectorization for all ARM devices, because Android assumes that
Aart Bikb29f6842017-07-28 15:58:41 -07001355 // ARMv8 AArch64 always supports advanced SIMD (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001356 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001357 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001358 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001359 case DataType::Type::kInt8:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001360 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001361 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001362 case DataType::Type::kUint16:
1363 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001364 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001365 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001366 case DataType::Type::kInt32:
Aart Bikf8f5a162017-02-06 15:35:29 -08001367 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001368 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001369 case DataType::Type::kInt64:
Vladimir Markof51e6142018-10-29 18:31:14 +00001370 *restrictions |= kNoDiv | kNoMul;
Aart Bikf8f5a162017-02-06 15:35:29 -08001371 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001372 case DataType::Type::kFloat32:
Aart Bik0148de42017-09-05 09:25:01 -07001373 *restrictions |= kNoReduction;
Artem Serovd4bccf12017-04-03 18:47:32 +01001374 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001375 case DataType::Type::kFloat64:
Aart Bik0148de42017-09-05 09:25:01 -07001376 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001377 return TrySetVectorLength(2);
1378 default:
1379 return false;
1380 }
Vladimir Marko33bff252017-11-01 14:35:42 +00001381 case InstructionSet::kX86:
1382 case InstructionSet::kX86_64:
Aart Bikb29f6842017-07-28 15:58:41 -07001383 // Allow vectorization for SSE4.1-enabled X86 devices only (128-bit SIMD).
Aart Bikf8f5a162017-02-06 15:35:29 -08001384 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1385 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001386 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001387 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001388 case DataType::Type::kInt8:
Aart Bik0148de42017-09-05 09:25:01 -07001389 *restrictions |=
Aart Bikdbbac8f2017-09-01 13:06:08 -07001390 kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001391 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001392 case DataType::Type::kUint16:
1393 case DataType::Type::kInt16:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001394 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001395 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001396 case DataType::Type::kInt32:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001397 *restrictions |= kNoDiv | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001398 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001399 case DataType::Type::kInt64:
Vladimir Markof51e6142018-10-29 18:31:14 +00001400 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoSAD;
Aart Bikf8f5a162017-02-06 15:35:29 -08001401 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001402 case DataType::Type::kFloat32:
Vladimir Markof51e6142018-10-29 18:31:14 +00001403 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001404 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001405 case DataType::Type::kFloat64:
Vladimir Markof51e6142018-10-29 18:31:14 +00001406 *restrictions |= kNoReduction;
Aart Bikf8f5a162017-02-06 15:35:29 -08001407 return TrySetVectorLength(2);
1408 default:
1409 break;
1410 } // switch type
1411 }
1412 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001413 case InstructionSet::kMips:
Lena Djokic51765b02017-06-22 13:49:59 +02001414 if (features->AsMipsInstructionSetFeatures()->HasMsa()) {
1415 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001416 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001417 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001418 case DataType::Type::kInt8:
Lena Djokic38e380b2017-10-30 16:17:10 +01001419 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001420 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001421 case DataType::Type::kUint16:
1422 case DataType::Type::kInt16:
Lena Djokic38e380b2017-10-30 16:17:10 +01001423 *restrictions |= kNoDiv | kNoStringCharAt;
Lena Djokic51765b02017-06-22 13:49:59 +02001424 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001425 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001426 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001427 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001428 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001429 *restrictions |= kNoDiv;
Lena Djokic51765b02017-06-22 13:49:59 +02001430 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001431 case DataType::Type::kFloat32:
Vladimir Markof51e6142018-10-29 18:31:14 +00001432 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001433 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001434 case DataType::Type::kFloat64:
Vladimir Markof51e6142018-10-29 18:31:14 +00001435 *restrictions |= kNoReduction;
Lena Djokic51765b02017-06-22 13:49:59 +02001436 return TrySetVectorLength(2);
1437 default:
1438 break;
1439 } // switch type
1440 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001441 return false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001442 case InstructionSet::kMips64:
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001443 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1444 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001445 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001446 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001447 case DataType::Type::kInt8:
Lena Djokic38e380b2017-10-30 16:17:10 +01001448 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001449 return TrySetVectorLength(16);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001450 case DataType::Type::kUint16:
1451 case DataType::Type::kInt16:
Lena Djokic38e380b2017-10-30 16:17:10 +01001452 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001453 return TrySetVectorLength(8);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001454 case DataType::Type::kInt32:
Lena Djokic38e380b2017-10-30 16:17:10 +01001455 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001456 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001457 case DataType::Type::kInt64:
Lena Djokic38e380b2017-10-30 16:17:10 +01001458 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001459 return TrySetVectorLength(2);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001460 case DataType::Type::kFloat32:
Vladimir Markof51e6142018-10-29 18:31:14 +00001461 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001462 return TrySetVectorLength(4);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001463 case DataType::Type::kFloat64:
Vladimir Markof51e6142018-10-29 18:31:14 +00001464 *restrictions |= kNoReduction;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001465 return TrySetVectorLength(2);
1466 default:
1467 break;
1468 } // switch type
1469 }
1470 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001471 default:
1472 return false;
1473 } // switch instruction set
1474}
1475
1476bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1477 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1478 // First time set?
1479 if (vector_length_ == 0) {
1480 vector_length_ = length;
1481 }
1482 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1483 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1484 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1485 return vector_length_ == length;
1486}
1487
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001488void HLoopOptimization::GenerateVecInv(HInstruction* org, DataType::Type type) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001489 if (vector_map_->find(org) == vector_map_->end()) {
1490 // In scalar code, just use a self pass-through for scalar invariants
1491 // (viz. expression remains itself).
1492 if (vector_mode_ == kSequential) {
1493 vector_map_->Put(org, org);
1494 return;
1495 }
1496 // In vector code, explicit scalar expansion is needed.
Aart Bik0148de42017-09-05 09:25:01 -07001497 HInstruction* vector = nullptr;
1498 auto it = vector_permanent_map_->find(org);
1499 if (it != vector_permanent_map_->end()) {
1500 vector = it->second; // reuse during unrolling
1501 } else {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001502 // Generates ReplicateScalar( (optional_type_conv) org ).
1503 HInstruction* input = org;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001504 DataType::Type input_type = input->GetType();
1505 if (type != input_type && (type == DataType::Type::kInt64 ||
1506 input_type == DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001507 input = Insert(vector_preheader_,
1508 new (global_allocator_) HTypeConversion(type, input, kNoDexPc));
1509 }
1510 vector = new (global_allocator_)
Aart Bik46b6dbc2017-10-03 11:37:37 -07001511 HVecReplicateScalar(global_allocator_, input, type, vector_length_, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001512 vector_permanent_map_->Put(org, Insert(vector_preheader_, vector));
1513 }
1514 vector_map_->Put(org, vector);
Aart Bikf8f5a162017-02-06 15:35:29 -08001515 }
1516}
1517
1518void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1519 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001520 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001521 int64_t value = 0;
1522 if (!IsInt64AndGet(offset, &value) || value != 0) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001523 subscript = new (global_allocator_) HAdd(DataType::Type::kInt32, subscript, offset);
Aart Bikf8f5a162017-02-06 15:35:29 -08001524 if (org->IsPhi()) {
1525 Insert(vector_body_, subscript); // lacks layout placeholder
1526 }
1527 }
1528 vector_map_->Put(org, subscript);
1529 }
1530}
1531
1532void HLoopOptimization::GenerateVecMem(HInstruction* org,
1533 HInstruction* opa,
1534 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001535 HInstruction* offset,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001536 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001537 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001538 HInstruction* vector = nullptr;
1539 if (vector_mode_ == kVector) {
1540 // Vector store or load.
Aart Bik38a3f212017-10-20 17:02:21 -07001541 bool is_string_char_at = false;
Aart Bik14a68b42017-06-08 14:06:58 -07001542 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001543 if (opb != nullptr) {
1544 vector = new (global_allocator_) HVecStore(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001545 global_allocator_, base, opa, opb, type, org->GetSideEffects(), vector_length_, dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001546 } else {
Aart Bik38a3f212017-10-20 17:02:21 -07001547 is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001548 vector = new (global_allocator_) HVecLoad(global_allocator_,
1549 base,
1550 opa,
1551 type,
1552 org->GetSideEffects(),
1553 vector_length_,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001554 is_string_char_at,
1555 dex_pc);
Aart Bik14a68b42017-06-08 14:06:58 -07001556 }
Aart Bik38a3f212017-10-20 17:02:21 -07001557 // Known (forced/adjusted/original) alignment?
1558 if (vector_dynamic_peeling_candidate_ != nullptr) {
1559 if (vector_dynamic_peeling_candidate_->offset == offset && // TODO: diffs too?
1560 DataType::Size(vector_dynamic_peeling_candidate_->type) == DataType::Size(type) &&
1561 vector_dynamic_peeling_candidate_->is_string_char_at == is_string_char_at) {
1562 vector->AsVecMemoryOperation()->SetAlignment( // forced
1563 Alignment(GetVectorSizeInBytes(), 0));
1564 }
1565 } else {
1566 vector->AsVecMemoryOperation()->SetAlignment( // adjusted/original
1567 ComputeAlignment(offset, type, is_string_char_at, vector_static_peeling_factor_));
Aart Bikf8f5a162017-02-06 15:35:29 -08001568 }
1569 } else {
1570 // Scalar store or load.
1571 DCHECK(vector_mode_ == kSequential);
1572 if (opb != nullptr) {
Aart Bik4d1a9d42017-10-19 14:40:55 -07001573 DataType::Type component_type = org->AsArraySet()->GetComponentType();
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001574 vector = new (global_allocator_) HArraySet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001575 org->InputAt(0), opa, opb, component_type, org->GetSideEffects(), dex_pc);
Aart Bikf8f5a162017-02-06 15:35:29 -08001576 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001577 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1578 vector = new (global_allocator_) HArrayGet(
Aart Bik4d1a9d42017-10-19 14:40:55 -07001579 org->InputAt(0), opa, org->GetType(), org->GetSideEffects(), dex_pc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001580 }
1581 }
1582 vector_map_->Put(org, vector);
1583}
1584
Aart Bik0148de42017-09-05 09:25:01 -07001585void HLoopOptimization::GenerateVecReductionPhi(HPhi* phi) {
1586 DCHECK(reductions_->find(phi) != reductions_->end());
1587 DCHECK(reductions_->Get(phi->InputAt(1)) == phi);
1588 HInstruction* vector = nullptr;
1589 if (vector_mode_ == kSequential) {
1590 HPhi* new_phi = new (global_allocator_) HPhi(
1591 global_allocator_, kNoRegNumber, 0, phi->GetType());
1592 vector_header_->AddPhi(new_phi);
1593 vector = new_phi;
1594 } else {
1595 // Link vector reduction back to prior unrolled update, or a first phi.
1596 auto it = vector_permanent_map_->find(phi);
1597 if (it != vector_permanent_map_->end()) {
1598 vector = it->second;
1599 } else {
1600 HPhi* new_phi = new (global_allocator_) HPhi(
1601 global_allocator_, kNoRegNumber, 0, HVecOperation::kSIMDType);
1602 vector_header_->AddPhi(new_phi);
1603 vector = new_phi;
1604 }
1605 }
1606 vector_map_->Put(phi, vector);
1607}
1608
1609void HLoopOptimization::GenerateVecReductionPhiInputs(HPhi* phi, HInstruction* reduction) {
1610 HInstruction* new_phi = vector_map_->Get(phi);
1611 HInstruction* new_init = reductions_->Get(phi);
1612 HInstruction* new_red = vector_map_->Get(reduction);
1613 // Link unrolled vector loop back to new phi.
1614 for (; !new_phi->IsPhi(); new_phi = vector_permanent_map_->Get(new_phi)) {
1615 DCHECK(new_phi->IsVecOperation());
1616 }
1617 // Prepare the new initialization.
1618 if (vector_mode_ == kVector) {
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001619 // Generate a [initial, 0, .., 0] vector for add or
1620 // a [initial, initial, .., initial] vector for min/max.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001621 HVecOperation* red_vector = new_red->AsVecOperation();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001622 HVecReduce::ReductionKind kind = GetReductionKind(red_vector);
Aart Bik38a3f212017-10-20 17:02:21 -07001623 uint32_t vector_length = red_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001624 DataType::Type type = red_vector->GetPackedType();
Goran Jakovljevic89b8df02017-10-13 08:33:17 +02001625 if (kind == HVecReduce::ReductionKind::kSum) {
1626 new_init = Insert(vector_preheader_,
1627 new (global_allocator_) HVecSetScalars(global_allocator_,
1628 &new_init,
1629 type,
1630 vector_length,
1631 1,
1632 kNoDexPc));
1633 } else {
1634 new_init = Insert(vector_preheader_,
1635 new (global_allocator_) HVecReplicateScalar(global_allocator_,
1636 new_init,
1637 type,
1638 vector_length,
1639 kNoDexPc));
1640 }
Aart Bik0148de42017-09-05 09:25:01 -07001641 } else {
1642 new_init = ReduceAndExtractIfNeeded(new_init);
1643 }
1644 // Set the phi inputs.
1645 DCHECK(new_phi->IsPhi());
1646 new_phi->AsPhi()->AddInput(new_init);
1647 new_phi->AsPhi()->AddInput(new_red);
1648 // New feed value for next phi (safe mutation in iteration).
1649 reductions_->find(phi)->second = new_phi;
1650}
1651
1652HInstruction* HLoopOptimization::ReduceAndExtractIfNeeded(HInstruction* instruction) {
1653 if (instruction->IsPhi()) {
1654 HInstruction* input = instruction->InputAt(1);
Aart Bik2dd7b672017-12-07 11:11:22 -08001655 if (HVecOperation::ReturnsSIMDValue(input)) {
1656 DCHECK(!input->IsPhi());
Aart Bikdbbac8f2017-09-01 13:06:08 -07001657 HVecOperation* input_vector = input->AsVecOperation();
Aart Bik38a3f212017-10-20 17:02:21 -07001658 uint32_t vector_length = input_vector->GetVectorLength();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001659 DataType::Type type = input_vector->GetPackedType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001660 HVecReduce::ReductionKind kind = GetReductionKind(input_vector);
Aart Bik0148de42017-09-05 09:25:01 -07001661 HBasicBlock* exit = instruction->GetBlock()->GetSuccessors()[0];
1662 // Generate a vector reduction and scalar extract
1663 // x = REDUCE( [x_1, .., x_n] )
1664 // y = x_1
1665 // along the exit of the defining loop.
Aart Bik0148de42017-09-05 09:25:01 -07001666 HInstruction* reduce = new (global_allocator_) HVecReduce(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001667 global_allocator_, instruction, type, vector_length, kind, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001668 exit->InsertInstructionBefore(reduce, exit->GetFirstInstruction());
1669 instruction = new (global_allocator_) HVecExtractScalar(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001670 global_allocator_, reduce, type, vector_length, 0, kNoDexPc);
Aart Bik0148de42017-09-05 09:25:01 -07001671 exit->InsertInstructionAfter(instruction, reduce);
1672 }
1673 }
1674 return instruction;
1675}
1676
Aart Bikf8f5a162017-02-06 15:35:29 -08001677#define GENERATE_VEC(x, y) \
1678 if (vector_mode_ == kVector) { \
1679 vector = (x); \
1680 } else { \
1681 DCHECK(vector_mode_ == kSequential); \
1682 vector = (y); \
1683 } \
1684 break;
1685
1686void HLoopOptimization::GenerateVecOp(HInstruction* org,
1687 HInstruction* opa,
1688 HInstruction* opb,
Vladimir Markof51e6142018-10-29 18:31:14 +00001689 DataType::Type type) {
Aart Bik46b6dbc2017-10-03 11:37:37 -07001690 uint32_t dex_pc = org->GetDexPc();
Aart Bikf8f5a162017-02-06 15:35:29 -08001691 HInstruction* vector = nullptr;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001692 DataType::Type org_type = org->GetType();
Aart Bikf8f5a162017-02-06 15:35:29 -08001693 switch (org->GetKind()) {
1694 case HInstruction::kNeg:
1695 DCHECK(opb == nullptr);
1696 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001697 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_, dex_pc),
1698 new (global_allocator_) HNeg(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001699 case HInstruction::kNot:
1700 DCHECK(opb == nullptr);
1701 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001702 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1703 new (global_allocator_) HNot(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001704 case HInstruction::kBooleanNot:
1705 DCHECK(opb == nullptr);
1706 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001707 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_, dex_pc),
1708 new (global_allocator_) HBooleanNot(opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001709 case HInstruction::kTypeConversion:
1710 DCHECK(opb == nullptr);
1711 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001712 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_, dex_pc),
1713 new (global_allocator_) HTypeConversion(org_type, opa, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001714 case HInstruction::kAdd:
1715 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001716 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1717 new (global_allocator_) HAdd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001718 case HInstruction::kSub:
1719 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001720 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1721 new (global_allocator_) HSub(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001722 case HInstruction::kMul:
1723 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001724 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1725 new (global_allocator_) HMul(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001726 case HInstruction::kDiv:
1727 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001728 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1729 new (global_allocator_) HDiv(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001730 case HInstruction::kAnd:
1731 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001732 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1733 new (global_allocator_) HAnd(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001734 case HInstruction::kOr:
1735 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001736 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1737 new (global_allocator_) HOr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001738 case HInstruction::kXor:
1739 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001740 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1741 new (global_allocator_) HXor(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001742 case HInstruction::kShl:
1743 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001744 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1745 new (global_allocator_) HShl(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001746 case HInstruction::kShr:
1747 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001748 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1749 new (global_allocator_) HShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001750 case HInstruction::kUShr:
1751 GENERATE_VEC(
Aart Bik46b6dbc2017-10-03 11:37:37 -07001752 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_, dex_pc),
1753 new (global_allocator_) HUShr(org_type, opa, opb, dex_pc));
Aart Bikf8f5a162017-02-06 15:35:29 -08001754 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001755 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1756 if (vector_mode_ == kVector) {
1757 switch (invoke->GetIntrinsic()) {
1758 case Intrinsics::kMathAbsInt:
1759 case Intrinsics::kMathAbsLong:
1760 case Intrinsics::kMathAbsFloat:
1761 case Intrinsics::kMathAbsDouble:
1762 DCHECK(opb == nullptr);
Aart Bik46b6dbc2017-10-03 11:37:37 -07001763 vector = new (global_allocator_)
1764 HVecAbs(global_allocator_, opa, type, vector_length_, dex_pc);
Aart Bik6daebeb2017-04-03 14:35:41 -07001765 break;
1766 default:
Aart Bik38a3f212017-10-20 17:02:21 -07001767 LOG(FATAL) << "Unsupported SIMD intrinsic " << org->GetId();
Aart Bik6daebeb2017-04-03 14:35:41 -07001768 UNREACHABLE();
1769 } // switch invoke
1770 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001771 // In scalar code, simply clone the method invoke, and replace its operands with the
1772 // corresponding new scalar instructions in the loop. The instruction will get an
1773 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001774 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001775 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001776 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1777 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001778 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001779 invoke->GetType(),
1780 invoke->GetDexPc(),
1781 invoke->GetDexMethodIndex(),
1782 invoke->GetResolvedMethod(),
1783 invoke->GetDispatchInfo(),
1784 invoke->GetInvokeType(),
1785 invoke->GetTargetMethod(),
1786 invoke->GetClinitCheckRequirement());
1787 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001788 size_t num_inputs = inputs.size();
1789 DCHECK_LE(num_args, num_inputs);
1790 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1791 for (size_t index = 0; index < num_inputs; ++index) {
1792 HInstruction* new_input = index < num_args
1793 ? vector_map_->Get(inputs[index])
1794 : inputs[index]; // beyond arguments: just pass through
1795 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001796 }
Aart Bik98990262017-04-10 13:15:57 -07001797 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1798 kNeedsEnvironmentOrCache,
1799 kNoSideEffects,
1800 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001801 vector = new_invoke;
1802 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001803 break;
1804 }
1805 default:
1806 break;
1807 } // switch
1808 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1809 vector_map_->Put(org, vector);
1810}
1811
1812#undef GENERATE_VEC
1813
1814//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001815// Vectorization idioms.
1816//
1817
1818// Method recognizes the following idioms:
Aart Bikdbbac8f2017-09-01 13:06:08 -07001819// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1820// truncated halving add (a + b) >> 1 for unsigned/signed operands a, b
Aart Bikf3e61ee2017-04-12 17:09:20 -07001821// Provided that the operands are promoted to a wider form to do the arithmetic and
1822// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1823// implementation that operates directly in narrower form (plus one extra bit).
1824// TODO: current version recognizes implicit byte/short/char widening only;
1825// explicit widening from int to long could be added later.
1826bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1827 HInstruction* instruction,
1828 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001829 DataType::Type type,
Aart Bikf3e61ee2017-04-12 17:09:20 -07001830 uint64_t restrictions) {
1831 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001832 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001833 // on the narrow precision computed by the idiom).
Aart Bikf3e61ee2017-04-12 17:09:20 -07001834 if ((instruction->IsShr() ||
1835 instruction->IsUShr()) &&
Aart Bik0148de42017-09-05 09:25:01 -07001836 IsInt64Value(instruction->InputAt(1), 1)) {
Aart Bik5f805002017-05-16 16:42:41 -07001837 // Test for (a + b + c) >> 1 for optional constant c.
1838 HInstruction* a = nullptr;
1839 HInstruction* b = nullptr;
1840 int64_t c = 0;
1841 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001842 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001843 // Accept c == 1 (rounded) or c == 0 (not rounded).
1844 bool is_rounded = false;
1845 if (c == 1) {
1846 is_rounded = true;
1847 } else if (c != 0) {
1848 return false;
1849 }
1850 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001851 HInstruction* r = nullptr;
1852 HInstruction* s = nullptr;
1853 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001854 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001855 return false;
1856 }
1857 // Deal with vector restrictions.
1858 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1859 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1860 return false;
1861 }
1862 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1863 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001864 DCHECK(r != nullptr);
1865 DCHECK(s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001866 if (generate_code && vector_mode_ != kVector) { // de-idiom
1867 r = instruction->InputAt(0);
1868 s = instruction->InputAt(1);
1869 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001870 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1871 VectorizeUse(node, s, generate_code, type, restrictions)) {
1872 if (generate_code) {
1873 if (vector_mode_ == kVector) {
1874 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1875 global_allocator_,
1876 vector_map_->Get(r),
1877 vector_map_->Get(s),
Aart Bik66c158e2018-01-31 12:55:04 -08001878 HVecOperation::ToProperType(type, is_unsigned),
Aart Bikf3e61ee2017-04-12 17:09:20 -07001879 vector_length_,
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001880 is_rounded,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001881 kNoDexPc));
Aart Bik21b85922017-09-06 13:29:16 -07001882 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001883 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001884 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001885 }
1886 }
1887 return true;
1888 }
1889 }
1890 }
1891 return false;
1892}
1893
Aart Bikdbbac8f2017-09-01 13:06:08 -07001894// Method recognizes the following idiom:
1895// q += ABS(a - b) for signed operands a, b
1896// Provided that the operands have the same type or are promoted to a wider form.
1897// Since this may involve a vector length change, the idiom is handled by going directly
1898// to a sad-accumulate node (rather than relying combining finer grained nodes later).
1899// TODO: unsigned SAD too?
1900bool HLoopOptimization::VectorizeSADIdiom(LoopNode* node,
1901 HInstruction* instruction,
1902 bool generate_code,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001903 DataType::Type reduction_type,
Aart Bikdbbac8f2017-09-01 13:06:08 -07001904 uint64_t restrictions) {
1905 // Filter integral "q += ABS(a - b);" reduction, where ABS and SUB
1906 // are done in the same precision (either int or long).
1907 if (!instruction->IsAdd() ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001908 (reduction_type != DataType::Type::kInt32 && reduction_type != DataType::Type::kInt64)) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001909 return false;
1910 }
1911 HInstruction* q = instruction->InputAt(0);
1912 HInstruction* v = instruction->InputAt(1);
1913 HInstruction* a = nullptr;
1914 HInstruction* b = nullptr;
1915 if (v->IsInvokeStaticOrDirect() &&
1916 (v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsInt ||
1917 v->AsInvokeStaticOrDirect()->GetIntrinsic() == Intrinsics::kMathAbsLong)) {
1918 HInstruction* x = v->InputAt(0);
Aart Bikdf011c32017-09-28 12:53:04 -07001919 if (x->GetType() == reduction_type) {
1920 int64_t c = 0;
1921 if (x->IsSub()) {
1922 a = x->InputAt(0);
1923 b = x->InputAt(1);
1924 } else if (IsAddConst(x, /*out*/ &a, /*out*/ &c)) {
1925 b = graph_->GetConstant(reduction_type, -c); // hidden SUB!
1926 }
Aart Bikdbbac8f2017-09-01 13:06:08 -07001927 }
1928 }
1929 if (a == nullptr || b == nullptr) {
1930 return false;
1931 }
1932 // Accept same-type or consistent sign extension for narrower-type on operands a and b.
1933 // The same-type or narrower operands are called r (a or lower) and s (b or lower).
Aart Bikdf011c32017-09-28 12:53:04 -07001934 // We inspect the operands carefully to pick the most suited type.
Aart Bikdbbac8f2017-09-01 13:06:08 -07001935 HInstruction* r = a;
1936 HInstruction* s = b;
1937 bool is_unsigned = false;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001938 DataType::Type sub_type = a->GetType();
Aart Bikdf011c32017-09-28 12:53:04 -07001939 if (DataType::Size(b->GetType()) < DataType::Size(sub_type)) {
1940 sub_type = b->GetType();
1941 }
1942 if (a->IsTypeConversion() &&
1943 DataType::Size(a->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
1944 sub_type = a->InputAt(0)->GetType();
1945 }
1946 if (b->IsTypeConversion() &&
1947 DataType::Size(b->InputAt(0)->GetType()) < DataType::Size(sub_type)) {
1948 sub_type = b->InputAt(0)->GetType();
Aart Bikdbbac8f2017-09-01 13:06:08 -07001949 }
1950 if (reduction_type != sub_type &&
1951 (!IsNarrowerOperands(a, b, sub_type, &r, &s, &is_unsigned) || is_unsigned)) {
1952 return false;
1953 }
1954 // Try same/narrower type and deal with vector restrictions.
Artem Serov6e9b1372017-10-05 16:48:30 +01001955 if (!TrySetVectorType(sub_type, &restrictions) ||
1956 HasVectorRestrictions(restrictions, kNoSAD) ||
1957 (reduction_type != sub_type && HasVectorRestrictions(restrictions, kNoWideSAD))) {
Aart Bikdbbac8f2017-09-01 13:06:08 -07001958 return false;
1959 }
1960 // Accept SAD idiom for vectorizable operands. Vectorized code uses the shorthand
1961 // idiomatic operation. Sequential code uses the original scalar expressions.
1962 DCHECK(r != nullptr);
1963 DCHECK(s != nullptr);
1964 if (generate_code && vector_mode_ != kVector) { // de-idiom
1965 r = s = v->InputAt(0);
1966 }
1967 if (VectorizeUse(node, q, generate_code, sub_type, restrictions) &&
1968 VectorizeUse(node, r, generate_code, sub_type, restrictions) &&
1969 VectorizeUse(node, s, generate_code, sub_type, restrictions)) {
1970 if (generate_code) {
Aart Bik66c158e2018-01-31 12:55:04 -08001971 reduction_type = HVecOperation::ToProperType(reduction_type, is_unsigned);
Aart Bikdbbac8f2017-09-01 13:06:08 -07001972 if (vector_mode_ == kVector) {
1973 vector_map_->Put(instruction, new (global_allocator_) HVecSADAccumulate(
1974 global_allocator_,
1975 vector_map_->Get(q),
1976 vector_map_->Get(r),
1977 vector_map_->Get(s),
1978 reduction_type,
Aart Bik46b6dbc2017-10-03 11:37:37 -07001979 GetOtherVL(reduction_type, sub_type, vector_length_),
1980 kNoDexPc));
Aart Bikdbbac8f2017-09-01 13:06:08 -07001981 MaybeRecordStat(stats_, MethodCompilationStat::kLoopVectorizedIdiom);
1982 } else {
1983 GenerateVecOp(v, vector_map_->Get(r), nullptr, reduction_type);
1984 GenerateVecOp(instruction, vector_map_->Get(q), vector_map_->Get(v), reduction_type);
1985 }
1986 }
1987 return true;
1988 }
1989 return false;
1990}
1991
Aart Bikf3e61ee2017-04-12 17:09:20 -07001992//
Aart Bik14a68b42017-06-08 14:06:58 -07001993// Vectorization heuristics.
1994//
1995
Aart Bik38a3f212017-10-20 17:02:21 -07001996Alignment HLoopOptimization::ComputeAlignment(HInstruction* offset,
1997 DataType::Type type,
1998 bool is_string_char_at,
1999 uint32_t peeling) {
2000 // Combine the alignment and hidden offset that is guaranteed by
2001 // the Android runtime with a known starting index adjusted as bytes.
2002 int64_t value = 0;
2003 if (IsInt64AndGet(offset, /*out*/ &value)) {
2004 uint32_t start_offset =
2005 HiddenOffset(type, is_string_char_at) + (value + peeling) * DataType::Size(type);
2006 return Alignment(BaseAlignment(), start_offset & (BaseAlignment() - 1u));
2007 }
2008 // Otherwise, the Android runtime guarantees at least natural alignment.
2009 return Alignment(DataType::Size(type), 0);
2010}
2011
2012void HLoopOptimization::SetAlignmentStrategy(uint32_t peeling_votes[],
2013 const ArrayReference* peeling_candidate) {
2014 // Current heuristic: pick the best static loop peeling factor, if any,
2015 // or otherwise use dynamic loop peeling on suggested peeling candidate.
2016 uint32_t max_vote = 0;
2017 for (int32_t i = 0; i < 16; i++) {
2018 if (peeling_votes[i] > max_vote) {
2019 max_vote = peeling_votes[i];
2020 vector_static_peeling_factor_ = i;
2021 }
2022 }
2023 if (max_vote == 0) {
2024 vector_dynamic_peeling_candidate_ = peeling_candidate;
2025 }
2026}
2027
2028uint32_t HLoopOptimization::MaxNumberPeeled() {
2029 if (vector_dynamic_peeling_candidate_ != nullptr) {
2030 return vector_length_ - 1u; // worst-case
2031 }
2032 return vector_static_peeling_factor_; // known exactly
2033}
2034
Aart Bik14a68b42017-06-08 14:06:58 -07002035bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002036 // Current heuristic: non-empty body with sufficient number of iterations (if known).
Aart Bik14a68b42017-06-08 14:06:58 -07002037 // TODO: refine by looking at e.g. operation count, alignment, etc.
Aart Bik38a3f212017-10-20 17:02:21 -07002038 // TODO: trip count is really unsigned entity, provided the guarding test
2039 // is satisfied; deal with this more carefully later
2040 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002041 if (vector_length_ == 0) {
2042 return false; // nothing found
Aart Bik38a3f212017-10-20 17:02:21 -07002043 } else if (trip_count < 0) {
2044 return false; // guard against non-taken/large
2045 } else if ((0 < trip_count) && (trip_count < (vector_length_ + max_peel))) {
Aart Bik14a68b42017-06-08 14:06:58 -07002046 return false; // insufficient iterations
2047 }
2048 return true;
2049}
2050
Artem Serovf26bb6c2017-09-01 10:59:03 +01002051static constexpr uint32_t ARM64_SIMD_MAXIMUM_UNROLL_FACTOR = 8;
2052static constexpr uint32_t ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE = 50;
2053
Aart Bik14a68b42017-06-08 14:06:58 -07002054uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
Aart Bik38a3f212017-10-20 17:02:21 -07002055 uint32_t max_peel = MaxNumberPeeled();
Aart Bik14a68b42017-06-08 14:06:58 -07002056 switch (compiler_driver_->GetInstructionSet()) {
Vladimir Marko33bff252017-11-01 14:35:42 +00002057 case InstructionSet::kArm64: {
Aart Bik521b50f2017-09-09 10:44:45 -07002058 // Don't unroll with insufficient iterations.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002059 // TODO: Unroll loops with unknown trip count.
Aart Bik521b50f2017-09-09 10:44:45 -07002060 DCHECK_NE(vector_length_, 0u);
Aart Bik38a3f212017-10-20 17:02:21 -07002061 if (trip_count < (2 * vector_length_ + max_peel)) {
Aart Bik521b50f2017-09-09 10:44:45 -07002062 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002063 }
Aart Bik521b50f2017-09-09 10:44:45 -07002064 // Don't unroll for large loop body size.
Artem Serovf26bb6c2017-09-01 10:59:03 +01002065 uint32_t instruction_count = block->GetInstructions().CountSize();
Aart Bik521b50f2017-09-09 10:44:45 -07002066 if (instruction_count >= ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE) {
2067 return kNoUnrollingFactor;
2068 }
Artem Serovf26bb6c2017-09-01 10:59:03 +01002069 // Find a beneficial unroll factor with the following restrictions:
2070 // - At least one iteration of the transformed loop should be executed.
2071 // - The loop body shouldn't be "too big" (heuristic).
2072 uint32_t uf1 = ARM64_SIMD_HEURISTIC_MAX_BODY_SIZE / instruction_count;
Aart Bik38a3f212017-10-20 17:02:21 -07002073 uint32_t uf2 = (trip_count - max_peel) / vector_length_;
Artem Serovf26bb6c2017-09-01 10:59:03 +01002074 uint32_t unroll_factor =
2075 TruncToPowerOfTwo(std::min({uf1, uf2, ARM64_SIMD_MAXIMUM_UNROLL_FACTOR}));
2076 DCHECK_GE(unroll_factor, 1u);
Artem Serovf26bb6c2017-09-01 10:59:03 +01002077 return unroll_factor;
Aart Bik14a68b42017-06-08 14:06:58 -07002078 }
Vladimir Marko33bff252017-11-01 14:35:42 +00002079 case InstructionSet::kX86:
2080 case InstructionSet::kX86_64:
Aart Bik14a68b42017-06-08 14:06:58 -07002081 default:
Aart Bik521b50f2017-09-09 10:44:45 -07002082 return kNoUnrollingFactor;
Aart Bik14a68b42017-06-08 14:06:58 -07002083 }
2084}
2085
2086//
Aart Bikf8f5a162017-02-06 15:35:29 -08002087// Helpers.
2088//
2089
2090bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002091 // Start with empty phi induction.
2092 iset_->clear();
2093
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01002094 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
2095 // smart enough to follow strongly connected components (and it's probably not worth
2096 // it to make it so). See b/33775412.
2097 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
2098 return false;
2099 }
Aart Bikb29f6842017-07-28 15:58:41 -07002100
2101 // Lookup phi induction cycle.
Aart Bikcc42be02016-10-20 16:14:16 -07002102 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
2103 if (set != nullptr) {
2104 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07002105 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08002106 // each instruction is removable and, when restrict uses are requested, other than for phi,
2107 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07002108 if (!i->IsInBlock()) {
2109 continue;
2110 } else if (!i->IsRemovable()) {
2111 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08002112 } else if (i != phi && restrict_uses) {
Aart Bikb29f6842017-07-28 15:58:41 -07002113 // Deal with regular uses.
Aart Bikcc42be02016-10-20 16:14:16 -07002114 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
2115 if (set->find(use.GetUser()) == set->end()) {
2116 return false;
2117 }
2118 }
2119 }
Aart Bike3dedc52016-11-02 17:50:27 -07002120 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07002121 }
Aart Bikcc42be02016-10-20 16:14:16 -07002122 return true;
2123 }
2124 return false;
2125}
2126
Aart Bikb29f6842017-07-28 15:58:41 -07002127bool HLoopOptimization::TrySetPhiReduction(HPhi* phi) {
Aart Bikcc42be02016-10-20 16:14:16 -07002128 DCHECK(iset_->empty());
Aart Bikb29f6842017-07-28 15:58:41 -07002129 // Only unclassified phi cycles are candidates for reductions.
2130 if (induction_range_.IsClassified(phi)) {
2131 return false;
2132 }
2133 // Accept operations like x = x + .., provided that the phi and the reduction are
2134 // used exactly once inside the loop, and by each other.
2135 HInputsRef inputs = phi->GetInputs();
2136 if (inputs.size() == 2) {
2137 HInstruction* reduction = inputs[1];
2138 if (HasReductionFormat(reduction, phi)) {
2139 HLoopInformation* loop_info = phi->GetBlock()->GetLoopInformation();
Aart Bik38a3f212017-10-20 17:02:21 -07002140 uint32_t use_count = 0;
Aart Bikb29f6842017-07-28 15:58:41 -07002141 bool single_use_inside_loop =
2142 // Reduction update only used by phi.
2143 reduction->GetUses().HasExactlyOneElement() &&
2144 !reduction->HasEnvironmentUses() &&
2145 // Reduction update is only use of phi inside the loop.
2146 IsOnlyUsedAfterLoop(loop_info, phi, /*collect_loop_uses*/ true, &use_count) &&
2147 iset_->size() == 1;
2148 iset_->clear(); // leave the way you found it
2149 if (single_use_inside_loop) {
2150 // Link reduction back, and start recording feed value.
2151 reductions_->Put(reduction, phi);
2152 reductions_->Put(phi, phi->InputAt(0));
2153 return true;
2154 }
2155 }
2156 }
2157 return false;
2158}
2159
2160bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block, /*out*/ HPhi** main_phi) {
2161 // Start with empty phi induction and reductions.
2162 iset_->clear();
2163 reductions_->clear();
2164
2165 // Scan the phis to find the following (the induction structure has already
2166 // been optimized, so we don't need to worry about trivial cases):
2167 // (1) optional reductions in loop,
2168 // (2) the main induction, used in loop control.
2169 HPhi* phi = nullptr;
2170 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
2171 if (TrySetPhiReduction(it.Current()->AsPhi())) {
2172 continue;
2173 } else if (phi == nullptr) {
2174 // Found the first candidate for main induction.
2175 phi = it.Current()->AsPhi();
2176 } else {
2177 return false;
2178 }
2179 }
2180
2181 // Then test for a typical loopheader:
2182 // s: SuspendCheck
2183 // c: Condition(phi, bound)
2184 // i: If(c)
2185 if (phi != nullptr && TrySetPhiInduction(phi, /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07002186 HInstruction* s = block->GetFirstInstruction();
2187 if (s != nullptr && s->IsSuspendCheck()) {
2188 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07002189 if (c != nullptr &&
2190 c->IsCondition() &&
2191 c->GetUses().HasExactlyOneElement() && // only used for termination
2192 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07002193 HInstruction* i = c->GetNext();
2194 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
2195 iset_->insert(c);
2196 iset_->insert(s);
Aart Bikb29f6842017-07-28 15:58:41 -07002197 *main_phi = phi;
Aart Bikcc42be02016-10-20 16:14:16 -07002198 return true;
2199 }
2200 }
2201 }
2202 }
2203 return false;
2204}
2205
2206bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08002207 if (!block->GetPhis().IsEmpty()) {
2208 return false;
2209 }
2210 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
2211 HInstruction* instruction = it.Current();
2212 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
2213 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07002214 }
Aart Bikf8f5a162017-02-06 15:35:29 -08002215 }
2216 return true;
2217}
2218
2219bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
2220 HInstruction* instruction) {
Aart Bikb29f6842017-07-28 15:58:41 -07002221 // Deal with regular uses.
Aart Bikf8f5a162017-02-06 15:35:29 -08002222 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2223 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
2224 return true;
2225 }
Aart Bikcc42be02016-10-20 16:14:16 -07002226 }
2227 return false;
2228}
2229
Aart Bik482095d2016-10-10 15:39:10 -07002230bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07002231 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08002232 bool collect_loop_uses,
Aart Bik38a3f212017-10-20 17:02:21 -07002233 /*out*/ uint32_t* use_count) {
Aart Bikb29f6842017-07-28 15:58:41 -07002234 // Deal with regular uses.
Aart Bik8c4a8542016-10-06 11:36:57 -07002235 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
2236 HInstruction* user = use.GetUser();
2237 if (iset_->find(user) == iset_->end()) { // not excluded?
2238 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07002239 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002240 // If collect_loop_uses is set, simply keep adding those uses to the set.
2241 // Otherwise, reject uses inside the loop that were not already in the set.
2242 if (collect_loop_uses) {
2243 iset_->insert(user);
2244 continue;
2245 }
Aart Bik8c4a8542016-10-06 11:36:57 -07002246 return false;
2247 }
2248 ++*use_count;
2249 }
2250 }
2251 return true;
2252}
2253
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002254bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
2255 HInstruction* instruction,
2256 HBasicBlock* block) {
2257 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07002258 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08002259 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
Aart Bikb29f6842017-07-28 15:58:41 -07002260 // Deal with regular uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002261 const HUseList<HInstruction*>& uses = instruction->GetUses();
2262 for (auto it = uses.begin(), end = uses.end(); it != end;) {
2263 HInstruction* user = it->GetUser();
2264 size_t index = it->GetIndex();
2265 ++it; // increment before replacing
2266 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002267 if (kIsDebugBuild) {
2268 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
2269 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
2270 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
2271 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002272 user->ReplaceInput(replacement, index);
2273 induction_range_.Replace(user, instruction, replacement); // update induction
2274 }
2275 }
Aart Bikb29f6842017-07-28 15:58:41 -07002276 // Deal with environment uses.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002277 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
2278 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
2279 HEnvironment* user = it->GetUser();
2280 size_t index = it->GetIndex();
2281 ++it; // increment before replacing
2282 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002283 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07002284 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002285 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
2286 user->RemoveAsUserOfInput(index);
2287 user->SetRawEnvAt(index, replacement);
2288 replacement->AddEnvUseAt(user, index);
2289 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08002290 }
2291 }
Aart Bik807868e2016-11-03 17:51:43 -07002292 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07002293 }
Aart Bik807868e2016-11-03 17:51:43 -07002294 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07002295}
2296
Aart Bikf8f5a162017-02-06 15:35:29 -08002297bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
2298 HInstruction* instruction,
2299 HBasicBlock* block,
2300 bool collect_loop_uses) {
2301 // Assigning the last value is always successful if there are no uses.
2302 // Otherwise, it succeeds in a no early-exit loop by generating the
2303 // proper last value assignment.
Aart Bik38a3f212017-10-20 17:02:21 -07002304 uint32_t use_count = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -08002305 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
2306 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01002307 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08002308}
2309
Aart Bik6b69e0a2017-01-11 10:20:43 -08002310void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
2311 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
2312 HInstruction* instruction = i.Current();
2313 if (instruction->IsDeadAndRemovable()) {
2314 simplified_ = true;
2315 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
2316 }
2317 }
2318}
2319
Aart Bik14a68b42017-06-08 14:06:58 -07002320bool HLoopOptimization::CanRemoveCycle() {
2321 for (HInstruction* i : *iset_) {
2322 // We can never remove instructions that have environment
2323 // uses when we compile 'debuggable'.
2324 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
2325 return false;
2326 }
2327 // A deoptimization should never have an environment input removed.
2328 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
2329 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
2330 return false;
2331 }
2332 }
2333 }
2334 return true;
2335}
2336
Aart Bik281c6812016-08-26 11:31:48 -07002337} // namespace art