blob: 32f40024d3c591c2fbe85d4289fc719d45b5bf1e [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/instruction_set.h"
20#include "arch/arm/instruction_set_features_arm.h"
21#include "arch/arm64/instruction_set_features_arm64.h"
22#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 Bik281c6812016-08-26 11:31:48 -070028
29namespace art {
30
Aart Bikf8f5a162017-02-06 15:35:29 -080031// Enables vectorization (SIMDization) in the loop optimizer.
32static constexpr bool kEnableVectorization = true;
33
Aart Bik14a68b42017-06-08 14:06:58 -070034// All current SIMD targets want 16-byte alignment.
35static constexpr size_t kAlignedBase = 16;
36
Aart Bik9abf8942016-10-14 09:49:42 -070037// Remove the instruction from the graph. A bit more elaborate than the usual
38// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070039static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070040 instruction->RemoveAsUserOfAllInputs();
41 instruction->RemoveEnvironmentUsers();
42 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
43}
44
Aart Bik807868e2016-11-03 17:51:43 -070045// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070046static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
47 if (block->GetPredecessors().size() == 1 &&
48 block->GetSuccessors().size() == 1 &&
49 block->IsSingleGoto()) {
50 *succ = block->GetSingleSuccessor();
51 return true;
52 }
53 return false;
54}
55
Aart Bik807868e2016-11-03 17:51:43 -070056// Detect an early exit loop.
57static bool IsEarlyExit(HLoopInformation* loop_info) {
58 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
59 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
60 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
61 if (!loop_info->Contains(*successor)) {
62 return true;
63 }
64 }
65 }
66 return false;
67}
68
Aart Bikf3e61ee2017-04-12 17:09:20 -070069// Detect a sign extension from the given type. Returns the promoted operand on success.
70static bool IsSignExtensionAndGet(HInstruction* instruction,
71 Primitive::Type type,
72 /*out*/ HInstruction** operand) {
73 // Accept any already wider constant that would be handled properly by sign
74 // extension when represented in the *width* of the given narrower data type
75 // (the fact that char normally zero extends does not matter here).
76 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -070077 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070078 switch (type) {
79 case Primitive::kPrimByte:
80 if (std::numeric_limits<int8_t>::min() <= value &&
81 std::numeric_limits<int8_t>::max() >= value) {
82 *operand = instruction;
83 return true;
84 }
85 return false;
86 case Primitive::kPrimChar:
87 case Primitive::kPrimShort:
88 if (std::numeric_limits<int16_t>::min() <= value &&
89 std::numeric_limits<int16_t>::max() <= value) {
90 *operand = instruction;
91 return true;
92 }
93 return false;
94 default:
95 return false;
96 }
97 }
98 // An implicit widening conversion of a signed integer to an integral type sign-extends
99 // the two's-complement representation of the integer value to fill the wider format.
100 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
101 instruction->IsStaticFieldGet() ||
102 instruction->IsInstanceFieldGet())) {
103 switch (type) {
104 case Primitive::kPrimByte:
105 case Primitive::kPrimShort:
106 *operand = instruction;
107 return true;
108 default:
109 return false;
110 }
111 }
112 // TODO: perhaps explicit conversions later too?
113 // (this may return something different from instruction)
114 return false;
115}
116
117// Detect a zero extension from the given type. Returns the promoted operand on success.
118static bool IsZeroExtensionAndGet(HInstruction* instruction,
119 Primitive::Type type,
120 /*out*/ HInstruction** operand) {
121 // Accept any already wider constant that would be handled properly by zero
122 // extension when represented in the *width* of the given narrower data type
123 // (the fact that byte/short normally sign extend does not matter here).
124 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700125 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700126 switch (type) {
127 case Primitive::kPrimByte:
128 if (std::numeric_limits<uint8_t>::min() <= value &&
129 std::numeric_limits<uint8_t>::max() >= value) {
130 *operand = instruction;
131 return true;
132 }
133 return false;
134 case Primitive::kPrimChar:
135 case Primitive::kPrimShort:
136 if (std::numeric_limits<uint16_t>::min() <= value &&
137 std::numeric_limits<uint16_t>::max() <= value) {
138 *operand = instruction;
139 return true;
140 }
141 return false;
142 default:
143 return false;
144 }
145 }
146 // An implicit widening conversion of a char to an integral type zero-extends
147 // the representation of the char value to fill the wider format.
148 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
149 instruction->IsStaticFieldGet() ||
150 instruction->IsInstanceFieldGet())) {
151 if (type == Primitive::kPrimChar) {
152 *operand = instruction;
153 return true;
154 }
155 }
156 // A sign (or zero) extension followed by an explicit removal of just the
157 // higher sign bits is equivalent to a zero extension of the underlying operand.
158 if (instruction->IsAnd()) {
159 int64_t mask = 0;
160 HInstruction* a = instruction->InputAt(0);
161 HInstruction* b = instruction->InputAt(1);
162 // In (a & b) find (mask & b) or (a & mask) with sign or zero extension on the non-mask.
163 if ((IsInt64AndGet(a, /*out*/ &mask) && (IsSignExtensionAndGet(b, type, /*out*/ operand) ||
164 IsZeroExtensionAndGet(b, type, /*out*/ operand))) ||
165 (IsInt64AndGet(b, /*out*/ &mask) && (IsSignExtensionAndGet(a, type, /*out*/ operand) ||
166 IsZeroExtensionAndGet(a, type, /*out*/ operand)))) {
167 switch ((*operand)->GetType()) {
168 case Primitive::kPrimByte: return mask == std::numeric_limits<uint8_t>::max();
169 case Primitive::kPrimChar:
170 case Primitive::kPrimShort: return mask == std::numeric_limits<uint16_t>::max();
171 default: return false;
172 }
173 }
174 }
175 // TODO: perhaps explicit conversions later too?
176 return false;
177}
178
Aart Bik304c8a52017-05-23 11:01:13 -0700179// Detect situations with same-extension narrower operands.
180// Returns true on success and sets is_unsigned accordingly.
181static bool IsNarrowerOperands(HInstruction* a,
182 HInstruction* b,
183 Primitive::Type type,
184 /*out*/ HInstruction** r,
185 /*out*/ HInstruction** s,
186 /*out*/ bool* is_unsigned) {
187 if (IsSignExtensionAndGet(a, type, r) && IsSignExtensionAndGet(b, type, s)) {
188 *is_unsigned = false;
189 return true;
190 } else if (IsZeroExtensionAndGet(a, type, r) && IsZeroExtensionAndGet(b, type, s)) {
191 *is_unsigned = true;
192 return true;
193 }
194 return false;
195}
196
197// As above, single operand.
198static bool IsNarrowerOperand(HInstruction* a,
199 Primitive::Type type,
200 /*out*/ HInstruction** r,
201 /*out*/ bool* is_unsigned) {
202 if (IsSignExtensionAndGet(a, type, r)) {
203 *is_unsigned = false;
204 return true;
205 } else if (IsZeroExtensionAndGet(a, type, r)) {
206 *is_unsigned = true;
207 return true;
208 }
209 return false;
210}
211
Aart Bik5f805002017-05-16 16:42:41 -0700212// Detect up to two instructions a and b, and an acccumulated constant c.
213static bool IsAddConstHelper(HInstruction* instruction,
214 /*out*/ HInstruction** a,
215 /*out*/ HInstruction** b,
216 /*out*/ int64_t* c,
217 int32_t depth) {
218 static constexpr int32_t kMaxDepth = 8; // don't search too deep
219 int64_t value = 0;
220 if (IsInt64AndGet(instruction, &value)) {
221 *c += value;
222 return true;
223 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
224 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
225 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
226 } else if (*a == nullptr) {
227 *a = instruction;
228 return true;
229 } else if (*b == nullptr) {
230 *b = instruction;
231 return true;
232 }
233 return false; // too many non-const operands
234}
235
236// Detect a + b + c for an optional constant c.
237static bool IsAddConst(HInstruction* instruction,
238 /*out*/ HInstruction** a,
239 /*out*/ HInstruction** b,
240 /*out*/ int64_t* c) {
241 if (instruction->IsAdd()) {
242 // Try to find a + b and accumulated c.
243 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
244 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
245 *b != nullptr) {
246 return true;
247 }
248 // Found a + b.
249 *a = instruction->InputAt(0);
250 *b = instruction->InputAt(1);
251 *c = 0;
252 return true;
253 }
254 return false;
255}
256
Aart Bikf8f5a162017-02-06 15:35:29 -0800257// Test vector restrictions.
258static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
259 return (restrictions & tested) != 0;
260}
261
Aart Bikf3e61ee2017-04-12 17:09:20 -0700262// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800263static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
264 DCHECK(block != nullptr);
265 DCHECK(instruction != nullptr);
266 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
267 return instruction;
268}
269
Aart Bik281c6812016-08-26 11:31:48 -0700270//
271// Class methods.
272//
273
274HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800275 CompilerDriver* compiler_driver,
Aart Bik281c6812016-08-26 11:31:48 -0700276 HInductionVarAnalysis* induction_analysis)
277 : HOptimization(graph, kLoopOptimizationPassName),
Aart Bik92685a82017-03-06 11:13:43 -0800278 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700279 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700280 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800281 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -0700282 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700283 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700284 iset_(nullptr),
Aart Bikdf7822e2016-12-06 10:05:30 -0800285 induction_simplication_count_(0),
Aart Bikf8f5a162017-02-06 15:35:29 -0800286 simplified_(false),
287 vector_length_(0),
288 vector_refs_(nullptr),
Aart Bik14a68b42017-06-08 14:06:58 -0700289 vector_peeling_candidate_(nullptr),
290 vector_runtime_test_a_(nullptr),
291 vector_runtime_test_b_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800292 vector_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700293}
294
295void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800296 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700297 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800298 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700299 return;
300 }
301
Aart Bik96202302016-10-04 17:33:56 -0700302 // Phase-local allocator that draws from the global pool. Since the allocator
303 // itself resides on the stack, it is destructed on exiting Run(), which
304 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800305 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700306 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100307
Aart Bik96202302016-10-04 17:33:56 -0700308 // Perform loop optimizations.
309 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800310 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800311 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800312 }
313
Aart Bik96202302016-10-04 17:33:56 -0700314 // Detach.
315 loop_allocator_ = nullptr;
316 last_loop_ = top_loop_ = nullptr;
317}
318
319void HLoopOptimization::LocalRun() {
320 // Build the linear order using the phase-local allocator. This step enables building
321 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
322 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
323 LinearizeGraph(graph_, loop_allocator_, &linear_order);
324
Aart Bik281c6812016-08-26 11:31:48 -0700325 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700326 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700327 if (block->IsLoopHeader()) {
328 AddLoop(block->GetLoopInformation());
329 }
330 }
Aart Bik96202302016-10-04 17:33:56 -0700331
Aart Bik8c4a8542016-10-06 11:36:57 -0700332 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800333 // temporary data structures using the phase-local allocator. All new HIR
334 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700335 if (top_loop_ != nullptr) {
336 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800337 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
338 ArenaSafeMap<HInstruction*, HInstruction*> map(
339 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
340 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700341 iset_ = &iset;
Aart Bikf8f5a162017-02-06 15:35:29 -0800342 vector_refs_ = &refs;
343 vector_map_ = &map;
344 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700345 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800346 // Detach.
347 iset_ = nullptr;
348 vector_refs_ = nullptr;
349 vector_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700350 }
Aart Bik281c6812016-08-26 11:31:48 -0700351}
352
353void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
354 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800355 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700356 if (last_loop_ == nullptr) {
357 // First loop.
358 DCHECK(top_loop_ == nullptr);
359 last_loop_ = top_loop_ = node;
360 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
361 // Inner loop.
362 node->outer = last_loop_;
363 DCHECK(last_loop_->inner == nullptr);
364 last_loop_ = last_loop_->inner = node;
365 } else {
366 // Subsequent loop.
367 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
368 last_loop_ = last_loop_->outer;
369 }
370 node->outer = last_loop_->outer;
371 node->previous = last_loop_;
372 DCHECK(last_loop_->next == nullptr);
373 last_loop_ = last_loop_->next = node;
374 }
375}
376
377void HLoopOptimization::RemoveLoop(LoopNode* node) {
378 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700379 DCHECK(node->inner == nullptr);
380 if (node->previous != nullptr) {
381 // Within sequence.
382 node->previous->next = node->next;
383 if (node->next != nullptr) {
384 node->next->previous = node->previous;
385 }
386 } else {
387 // First of sequence.
388 if (node->outer != nullptr) {
389 node->outer->inner = node->next;
390 } else {
391 top_loop_ = node->next;
392 }
393 if (node->next != nullptr) {
394 node->next->outer = node->outer;
395 node->next->previous = nullptr;
396 }
397 }
Aart Bik281c6812016-08-26 11:31:48 -0700398}
399
400void HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
401 for ( ; node != nullptr; node = node->next) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800402 // Visit inner loops first.
Aart Bikf8f5a162017-02-06 15:35:29 -0800403 uint32_t current_induction_simplification_count = induction_simplication_count_;
Aart Bik281c6812016-08-26 11:31:48 -0700404 if (node->inner != nullptr) {
405 TraverseLoopsInnerToOuter(node->inner);
406 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800407 // Recompute induction information of this loop if the induction
408 // of any inner loop has been simplified.
Aart Bik482095d2016-10-10 15:39:10 -0700409 if (current_induction_simplification_count != induction_simplication_count_) {
410 induction_range_.ReVisit(node->loop_info);
411 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800412 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800413 // Note that since each simplification consists of eliminating code (without
414 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800415 do {
416 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800417 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800418 SimplifyBlocks(node);
Aart Bikdf7822e2016-12-06 10:05:30 -0800419 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800420 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700421 if (node->inner == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800422 OptimizeInnerLoop(node);
Aart Bik9abf8942016-10-14 09:49:42 -0700423 }
Aart Bik281c6812016-08-26 11:31:48 -0700424 }
425}
426
Aart Bikf8f5a162017-02-06 15:35:29 -0800427//
428// Optimization.
429//
430
Aart Bik281c6812016-08-26 11:31:48 -0700431void HLoopOptimization::SimplifyInduction(LoopNode* node) {
432 HBasicBlock* header = node->loop_info->GetHeader();
433 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700434 // Scan the phis in the header to find opportunities to simplify an induction
435 // cycle that is only used outside the loop. Replace these uses, if any, with
436 // the last value and remove the induction cycle.
437 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
438 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700439 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
440 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800441 iset_->clear(); // prepare phi induction
442 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
443 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +0100444 // Note that it's ok to have replaced uses after the loop with the last value, without
445 // being able to remove the cycle. Environment uses (which are the reason we may not be
446 // able to remove the cycle) within the loop will still hold the right value.
447 if (CanRemoveCycle()) {
448 for (HInstruction* i : *iset_) {
449 RemoveFromCycle(i);
450 }
451 simplified_ = true;
Aart Bik281c6812016-08-26 11:31:48 -0700452 }
Aart Bik482095d2016-10-10 15:39:10 -0700453 }
454 }
455}
456
457void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800458 // Iterate over all basic blocks in the loop-body.
459 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
460 HBasicBlock* block = it.Current();
461 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800462 RemoveDeadInstructions(block->GetPhis());
463 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800464 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800465 if (block->GetPredecessors().size() == 1 &&
466 block->GetSuccessors().size() == 1 &&
467 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800468 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800469 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800470 } else if (block->GetSuccessors().size() == 2) {
471 // Trivial if block can be bypassed to either branch.
472 HBasicBlock* succ0 = block->GetSuccessors()[0];
473 HBasicBlock* succ1 = block->GetSuccessors()[1];
474 HBasicBlock* meet0 = nullptr;
475 HBasicBlock* meet1 = nullptr;
476 if (succ0 != succ1 &&
477 IsGotoBlock(succ0, &meet0) &&
478 IsGotoBlock(succ1, &meet1) &&
479 meet0 == meet1 && // meets again
480 meet0 != block && // no self-loop
481 meet0->GetPhis().IsEmpty()) { // not used for merging
482 simplified_ = true;
483 succ0->DisconnectAndDelete();
484 if (block->Dominates(meet0)) {
485 block->RemoveDominatedBlock(meet0);
486 succ1->AddDominatedBlock(meet0);
487 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700488 }
Aart Bik482095d2016-10-10 15:39:10 -0700489 }
Aart Bik281c6812016-08-26 11:31:48 -0700490 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800491 }
Aart Bik281c6812016-08-26 11:31:48 -0700492}
493
Aart Bikf8f5a162017-02-06 15:35:29 -0800494void HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700495 HBasicBlock* header = node->loop_info->GetHeader();
496 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700497 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800498 int64_t trip_count = 0;
499 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
500 return;
Aart Bik9abf8942016-10-14 09:49:42 -0700501 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800502
Aart Bik281c6812016-08-26 11:31:48 -0700503 // Ensure there is only a single loop-body (besides the header).
504 HBasicBlock* body = nullptr;
505 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
506 if (it.Current() != header) {
507 if (body != nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800508 return;
Aart Bik281c6812016-08-26 11:31:48 -0700509 }
510 body = it.Current();
511 }
512 }
Andreas Gampef45d61c2017-06-07 10:29:33 -0700513 CHECK(body != nullptr);
Aart Bik281c6812016-08-26 11:31:48 -0700514 // Ensure there is only a single exit point.
515 if (header->GetSuccessors().size() != 2) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800516 return;
Aart Bik281c6812016-08-26 11:31:48 -0700517 }
518 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
519 ? header->GetSuccessors()[1]
520 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700521 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700522 if (exit->GetPredecessors().size() != 1) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800523 return;
Aart Bik281c6812016-08-26 11:31:48 -0700524 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800525 // Detect either an empty loop (no side effects other than plain iteration) or
526 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
527 // with the last value and remove the loop, possibly after unrolling its body.
528 HInstruction* phi = header->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800529 iset_->clear(); // prepare phi induction
530 if (TrySetSimpleLoopHeader(header)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800531 bool is_empty = IsEmptyBody(body);
Aart Bikf8f5a162017-02-06 15:35:29 -0800532 if ((is_empty || trip_count == 1) &&
533 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800534 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800535 // Unroll the loop-body, which sees initial value of the index.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800536 phi->ReplaceWith(phi->InputAt(0));
537 preheader->MergeInstructionsWith(body);
538 }
539 body->DisconnectAndDelete();
540 exit->RemovePredecessor(header);
541 header->RemoveSuccessor(exit);
542 header->RemoveDominatedBlock(exit);
543 header->DisconnectAndDelete();
544 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800545 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800546 preheader->AddDominatedBlock(exit);
547 exit->SetDominator(preheader);
548 RemoveLoop(node); // update hierarchy
Aart Bikf8f5a162017-02-06 15:35:29 -0800549 return;
550 }
551 }
552
553 // Vectorize loop, if possible and valid.
554 if (kEnableVectorization) {
555 iset_->clear(); // prepare phi induction
556 if (TrySetSimpleLoopHeader(header) &&
Aart Bik14a68b42017-06-08 14:06:58 -0700557 ShouldVectorize(node, body, trip_count) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800558 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
559 Vectorize(node, body, exit, trip_count);
560 graph_->SetHasSIMD(true); // flag SIMD usage
561 return;
562 }
563 }
564}
565
566//
567// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
568// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
569// Intel Press, June, 2004 (http://www.aartbik.com/).
570//
571
Aart Bik14a68b42017-06-08 14:06:58 -0700572bool HLoopOptimization::ShouldVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800573 // Reset vector bookkeeping.
574 vector_length_ = 0;
575 vector_refs_->clear();
Aart Bik14a68b42017-06-08 14:06:58 -0700576 vector_peeling_candidate_ = nullptr;
Aart Bikf8f5a162017-02-06 15:35:29 -0800577 vector_runtime_test_a_ =
578 vector_runtime_test_b_= nullptr;
579
580 // Phis in the loop-body prevent vectorization.
581 if (!block->GetPhis().IsEmpty()) {
582 return false;
583 }
584
585 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
586 // occurrence, which allows passing down attributes down the use tree.
587 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
588 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
589 return false; // failure to vectorize a left-hand-side
590 }
591 }
592
Aart Bik14a68b42017-06-08 14:06:58 -0700593 // Does vectorization seem profitable?
594 if (!IsVectorizationProfitable(trip_count)) {
595 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800596 }
597
598 // Data dependence analysis. Find each pair of references with same type, where
599 // at least one is a write. Each such pair denotes a possible data dependence.
600 // This analysis exploits the property that differently typed arrays cannot be
601 // aliased, as well as the property that references either point to the same
602 // array or to two completely disjoint arrays, i.e., no partial aliasing.
603 // Other than a few simply heuristics, no detailed subscript analysis is done.
604 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
605 for (auto j = i; ++j != vector_refs_->end(); ) {
606 if (i->type == j->type && (i->lhs || j->lhs)) {
607 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
608 HInstruction* a = i->base;
609 HInstruction* b = j->base;
610 HInstruction* x = i->offset;
611 HInstruction* y = j->offset;
612 if (a == b) {
613 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
614 // Conservatively assume a loop-carried data dependence otherwise, and reject.
615 if (x != y) {
616 return false;
617 }
618 } else {
619 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
620 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
621 // generating an explicit a != b disambiguation runtime test on the two references.
622 if (x != y) {
623 // For now, we reject after one test to avoid excessive overhead.
624 if (vector_runtime_test_a_ != nullptr) {
625 return false;
626 }
627 vector_runtime_test_a_ = a;
628 vector_runtime_test_b_ = b;
629 }
630 }
631 }
632 }
633 }
634
Aart Bik14a68b42017-06-08 14:06:58 -0700635 // Consider dynamic loop peeling for alignment.
636 SetPeelingCandidate(trip_count);
637
Aart Bikf8f5a162017-02-06 15:35:29 -0800638 // Success!
639 return true;
640}
641
642void HLoopOptimization::Vectorize(LoopNode* node,
643 HBasicBlock* block,
644 HBasicBlock* exit,
645 int64_t trip_count) {
646 Primitive::Type induc_type = Primitive::kPrimInt;
647 HBasicBlock* header = node->loop_info->GetHeader();
648 HBasicBlock* preheader = node->loop_info->GetPreHeader();
649
Aart Bik14a68b42017-06-08 14:06:58 -0700650 // Pick a loop unrolling factor for the vector loop.
651 uint32_t unroll = GetUnrollingFactor(block, trip_count);
652 uint32_t chunk = vector_length_ * unroll;
653
654 // A cleanup loop is needed, at least, for any unknown trip count or
655 // for a known trip count with remainder iterations after vectorization.
656 bool needs_cleanup = trip_count == 0 || (trip_count % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800657
658 // Adjust vector bookkeeping.
659 iset_->clear(); // prepare phi induction
660 bool is_simple_loop_header = TrySetSimpleLoopHeader(header); // fills iset_
661 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700662 vector_header_ = header;
663 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800664
Aart Bik14a68b42017-06-08 14:06:58 -0700665 // Generate dynamic loop peeling trip count, if needed:
666 // ptc = <peeling-needed-for-candidate>
667 HInstruction* ptc = nullptr;
668 if (vector_peeling_candidate_ != nullptr) {
669 DCHECK_LT(vector_length_, trip_count) << "dynamic peeling currently requires known trip count";
670 //
671 // TODO: Implement this. Compute address of first access memory location and
672 // compute peeling factor to obtain kAlignedBase alignment.
673 //
674 needs_cleanup = true;
675 }
676
677 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800678 // stc = <trip-count>;
Aart Bik14a68b42017-06-08 14:06:58 -0700679 // vtc = stc - (stc - ptc) % chunk;
680 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800681 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
682 HInstruction* vtc = stc;
683 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700684 DCHECK(IsPowerOfTwo(chunk));
685 HInstruction* diff = stc;
686 if (ptc != nullptr) {
687 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
688 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800689 HInstruction* rem = Insert(
690 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700691 diff,
692 graph_->GetIntConstant(chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800693 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
694 }
Aart Bik14a68b42017-06-08 14:06:58 -0700695 vector_index_ = graph_->GetIntConstant(0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800696
697 // Generate runtime disambiguation test:
698 // vtc = a != b ? vtc : 0;
699 if (vector_runtime_test_a_ != nullptr) {
700 HInstruction* rt = Insert(
701 preheader,
702 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
703 vtc = Insert(preheader,
704 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
705 needs_cleanup = true;
706 }
707
Aart Bik14a68b42017-06-08 14:06:58 -0700708 // Generate dynamic peeling loop for alignment, if needed:
709 // for ( ; i < ptc; i += 1)
710 // <loop-body>
711 if (ptc != nullptr) {
712 vector_mode_ = kSequential;
713 GenerateNewLoop(node,
714 block,
715 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
716 vector_index_,
717 ptc,
718 graph_->GetIntConstant(1),
719 /*unroll*/ 1);
720 }
721
722 // Generate vector loop, possibly further unrolled:
723 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800724 // <vectorized-loop-body>
725 vector_mode_ = kVector;
726 GenerateNewLoop(node,
727 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700728 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
729 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800730 vtc,
Aart Bik14a68b42017-06-08 14:06:58 -0700731 graph_->GetIntConstant(vector_length_), // increment per unroll
732 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800733 HLoopInformation* vloop = vector_header_->GetLoopInformation();
734
735 // Generate cleanup loop, if needed:
736 // for ( ; i < stc; i += 1)
737 // <loop-body>
738 if (needs_cleanup) {
739 vector_mode_ = kSequential;
740 GenerateNewLoop(node,
741 block,
742 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700743 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800744 stc,
Aart Bik14a68b42017-06-08 14:06:58 -0700745 graph_->GetIntConstant(1),
746 /*unroll*/ 1);
Aart Bikf8f5a162017-02-06 15:35:29 -0800747 }
748
749 // Remove the original loop by disconnecting the body block
750 // and removing all instructions from the header.
751 block->DisconnectAndDelete();
752 while (!header->GetFirstInstruction()->IsGoto()) {
753 header->RemoveInstruction(header->GetFirstInstruction());
754 }
Aart Bik14a68b42017-06-08 14:06:58 -0700755 // Update loop hierarchy: the old header now resides in the same outer loop
756 // as the old preheader. Note that we don't bother putting sequential
757 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800758 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
759 node->loop_info = vloop;
760}
761
762void HLoopOptimization::GenerateNewLoop(LoopNode* node,
763 HBasicBlock* block,
764 HBasicBlock* new_preheader,
765 HInstruction* lo,
766 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700767 HInstruction* step,
768 uint32_t unroll) {
769 DCHECK(unroll == 1 || vector_mode_ == kVector);
Aart Bikf8f5a162017-02-06 15:35:29 -0800770 Primitive::Type induc_type = Primitive::kPrimInt;
771 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800772 vector_preheader_ = new_preheader,
773 vector_header_ = vector_preheader_->GetSingleSuccessor();
774 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -0700775 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
776 kNoRegNumber,
777 0,
778 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700779 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800780 // for (i = lo; i < hi; i += step)
781 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -0700782 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
783 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -0800784 vector_header_->AddInstruction(cond);
785 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -0700786 vector_index_ = phi;
787 for (uint32_t u = 0; u < unroll; u++) {
788 // Clear map, leaving loop invariants setup during unrolling.
789 if (u == 0) {
790 vector_map_->clear();
791 } else {
792 for (auto i = vector_map_->begin(); i != vector_map_->end(); ) {
793 if (i->second->IsVecReplicateScalar()) {
794 DCHECK(node->loop_info->IsDefinedOutOfTheLoop(i->first));
795 ++i;
796 } else {
797 i = vector_map_->erase(i);
798 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800799 }
800 }
Aart Bik14a68b42017-06-08 14:06:58 -0700801 // Generate instruction map.
802 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
803 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
804 DCHECK(vectorized_def);
805 }
806 // Generate body from the instruction map, but in original program order.
807 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
808 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
809 auto i = vector_map_->find(it.Current());
810 if (i != vector_map_->end() && !i->second->IsInBlock()) {
811 Insert(vector_body_, i->second);
812 // Deal with instructions that need an environment, such as the scalar intrinsics.
813 if (i->second->NeedsEnvironment()) {
814 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
815 }
816 }
817 }
818 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
819 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800820 }
Aart Bik14a68b42017-06-08 14:06:58 -0700821 // Finalize phi for the loop index.
822 phi->AddInput(lo);
823 phi->AddInput(vector_index_);
824 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -0800825}
826
827// TODO: accept reductions at left-hand-side, mixed-type store idioms, etc.
828bool HLoopOptimization::VectorizeDef(LoopNode* node,
829 HInstruction* instruction,
830 bool generate_code) {
831 // Accept a left-hand-side array base[index] for
832 // (1) supported vector type,
833 // (2) loop-invariant base,
834 // (3) unit stride index,
835 // (4) vectorizable right-hand-side value.
836 uint64_t restrictions = kNone;
837 if (instruction->IsArraySet()) {
838 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
839 HInstruction* base = instruction->InputAt(0);
840 HInstruction* index = instruction->InputAt(1);
841 HInstruction* value = instruction->InputAt(2);
842 HInstruction* offset = nullptr;
843 if (TrySetVectorType(type, &restrictions) &&
844 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bikfa762962017-04-07 11:33:37 -0700845 induction_range_.IsUnitStride(instruction, index, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800846 VectorizeUse(node, value, generate_code, type, restrictions)) {
847 if (generate_code) {
848 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -0700849 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -0800850 } else {
851 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
852 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800853 return true;
854 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800855 return false;
856 }
857 // Branch back okay.
858 if (instruction->IsGoto()) {
859 return true;
860 }
861 // Otherwise accept only expressions with no effects outside the immediate loop-body.
862 // Note that actual uses are inspected during right-hand-side tree traversal.
863 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
864}
865
Aart Bik304c8a52017-05-23 11:01:13 -0700866// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -0800867bool HLoopOptimization::VectorizeUse(LoopNode* node,
868 HInstruction* instruction,
869 bool generate_code,
870 Primitive::Type type,
871 uint64_t restrictions) {
872 // Accept anything for which code has already been generated.
873 if (generate_code) {
874 if (vector_map_->find(instruction) != vector_map_->end()) {
875 return true;
876 }
877 }
878 // Continue the right-hand-side tree traversal, passing in proper
879 // types and vector restrictions along the way. During code generation,
880 // all new nodes are drawn from the global allocator.
881 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
882 // Accept invariant use, using scalar expansion.
883 if (generate_code) {
884 GenerateVecInv(instruction, type);
885 }
886 return true;
887 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +0200888 // Deal with vector restrictions.
889 if (instruction->AsArrayGet()->IsStringCharAt() &&
890 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
891 return false;
892 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800893 // Accept a right-hand-side array base[index] for
894 // (1) exact matching vector type,
895 // (2) loop-invariant base,
896 // (3) unit stride index,
897 // (4) vectorizable right-hand-side value.
898 HInstruction* base = instruction->InputAt(0);
899 HInstruction* index = instruction->InputAt(1);
900 HInstruction* offset = nullptr;
901 if (type == instruction->GetType() &&
902 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bikfa762962017-04-07 11:33:37 -0700903 induction_range_.IsUnitStride(instruction, index, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800904 if (generate_code) {
905 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -0700906 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -0800907 } else {
908 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
909 }
910 return true;
911 }
912 } else if (instruction->IsTypeConversion()) {
913 // Accept particular type conversions.
914 HTypeConversion* conversion = instruction->AsTypeConversion();
915 HInstruction* opa = conversion->InputAt(0);
916 Primitive::Type from = conversion->GetInputType();
917 Primitive::Type to = conversion->GetResultType();
918 if ((to == Primitive::kPrimByte ||
919 to == Primitive::kPrimChar ||
920 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
921 // Accept a "narrowing" type conversion from a "wider" computation for
922 // (1) conversion into final required type,
923 // (2) vectorizable operand,
924 // (3) "wider" operations cannot bring in higher order bits.
925 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
926 if (generate_code) {
927 if (vector_mode_ == kVector) {
928 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
929 } else {
930 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
931 }
932 }
933 return true;
934 }
935 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
936 DCHECK_EQ(to, type);
937 // Accept int to float conversion for
938 // (1) supported int,
939 // (2) vectorizable operand.
940 if (TrySetVectorType(from, &restrictions) &&
941 VectorizeUse(node, opa, generate_code, from, restrictions)) {
942 if (generate_code) {
943 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
944 }
945 return true;
946 }
947 }
948 return false;
949 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
950 // Accept unary operator for vectorizable operand.
951 HInstruction* opa = instruction->InputAt(0);
952 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
953 if (generate_code) {
954 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
955 }
956 return true;
957 }
958 } else if (instruction->IsAdd() || instruction->IsSub() ||
959 instruction->IsMul() || instruction->IsDiv() ||
960 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
961 // Deal with vector restrictions.
962 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
963 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
964 return false;
965 }
966 // Accept binary operator for vectorizable operands.
967 HInstruction* opa = instruction->InputAt(0);
968 HInstruction* opb = instruction->InputAt(1);
969 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
970 VectorizeUse(node, opb, generate_code, type, restrictions)) {
971 if (generate_code) {
972 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
973 }
974 return true;
975 }
976 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700977 // Recognize vectorization idioms.
978 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
979 return true;
980 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800981 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -0700982 HInstruction* opa = instruction->InputAt(0);
983 HInstruction* opb = instruction->InputAt(1);
984 HInstruction* r = opa;
985 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800986 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
987 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
988 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -0700989 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
990 // Shifts right need extra care to account for higher order bits.
991 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
992 if (instruction->IsShr() &&
993 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
994 return false; // reject, unless all operands are sign-extension narrower
995 } else if (instruction->IsUShr() &&
996 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
997 return false; // reject, unless all operands are zero-extension narrower
998 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800999 }
1000 // Accept shift operator for vectorizable/invariant operands.
1001 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001002 DCHECK(r != nullptr);
1003 if (generate_code && vector_mode_ != kVector) { // de-idiom
1004 r = opa;
1005 }
Aart Bik50e20d52017-05-05 14:07:29 -07001006 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001007 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001008 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001009 // Restrict shift distance to packed data type width.
1010 int64_t max_distance = Primitive::ComponentSize(type) * 8;
1011 if (0 <= distance && distance < max_distance) {
1012 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001013 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001014 }
1015 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001016 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001017 }
1018 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001019 // Accept particular intrinsics.
1020 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1021 switch (invoke->GetIntrinsic()) {
1022 case Intrinsics::kMathAbsInt:
1023 case Intrinsics::kMathAbsLong:
1024 case Intrinsics::kMathAbsFloat:
1025 case Intrinsics::kMathAbsDouble: {
1026 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001027 HInstruction* opa = instruction->InputAt(0);
1028 HInstruction* r = opa;
1029 bool is_unsigned = false;
1030 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001031 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001032 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1033 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1034 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001035 }
1036 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001037 DCHECK(r != nullptr);
1038 if (generate_code && vector_mode_ != kVector) { // de-idiom
1039 r = opa;
1040 }
1041 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001042 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001043 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001044 }
1045 return true;
1046 }
1047 return false;
1048 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001049 case Intrinsics::kMathMinIntInt:
1050 case Intrinsics::kMathMinLongLong:
1051 case Intrinsics::kMathMinFloatFloat:
1052 case Intrinsics::kMathMinDoubleDouble:
1053 case Intrinsics::kMathMaxIntInt:
1054 case Intrinsics::kMathMaxLongLong:
1055 case Intrinsics::kMathMaxFloatFloat:
1056 case Intrinsics::kMathMaxDoubleDouble: {
1057 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001058 HInstruction* opa = instruction->InputAt(0);
1059 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001060 HInstruction* r = opa;
1061 HInstruction* s = opb;
1062 bool is_unsigned = false;
1063 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1064 return false;
1065 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1066 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1067 return false; // reject, unless all operands are same-extension narrower
1068 }
1069 // Accept MIN/MAX(x, y) for vectorizable operands.
1070 DCHECK(r != nullptr && s != nullptr);
1071 if (generate_code && vector_mode_ != kVector) { // de-idiom
1072 r = opa;
1073 s = opb;
1074 }
1075 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1076 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001077 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001078 GenerateVecOp(
1079 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001080 }
1081 return true;
1082 }
1083 return false;
1084 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001085 default:
1086 return false;
1087 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001088 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001089 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001090}
1091
Aart Bikf8f5a162017-02-06 15:35:29 -08001092bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
1093 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1094 switch (compiler_driver_->GetInstructionSet()) {
1095 case kArm:
1096 case kThumb2:
1097 return false;
1098 case kArm64:
1099 // Allow vectorization for all ARM devices, because Android assumes that
Artem Serovd4bccf12017-04-03 18:47:32 +01001100 // ARMv8 AArch64 always supports advanced SIMD.
Aart Bikf8f5a162017-02-06 15:35:29 -08001101 switch (type) {
1102 case Primitive::kPrimBoolean:
1103 case Primitive::kPrimByte:
Aart Bik304c8a52017-05-23 11:01:13 -07001104 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001105 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -08001106 case Primitive::kPrimChar:
1107 case Primitive::kPrimShort:
Aart Bik304c8a52017-05-23 11:01:13 -07001108 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001109 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -08001110 case Primitive::kPrimInt:
1111 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001112 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001113 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001114 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001115 return TrySetVectorLength(2);
1116 case Primitive::kPrimFloat:
Artem Serovd4bccf12017-04-03 18:47:32 +01001117 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001118 case Primitive::kPrimDouble:
Aart Bikf8f5a162017-02-06 15:35:29 -08001119 return TrySetVectorLength(2);
1120 default:
1121 return false;
1122 }
1123 case kX86:
1124 case kX86_64:
1125 // Allow vectorization for SSE4-enabled X86 devices only (128-bit vectors).
1126 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1127 switch (type) {
1128 case Primitive::kPrimBoolean:
1129 case Primitive::kPrimByte:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001130 *restrictions |= kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001131 return TrySetVectorLength(16);
1132 case Primitive::kPrimChar:
1133 case Primitive::kPrimShort:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001134 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001135 return TrySetVectorLength(8);
1136 case Primitive::kPrimInt:
1137 *restrictions |= kNoDiv;
1138 return TrySetVectorLength(4);
1139 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001140 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001141 return TrySetVectorLength(2);
1142 case Primitive::kPrimFloat:
Aart Bikc8e93c72017-05-10 10:49:22 -07001143 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001144 return TrySetVectorLength(4);
1145 case Primitive::kPrimDouble:
Aart Bikc8e93c72017-05-10 10:49:22 -07001146 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001147 return TrySetVectorLength(2);
1148 default:
1149 break;
1150 } // switch type
1151 }
1152 return false;
1153 case kMips:
Aart Bikf8f5a162017-02-06 15:35:29 -08001154 // TODO: implement MIPS SIMD.
1155 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001156 case kMips64:
1157 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1158 switch (type) {
1159 case Primitive::kPrimBoolean:
1160 case Primitive::kPrimByte:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001161 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001162 return TrySetVectorLength(16);
1163 case Primitive::kPrimChar:
1164 case Primitive::kPrimShort:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001165 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001166 return TrySetVectorLength(8);
1167 case Primitive::kPrimInt:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001168 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001169 return TrySetVectorLength(4);
1170 case Primitive::kPrimLong:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001171 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001172 return TrySetVectorLength(2);
1173 case Primitive::kPrimFloat:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001174 *restrictions |= kNoMinMax; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001175 return TrySetVectorLength(4);
1176 case Primitive::kPrimDouble:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001177 *restrictions |= kNoMinMax; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001178 return TrySetVectorLength(2);
1179 default:
1180 break;
1181 } // switch type
1182 }
1183 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001184 default:
1185 return false;
1186 } // switch instruction set
1187}
1188
1189bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1190 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1191 // First time set?
1192 if (vector_length_ == 0) {
1193 vector_length_ = length;
1194 }
1195 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1196 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1197 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1198 return vector_length_ == length;
1199}
1200
1201void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
1202 if (vector_map_->find(org) == vector_map_->end()) {
1203 // In scalar code, just use a self pass-through for scalar invariants
1204 // (viz. expression remains itself).
1205 if (vector_mode_ == kSequential) {
1206 vector_map_->Put(org, org);
1207 return;
1208 }
1209 // In vector code, explicit scalar expansion is needed.
1210 HInstruction* vector = new (global_allocator_) HVecReplicateScalar(
1211 global_allocator_, org, type, vector_length_);
1212 vector_map_->Put(org, Insert(vector_preheader_, vector));
1213 }
1214}
1215
1216void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1217 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001218 HInstruction* subscript = vector_index_;
Aart Bikf8f5a162017-02-06 15:35:29 -08001219 if (offset != nullptr) {
1220 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
1221 if (org->IsPhi()) {
1222 Insert(vector_body_, subscript); // lacks layout placeholder
1223 }
1224 }
1225 vector_map_->Put(org, subscript);
1226 }
1227}
1228
1229void HLoopOptimization::GenerateVecMem(HInstruction* org,
1230 HInstruction* opa,
1231 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001232 HInstruction* offset,
Aart Bikf8f5a162017-02-06 15:35:29 -08001233 Primitive::Type type) {
1234 HInstruction* vector = nullptr;
1235 if (vector_mode_ == kVector) {
1236 // Vector store or load.
Aart Bik14a68b42017-06-08 14:06:58 -07001237 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001238 if (opb != nullptr) {
1239 vector = new (global_allocator_) HVecStore(
Aart Bik14a68b42017-06-08 14:06:58 -07001240 global_allocator_, base, opa, opb, type, vector_length_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001241 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001242 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001243 vector = new (global_allocator_) HVecLoad(
Aart Bik14a68b42017-06-08 14:06:58 -07001244 global_allocator_, base, opa, type, vector_length_, is_string_char_at);
1245 }
1246 // Known dynamically enforced alignment?
1247 // TODO: detect offset + constant differences.
1248 // TODO: long run, static alignment analysis?
1249 if (vector_peeling_candidate_ != nullptr &&
1250 vector_peeling_candidate_->base == base &&
1251 vector_peeling_candidate_->offset == offset) {
1252 vector->AsVecMemoryOperation()->SetAlignment(Alignment(kAlignedBase, 0));
Aart Bikf8f5a162017-02-06 15:35:29 -08001253 }
1254 } else {
1255 // Scalar store or load.
1256 DCHECK(vector_mode_ == kSequential);
1257 if (opb != nullptr) {
1258 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1259 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001260 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1261 vector = new (global_allocator_) HArrayGet(
1262 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001263 }
1264 }
1265 vector_map_->Put(org, vector);
1266}
1267
1268#define GENERATE_VEC(x, y) \
1269 if (vector_mode_ == kVector) { \
1270 vector = (x); \
1271 } else { \
1272 DCHECK(vector_mode_ == kSequential); \
1273 vector = (y); \
1274 } \
1275 break;
1276
1277void HLoopOptimization::GenerateVecOp(HInstruction* org,
1278 HInstruction* opa,
1279 HInstruction* opb,
Aart Bik304c8a52017-05-23 11:01:13 -07001280 Primitive::Type type,
1281 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001282 if (vector_mode_ == kSequential) {
Aart Bik304c8a52017-05-23 11:01:13 -07001283 // Non-converting scalar code follows implicit integral promotion.
1284 if (!org->IsTypeConversion() && (type == Primitive::kPrimBoolean ||
1285 type == Primitive::kPrimByte ||
1286 type == Primitive::kPrimChar ||
1287 type == Primitive::kPrimShort)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001288 type = Primitive::kPrimInt;
1289 }
1290 }
1291 HInstruction* vector = nullptr;
1292 switch (org->GetKind()) {
1293 case HInstruction::kNeg:
1294 DCHECK(opb == nullptr);
1295 GENERATE_VEC(
1296 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
1297 new (global_allocator_) HNeg(type, opa));
1298 case HInstruction::kNot:
1299 DCHECK(opb == nullptr);
1300 GENERATE_VEC(
1301 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1302 new (global_allocator_) HNot(type, opa));
1303 case HInstruction::kBooleanNot:
1304 DCHECK(opb == nullptr);
1305 GENERATE_VEC(
1306 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1307 new (global_allocator_) HBooleanNot(opa));
1308 case HInstruction::kTypeConversion:
1309 DCHECK(opb == nullptr);
1310 GENERATE_VEC(
1311 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
1312 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
1313 case HInstruction::kAdd:
1314 GENERATE_VEC(
1315 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
1316 new (global_allocator_) HAdd(type, opa, opb));
1317 case HInstruction::kSub:
1318 GENERATE_VEC(
1319 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
1320 new (global_allocator_) HSub(type, opa, opb));
1321 case HInstruction::kMul:
1322 GENERATE_VEC(
1323 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
1324 new (global_allocator_) HMul(type, opa, opb));
1325 case HInstruction::kDiv:
1326 GENERATE_VEC(
1327 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
1328 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
1329 case HInstruction::kAnd:
1330 GENERATE_VEC(
1331 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
1332 new (global_allocator_) HAnd(type, opa, opb));
1333 case HInstruction::kOr:
1334 GENERATE_VEC(
1335 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
1336 new (global_allocator_) HOr(type, opa, opb));
1337 case HInstruction::kXor:
1338 GENERATE_VEC(
1339 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
1340 new (global_allocator_) HXor(type, opa, opb));
1341 case HInstruction::kShl:
1342 GENERATE_VEC(
1343 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
1344 new (global_allocator_) HShl(type, opa, opb));
1345 case HInstruction::kShr:
1346 GENERATE_VEC(
1347 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
1348 new (global_allocator_) HShr(type, opa, opb));
1349 case HInstruction::kUShr:
1350 GENERATE_VEC(
1351 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
1352 new (global_allocator_) HUShr(type, opa, opb));
1353 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001354 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1355 if (vector_mode_ == kVector) {
1356 switch (invoke->GetIntrinsic()) {
1357 case Intrinsics::kMathAbsInt:
1358 case Intrinsics::kMathAbsLong:
1359 case Intrinsics::kMathAbsFloat:
1360 case Intrinsics::kMathAbsDouble:
1361 DCHECK(opb == nullptr);
1362 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1363 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001364 case Intrinsics::kMathMinIntInt:
1365 case Intrinsics::kMathMinLongLong:
1366 case Intrinsics::kMathMinFloatFloat:
1367 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001368 vector = new (global_allocator_)
1369 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1370 break;
1371 }
1372 case Intrinsics::kMathMaxIntInt:
1373 case Intrinsics::kMathMaxLongLong:
1374 case Intrinsics::kMathMaxFloatFloat:
1375 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001376 vector = new (global_allocator_)
1377 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1378 break;
1379 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001380 default:
1381 LOG(FATAL) << "Unsupported SIMD intrinsic";
1382 UNREACHABLE();
1383 } // switch invoke
1384 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001385 // In scalar code, simply clone the method invoke, and replace its operands with the
1386 // corresponding new scalar instructions in the loop. The instruction will get an
1387 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001388 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001389 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001390 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1391 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001392 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001393 invoke->GetType(),
1394 invoke->GetDexPc(),
1395 invoke->GetDexMethodIndex(),
1396 invoke->GetResolvedMethod(),
1397 invoke->GetDispatchInfo(),
1398 invoke->GetInvokeType(),
1399 invoke->GetTargetMethod(),
1400 invoke->GetClinitCheckRequirement());
1401 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001402 size_t num_inputs = inputs.size();
1403 DCHECK_LE(num_args, num_inputs);
1404 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1405 for (size_t index = 0; index < num_inputs; ++index) {
1406 HInstruction* new_input = index < num_args
1407 ? vector_map_->Get(inputs[index])
1408 : inputs[index]; // beyond arguments: just pass through
1409 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001410 }
Aart Bik98990262017-04-10 13:15:57 -07001411 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1412 kNeedsEnvironmentOrCache,
1413 kNoSideEffects,
1414 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001415 vector = new_invoke;
1416 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001417 break;
1418 }
1419 default:
1420 break;
1421 } // switch
1422 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1423 vector_map_->Put(org, vector);
1424}
1425
1426#undef GENERATE_VEC
1427
1428//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001429// Vectorization idioms.
1430//
1431
1432// Method recognizes the following idioms:
1433// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1434// regular halving add (a + b) >> 1 for unsigned/signed operands a, b
1435// Provided that the operands are promoted to a wider form to do the arithmetic and
1436// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1437// implementation that operates directly in narrower form (plus one extra bit).
1438// TODO: current version recognizes implicit byte/short/char widening only;
1439// explicit widening from int to long could be added later.
1440bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1441 HInstruction* instruction,
1442 bool generate_code,
1443 Primitive::Type type,
1444 uint64_t restrictions) {
1445 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001446 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001447 // on the narrow precision computed by the idiom).
Aart Bik5f805002017-05-16 16:42:41 -07001448 int64_t distance = 0;
Aart Bikf3e61ee2017-04-12 17:09:20 -07001449 if ((instruction->IsShr() ||
1450 instruction->IsUShr()) &&
Aart Bik5f805002017-05-16 16:42:41 -07001451 IsInt64AndGet(instruction->InputAt(1), /*out*/ &distance) && distance == 1) {
1452 // Test for (a + b + c) >> 1 for optional constant c.
1453 HInstruction* a = nullptr;
1454 HInstruction* b = nullptr;
1455 int64_t c = 0;
1456 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001457 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001458 // Accept c == 1 (rounded) or c == 0 (not rounded).
1459 bool is_rounded = false;
1460 if (c == 1) {
1461 is_rounded = true;
1462 } else if (c != 0) {
1463 return false;
1464 }
1465 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001466 HInstruction* r = nullptr;
1467 HInstruction* s = nullptr;
1468 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001469 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001470 return false;
1471 }
1472 // Deal with vector restrictions.
1473 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1474 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1475 return false;
1476 }
1477 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1478 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
1479 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001480 if (generate_code && vector_mode_ != kVector) { // de-idiom
1481 r = instruction->InputAt(0);
1482 s = instruction->InputAt(1);
1483 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001484 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1485 VectorizeUse(node, s, generate_code, type, restrictions)) {
1486 if (generate_code) {
1487 if (vector_mode_ == kVector) {
1488 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1489 global_allocator_,
1490 vector_map_->Get(r),
1491 vector_map_->Get(s),
1492 type,
1493 vector_length_,
1494 is_unsigned,
1495 is_rounded));
1496 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001497 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001498 }
1499 }
1500 return true;
1501 }
1502 }
1503 }
1504 return false;
1505}
1506
1507//
Aart Bik14a68b42017-06-08 14:06:58 -07001508// Vectorization heuristics.
1509//
1510
1511bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
1512 // Current heuristic: non-empty body with sufficient number
1513 // of iterations (if known).
1514 // TODO: refine by looking at e.g. operation count, alignment, etc.
1515 if (vector_length_ == 0) {
1516 return false; // nothing found
1517 } else if (0 < trip_count && trip_count < vector_length_) {
1518 return false; // insufficient iterations
1519 }
1520 return true;
1521}
1522
1523void HLoopOptimization::SetPeelingCandidate(int64_t trip_count ATTRIBUTE_UNUSED) {
1524 // Current heuristic: none.
1525 // TODO: implement
1526}
1527
1528uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
1529 // Current heuristic: unroll by 2 on ARM64/X86 for large known trip
1530 // counts and small loop bodies.
1531 // TODO: refine with operation count, remaining iterations, etc.
1532 // Artem had some really cool ideas for this already.
1533 switch (compiler_driver_->GetInstructionSet()) {
1534 case kArm64:
1535 case kX86:
1536 case kX86_64: {
1537 size_t num_instructions = block->GetInstructions().CountSize();
1538 if (num_instructions <= 10 && trip_count >= 4 * vector_length_) {
1539 return 2;
1540 }
1541 return 1;
1542 }
1543 default:
1544 return 1;
1545 }
1546}
1547
1548//
Aart Bikf8f5a162017-02-06 15:35:29 -08001549// Helpers.
1550//
1551
1552bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01001553 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
1554 // smart enough to follow strongly connected components (and it's probably not worth
1555 // it to make it so). See b/33775412.
1556 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
1557 return false;
1558 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001559 DCHECK(iset_->empty());
Aart Bikcc42be02016-10-20 16:14:16 -07001560 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1561 if (set != nullptr) {
1562 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001563 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001564 // each instruction is removable and, when restrict uses are requested, other than for phi,
1565 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001566 if (!i->IsInBlock()) {
1567 continue;
1568 } else if (!i->IsRemovable()) {
1569 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001570 } else if (i != phi && restrict_uses) {
Aart Bikcc42be02016-10-20 16:14:16 -07001571 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1572 if (set->find(use.GetUser()) == set->end()) {
1573 return false;
1574 }
1575 }
1576 }
Aart Bike3dedc52016-11-02 17:50:27 -07001577 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001578 }
Aart Bikcc42be02016-10-20 16:14:16 -07001579 return true;
1580 }
1581 return false;
1582}
1583
1584// Find: phi: Phi(init, addsub)
1585// s: SuspendCheck
1586// c: Condition(phi, bound)
1587// i: If(c)
1588// TODO: Find a less pattern matching approach?
Aart Bikf8f5a162017-02-06 15:35:29 -08001589bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block) {
Aart Bikcc42be02016-10-20 16:14:16 -07001590 DCHECK(iset_->empty());
1591 HInstruction* phi = block->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -08001592 if (phi != nullptr &&
1593 phi->GetNext() == nullptr &&
1594 TrySetPhiInduction(phi->AsPhi(), /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001595 HInstruction* s = block->GetFirstInstruction();
1596 if (s != nullptr && s->IsSuspendCheck()) {
1597 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07001598 if (c != nullptr &&
1599 c->IsCondition() &&
1600 c->GetUses().HasExactlyOneElement() && // only used for termination
1601 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07001602 HInstruction* i = c->GetNext();
1603 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1604 iset_->insert(c);
1605 iset_->insert(s);
1606 return true;
1607 }
1608 }
1609 }
1610 }
1611 return false;
1612}
1613
1614bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001615 if (!block->GetPhis().IsEmpty()) {
1616 return false;
1617 }
1618 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1619 HInstruction* instruction = it.Current();
1620 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1621 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001622 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001623 }
1624 return true;
1625}
1626
1627bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1628 HInstruction* instruction) {
1629 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1630 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1631 return true;
1632 }
Aart Bikcc42be02016-10-20 16:14:16 -07001633 }
1634 return false;
1635}
1636
Aart Bik482095d2016-10-10 15:39:10 -07001637bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001638 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001639 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001640 /*out*/ int32_t* use_count) {
1641 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1642 HInstruction* user = use.GetUser();
1643 if (iset_->find(user) == iset_->end()) { // not excluded?
1644 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001645 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001646 // If collect_loop_uses is set, simply keep adding those uses to the set.
1647 // Otherwise, reject uses inside the loop that were not already in the set.
1648 if (collect_loop_uses) {
1649 iset_->insert(user);
1650 continue;
1651 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001652 return false;
1653 }
1654 ++*use_count;
1655 }
1656 }
1657 return true;
1658}
1659
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001660bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
1661 HInstruction* instruction,
1662 HBasicBlock* block) {
1663 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07001664 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001665 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
1666 const HUseList<HInstruction*>& uses = instruction->GetUses();
1667 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1668 HInstruction* user = it->GetUser();
1669 size_t index = it->GetIndex();
1670 ++it; // increment before replacing
1671 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001672 if (kIsDebugBuild) {
1673 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
1674 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
1675 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
1676 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001677 user->ReplaceInput(replacement, index);
1678 induction_range_.Replace(user, instruction, replacement); // update induction
1679 }
1680 }
1681 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1682 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1683 HEnvironment* user = it->GetUser();
1684 size_t index = it->GetIndex();
1685 ++it; // increment before replacing
1686 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001687 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07001688 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001689 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
1690 user->RemoveAsUserOfInput(index);
1691 user->SetRawEnvAt(index, replacement);
1692 replacement->AddEnvUseAt(user, index);
1693 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001694 }
1695 }
1696 induction_simplication_count_++;
Aart Bik807868e2016-11-03 17:51:43 -07001697 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001698 }
Aart Bik807868e2016-11-03 17:51:43 -07001699 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001700}
1701
Aart Bikf8f5a162017-02-06 15:35:29 -08001702bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1703 HInstruction* instruction,
1704 HBasicBlock* block,
1705 bool collect_loop_uses) {
1706 // Assigning the last value is always successful if there are no uses.
1707 // Otherwise, it succeeds in a no early-exit loop by generating the
1708 // proper last value assignment.
1709 int32_t use_count = 0;
1710 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
1711 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001712 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001713}
1714
Aart Bik6b69e0a2017-01-11 10:20:43 -08001715void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
1716 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
1717 HInstruction* instruction = i.Current();
1718 if (instruction->IsDeadAndRemovable()) {
1719 simplified_ = true;
1720 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
1721 }
1722 }
1723}
1724
Aart Bik14a68b42017-06-08 14:06:58 -07001725bool HLoopOptimization::CanRemoveCycle() {
1726 for (HInstruction* i : *iset_) {
1727 // We can never remove instructions that have environment
1728 // uses when we compile 'debuggable'.
1729 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
1730 return false;
1731 }
1732 // A deoptimization should never have an environment input removed.
1733 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
1734 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
1735 return false;
1736 }
1737 }
1738 }
1739 return true;
1740}
1741
Aart Bik281c6812016-08-26 11:31:48 -07001742} // namespace art