blob: b61d7b80d11f50a0c094685dec4ebf4eb8f5071d [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) {
Aart Bik37dc4df2017-06-28 14:08:00 -0700623 // To avoid excessive overhead, we only accept one a != b test.
624 if (vector_runtime_test_a_ == nullptr) {
625 // First test found.
626 vector_runtime_test_a_ = a;
627 vector_runtime_test_b_ = b;
628 } else if ((vector_runtime_test_a_ != a || vector_runtime_test_b_ != b) &&
629 (vector_runtime_test_a_ != b || vector_runtime_test_b_ != a)) {
630 return false; // second test would be needed
Aart Bikf8f5a162017-02-06 15:35:29 -0800631 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800632 }
633 }
634 }
635 }
636 }
637
Aart Bik14a68b42017-06-08 14:06:58 -0700638 // Consider dynamic loop peeling for alignment.
639 SetPeelingCandidate(trip_count);
640
Aart Bikf8f5a162017-02-06 15:35:29 -0800641 // Success!
642 return true;
643}
644
645void HLoopOptimization::Vectorize(LoopNode* node,
646 HBasicBlock* block,
647 HBasicBlock* exit,
648 int64_t trip_count) {
649 Primitive::Type induc_type = Primitive::kPrimInt;
650 HBasicBlock* header = node->loop_info->GetHeader();
651 HBasicBlock* preheader = node->loop_info->GetPreHeader();
652
Aart Bik14a68b42017-06-08 14:06:58 -0700653 // Pick a loop unrolling factor for the vector loop.
654 uint32_t unroll = GetUnrollingFactor(block, trip_count);
655 uint32_t chunk = vector_length_ * unroll;
656
657 // A cleanup loop is needed, at least, for any unknown trip count or
658 // for a known trip count with remainder iterations after vectorization.
659 bool needs_cleanup = trip_count == 0 || (trip_count % chunk) != 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800660
661 // Adjust vector bookkeeping.
662 iset_->clear(); // prepare phi induction
663 bool is_simple_loop_header = TrySetSimpleLoopHeader(header); // fills iset_
664 DCHECK(is_simple_loop_header);
Aart Bik14a68b42017-06-08 14:06:58 -0700665 vector_header_ = header;
666 vector_body_ = block;
Aart Bikf8f5a162017-02-06 15:35:29 -0800667
Aart Bik14a68b42017-06-08 14:06:58 -0700668 // Generate dynamic loop peeling trip count, if needed:
669 // ptc = <peeling-needed-for-candidate>
670 HInstruction* ptc = nullptr;
671 if (vector_peeling_candidate_ != nullptr) {
672 DCHECK_LT(vector_length_, trip_count) << "dynamic peeling currently requires known trip count";
673 //
674 // TODO: Implement this. Compute address of first access memory location and
675 // compute peeling factor to obtain kAlignedBase alignment.
676 //
677 needs_cleanup = true;
678 }
679
680 // Generate loop control:
Aart Bikf8f5a162017-02-06 15:35:29 -0800681 // stc = <trip-count>;
Aart Bik14a68b42017-06-08 14:06:58 -0700682 // vtc = stc - (stc - ptc) % chunk;
683 // i = 0;
Aart Bikf8f5a162017-02-06 15:35:29 -0800684 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
685 HInstruction* vtc = stc;
686 if (needs_cleanup) {
Aart Bik14a68b42017-06-08 14:06:58 -0700687 DCHECK(IsPowerOfTwo(chunk));
688 HInstruction* diff = stc;
689 if (ptc != nullptr) {
690 diff = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, ptc));
691 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800692 HInstruction* rem = Insert(
693 preheader, new (global_allocator_) HAnd(induc_type,
Aart Bik14a68b42017-06-08 14:06:58 -0700694 diff,
695 graph_->GetIntConstant(chunk - 1)));
Aart Bikf8f5a162017-02-06 15:35:29 -0800696 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
697 }
Aart Bik14a68b42017-06-08 14:06:58 -0700698 vector_index_ = graph_->GetIntConstant(0);
Aart Bikf8f5a162017-02-06 15:35:29 -0800699
700 // Generate runtime disambiguation test:
701 // vtc = a != b ? vtc : 0;
702 if (vector_runtime_test_a_ != nullptr) {
703 HInstruction* rt = Insert(
704 preheader,
705 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
706 vtc = Insert(preheader,
707 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
708 needs_cleanup = true;
709 }
710
Aart Bik14a68b42017-06-08 14:06:58 -0700711 // Generate dynamic peeling loop for alignment, if needed:
712 // for ( ; i < ptc; i += 1)
713 // <loop-body>
714 if (ptc != nullptr) {
715 vector_mode_ = kSequential;
716 GenerateNewLoop(node,
717 block,
718 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
719 vector_index_,
720 ptc,
721 graph_->GetIntConstant(1),
722 /*unroll*/ 1);
723 }
724
725 // Generate vector loop, possibly further unrolled:
726 // for ( ; i < vtc; i += chunk)
Aart Bikf8f5a162017-02-06 15:35:29 -0800727 // <vectorized-loop-body>
728 vector_mode_ = kVector;
729 GenerateNewLoop(node,
730 block,
Aart Bik14a68b42017-06-08 14:06:58 -0700731 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
732 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800733 vtc,
Aart Bik14a68b42017-06-08 14:06:58 -0700734 graph_->GetIntConstant(vector_length_), // increment per unroll
735 unroll);
Aart Bikf8f5a162017-02-06 15:35:29 -0800736 HLoopInformation* vloop = vector_header_->GetLoopInformation();
737
738 // Generate cleanup loop, if needed:
739 // for ( ; i < stc; i += 1)
740 // <loop-body>
741 if (needs_cleanup) {
742 vector_mode_ = kSequential;
743 GenerateNewLoop(node,
744 block,
745 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
Aart Bik14a68b42017-06-08 14:06:58 -0700746 vector_index_,
Aart Bikf8f5a162017-02-06 15:35:29 -0800747 stc,
Aart Bik14a68b42017-06-08 14:06:58 -0700748 graph_->GetIntConstant(1),
749 /*unroll*/ 1);
Aart Bikf8f5a162017-02-06 15:35:29 -0800750 }
751
752 // Remove the original loop by disconnecting the body block
753 // and removing all instructions from the header.
754 block->DisconnectAndDelete();
755 while (!header->GetFirstInstruction()->IsGoto()) {
756 header->RemoveInstruction(header->GetFirstInstruction());
757 }
Aart Bik14a68b42017-06-08 14:06:58 -0700758 // Update loop hierarchy: the old header now resides in the same outer loop
759 // as the old preheader. Note that we don't bother putting sequential
760 // loops back in the hierarchy at this point.
Aart Bikf8f5a162017-02-06 15:35:29 -0800761 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
762 node->loop_info = vloop;
763}
764
765void HLoopOptimization::GenerateNewLoop(LoopNode* node,
766 HBasicBlock* block,
767 HBasicBlock* new_preheader,
768 HInstruction* lo,
769 HInstruction* hi,
Aart Bik14a68b42017-06-08 14:06:58 -0700770 HInstruction* step,
771 uint32_t unroll) {
772 DCHECK(unroll == 1 || vector_mode_ == kVector);
Aart Bikf8f5a162017-02-06 15:35:29 -0800773 Primitive::Type induc_type = Primitive::kPrimInt;
774 // Prepare new loop.
Aart Bikf8f5a162017-02-06 15:35:29 -0800775 vector_preheader_ = new_preheader,
776 vector_header_ = vector_preheader_->GetSingleSuccessor();
777 vector_body_ = vector_header_->GetSuccessors()[1];
Aart Bik14a68b42017-06-08 14:06:58 -0700778 HPhi* phi = new (global_allocator_) HPhi(global_allocator_,
779 kNoRegNumber,
780 0,
781 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700782 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800783 // for (i = lo; i < hi; i += step)
784 // <loop-body>
Aart Bik14a68b42017-06-08 14:06:58 -0700785 HInstruction* cond = new (global_allocator_) HAboveOrEqual(phi, hi);
786 vector_header_->AddPhi(phi);
Aart Bikf8f5a162017-02-06 15:35:29 -0800787 vector_header_->AddInstruction(cond);
788 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bik14a68b42017-06-08 14:06:58 -0700789 vector_index_ = phi;
790 for (uint32_t u = 0; u < unroll; u++) {
791 // Clear map, leaving loop invariants setup during unrolling.
792 if (u == 0) {
793 vector_map_->clear();
794 } else {
795 for (auto i = vector_map_->begin(); i != vector_map_->end(); ) {
796 if (i->second->IsVecReplicateScalar()) {
797 DCHECK(node->loop_info->IsDefinedOutOfTheLoop(i->first));
798 ++i;
799 } else {
800 i = vector_map_->erase(i);
801 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800802 }
803 }
Aart Bik14a68b42017-06-08 14:06:58 -0700804 // Generate instruction map.
805 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
806 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
807 DCHECK(vectorized_def);
808 }
809 // Generate body from the instruction map, but in original program order.
810 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
811 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
812 auto i = vector_map_->find(it.Current());
813 if (i != vector_map_->end() && !i->second->IsInBlock()) {
814 Insert(vector_body_, i->second);
815 // Deal with instructions that need an environment, such as the scalar intrinsics.
816 if (i->second->NeedsEnvironment()) {
817 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
818 }
819 }
820 }
821 vector_index_ = new (global_allocator_) HAdd(induc_type, vector_index_, step);
822 Insert(vector_body_, vector_index_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800823 }
Aart Bik14a68b42017-06-08 14:06:58 -0700824 // Finalize phi for the loop index.
825 phi->AddInput(lo);
826 phi->AddInput(vector_index_);
827 vector_index_ = phi;
Aart Bikf8f5a162017-02-06 15:35:29 -0800828}
829
830// TODO: accept reductions at left-hand-side, mixed-type store idioms, etc.
831bool HLoopOptimization::VectorizeDef(LoopNode* node,
832 HInstruction* instruction,
833 bool generate_code) {
834 // Accept a left-hand-side array base[index] for
835 // (1) supported vector type,
836 // (2) loop-invariant base,
837 // (3) unit stride index,
838 // (4) vectorizable right-hand-side value.
839 uint64_t restrictions = kNone;
840 if (instruction->IsArraySet()) {
841 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
842 HInstruction* base = instruction->InputAt(0);
843 HInstruction* index = instruction->InputAt(1);
844 HInstruction* value = instruction->InputAt(2);
845 HInstruction* offset = nullptr;
846 if (TrySetVectorType(type, &restrictions) &&
847 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -0700848 induction_range_.IsUnitStride(instruction, index, graph_, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800849 VectorizeUse(node, value, generate_code, type, restrictions)) {
850 if (generate_code) {
851 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -0700852 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -0800853 } else {
854 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
855 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800856 return true;
857 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800858 return false;
859 }
860 // Branch back okay.
861 if (instruction->IsGoto()) {
862 return true;
863 }
864 // Otherwise accept only expressions with no effects outside the immediate loop-body.
865 // Note that actual uses are inspected during right-hand-side tree traversal.
866 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
867}
868
Aart Bik304c8a52017-05-23 11:01:13 -0700869// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -0800870bool HLoopOptimization::VectorizeUse(LoopNode* node,
871 HInstruction* instruction,
872 bool generate_code,
873 Primitive::Type type,
874 uint64_t restrictions) {
875 // Accept anything for which code has already been generated.
876 if (generate_code) {
877 if (vector_map_->find(instruction) != vector_map_->end()) {
878 return true;
879 }
880 }
881 // Continue the right-hand-side tree traversal, passing in proper
882 // types and vector restrictions along the way. During code generation,
883 // all new nodes are drawn from the global allocator.
884 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
885 // Accept invariant use, using scalar expansion.
886 if (generate_code) {
887 GenerateVecInv(instruction, type);
888 }
889 return true;
890 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +0200891 // Deal with vector restrictions.
892 if (instruction->AsArrayGet()->IsStringCharAt() &&
893 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
894 return false;
895 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800896 // Accept a right-hand-side array base[index] for
897 // (1) exact matching vector type,
898 // (2) loop-invariant base,
899 // (3) unit stride index,
900 // (4) vectorizable right-hand-side value.
901 HInstruction* base = instruction->InputAt(0);
902 HInstruction* index = instruction->InputAt(1);
903 HInstruction* offset = nullptr;
904 if (type == instruction->GetType() &&
905 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bik37dc4df2017-06-28 14:08:00 -0700906 induction_range_.IsUnitStride(instruction, index, graph_, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800907 if (generate_code) {
908 GenerateVecSub(index, offset);
Aart Bik14a68b42017-06-08 14:06:58 -0700909 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, offset, type);
Aart Bikf8f5a162017-02-06 15:35:29 -0800910 } else {
911 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
912 }
913 return true;
914 }
915 } else if (instruction->IsTypeConversion()) {
916 // Accept particular type conversions.
917 HTypeConversion* conversion = instruction->AsTypeConversion();
918 HInstruction* opa = conversion->InputAt(0);
919 Primitive::Type from = conversion->GetInputType();
920 Primitive::Type to = conversion->GetResultType();
921 if ((to == Primitive::kPrimByte ||
922 to == Primitive::kPrimChar ||
923 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
924 // Accept a "narrowing" type conversion from a "wider" computation for
925 // (1) conversion into final required type,
926 // (2) vectorizable operand,
927 // (3) "wider" operations cannot bring in higher order bits.
928 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
929 if (generate_code) {
930 if (vector_mode_ == kVector) {
931 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
932 } else {
933 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
934 }
935 }
936 return true;
937 }
938 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
939 DCHECK_EQ(to, type);
940 // Accept int to float conversion for
941 // (1) supported int,
942 // (2) vectorizable operand.
943 if (TrySetVectorType(from, &restrictions) &&
944 VectorizeUse(node, opa, generate_code, from, restrictions)) {
945 if (generate_code) {
946 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
947 }
948 return true;
949 }
950 }
951 return false;
952 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
953 // Accept unary operator for vectorizable operand.
954 HInstruction* opa = instruction->InputAt(0);
955 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
956 if (generate_code) {
957 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
958 }
959 return true;
960 }
961 } else if (instruction->IsAdd() || instruction->IsSub() ||
962 instruction->IsMul() || instruction->IsDiv() ||
963 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
964 // Deal with vector restrictions.
965 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
966 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
967 return false;
968 }
969 // Accept binary operator for vectorizable operands.
970 HInstruction* opa = instruction->InputAt(0);
971 HInstruction* opb = instruction->InputAt(1);
972 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
973 VectorizeUse(node, opb, generate_code, type, restrictions)) {
974 if (generate_code) {
975 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
976 }
977 return true;
978 }
979 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700980 // Recognize vectorization idioms.
981 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
982 return true;
983 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800984 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -0700985 HInstruction* opa = instruction->InputAt(0);
986 HInstruction* opb = instruction->InputAt(1);
987 HInstruction* r = opa;
988 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800989 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
990 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
991 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -0700992 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
993 // Shifts right need extra care to account for higher order bits.
994 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
995 if (instruction->IsShr() &&
996 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
997 return false; // reject, unless all operands are sign-extension narrower
998 } else if (instruction->IsUShr() &&
999 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
1000 return false; // reject, unless all operands are zero-extension narrower
1001 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001002 }
1003 // Accept shift operator for vectorizable/invariant operands.
1004 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -07001005 DCHECK(r != nullptr);
1006 if (generate_code && vector_mode_ != kVector) { // de-idiom
1007 r = opa;
1008 }
Aart Bik50e20d52017-05-05 14:07:29 -07001009 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -07001010 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -07001011 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -07001012 // Restrict shift distance to packed data type width.
1013 int64_t max_distance = Primitive::ComponentSize(type) * 8;
1014 if (0 <= distance && distance < max_distance) {
1015 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001016 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -07001017 }
1018 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -08001019 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001020 }
1021 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001022 // Accept particular intrinsics.
1023 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
1024 switch (invoke->GetIntrinsic()) {
1025 case Intrinsics::kMathAbsInt:
1026 case Intrinsics::kMathAbsLong:
1027 case Intrinsics::kMathAbsFloat:
1028 case Intrinsics::kMathAbsDouble: {
1029 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -07001030 HInstruction* opa = instruction->InputAt(0);
1031 HInstruction* r = opa;
1032 bool is_unsigned = false;
1033 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001034 return false;
Aart Bik304c8a52017-05-23 11:01:13 -07001035 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1036 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
1037 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -07001038 }
1039 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -07001040 DCHECK(r != nullptr);
1041 if (generate_code && vector_mode_ != kVector) { // de-idiom
1042 r = opa;
1043 }
1044 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -07001045 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001046 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -07001047 }
1048 return true;
1049 }
1050 return false;
1051 }
Aart Bikc8e93c72017-05-10 10:49:22 -07001052 case Intrinsics::kMathMinIntInt:
1053 case Intrinsics::kMathMinLongLong:
1054 case Intrinsics::kMathMinFloatFloat:
1055 case Intrinsics::kMathMinDoubleDouble:
1056 case Intrinsics::kMathMaxIntInt:
1057 case Intrinsics::kMathMaxLongLong:
1058 case Intrinsics::kMathMaxFloatFloat:
1059 case Intrinsics::kMathMaxDoubleDouble: {
1060 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +00001061 HInstruction* opa = instruction->InputAt(0);
1062 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -07001063 HInstruction* r = opa;
1064 HInstruction* s = opb;
1065 bool is_unsigned = false;
1066 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
1067 return false;
1068 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
1069 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
1070 return false; // reject, unless all operands are same-extension narrower
1071 }
1072 // Accept MIN/MAX(x, y) for vectorizable operands.
1073 DCHECK(r != nullptr && s != nullptr);
1074 if (generate_code && vector_mode_ != kVector) { // de-idiom
1075 r = opa;
1076 s = opb;
1077 }
1078 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1079 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001080 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001081 GenerateVecOp(
1082 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001083 }
1084 return true;
1085 }
1086 return false;
1087 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001088 default:
1089 return false;
1090 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001091 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001092 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001093}
1094
Aart Bikf8f5a162017-02-06 15:35:29 -08001095bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
1096 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1097 switch (compiler_driver_->GetInstructionSet()) {
1098 case kArm:
1099 case kThumb2:
1100 return false;
1101 case kArm64:
1102 // Allow vectorization for all ARM devices, because Android assumes that
Artem Serovd4bccf12017-04-03 18:47:32 +01001103 // ARMv8 AArch64 always supports advanced SIMD.
Aart Bikf8f5a162017-02-06 15:35:29 -08001104 switch (type) {
1105 case Primitive::kPrimBoolean:
1106 case Primitive::kPrimByte:
Aart Bik304c8a52017-05-23 11:01:13 -07001107 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001108 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -08001109 case Primitive::kPrimChar:
1110 case Primitive::kPrimShort:
Aart Bik304c8a52017-05-23 11:01:13 -07001111 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001112 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -08001113 case Primitive::kPrimInt:
1114 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001115 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001116 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001117 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001118 return TrySetVectorLength(2);
1119 case Primitive::kPrimFloat:
Artem Serovd4bccf12017-04-03 18:47:32 +01001120 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001121 case Primitive::kPrimDouble:
Aart Bikf8f5a162017-02-06 15:35:29 -08001122 return TrySetVectorLength(2);
1123 default:
1124 return false;
1125 }
1126 case kX86:
1127 case kX86_64:
1128 // Allow vectorization for SSE4-enabled X86 devices only (128-bit vectors).
1129 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1130 switch (type) {
1131 case Primitive::kPrimBoolean:
1132 case Primitive::kPrimByte:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001133 *restrictions |= kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001134 return TrySetVectorLength(16);
1135 case Primitive::kPrimChar:
1136 case Primitive::kPrimShort:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001137 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001138 return TrySetVectorLength(8);
1139 case Primitive::kPrimInt:
1140 *restrictions |= kNoDiv;
1141 return TrySetVectorLength(4);
1142 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001143 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001144 return TrySetVectorLength(2);
1145 case Primitive::kPrimFloat:
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(4);
1148 case Primitive::kPrimDouble:
Aart Bikc8e93c72017-05-10 10:49:22 -07001149 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001150 return TrySetVectorLength(2);
1151 default:
1152 break;
1153 } // switch type
1154 }
1155 return false;
1156 case kMips:
Aart Bikf8f5a162017-02-06 15:35:29 -08001157 // TODO: implement MIPS SIMD.
1158 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001159 case kMips64:
1160 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1161 switch (type) {
1162 case Primitive::kPrimBoolean:
1163 case Primitive::kPrimByte:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001164 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001165 return TrySetVectorLength(16);
1166 case Primitive::kPrimChar:
1167 case Primitive::kPrimShort:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001168 *restrictions |= kNoDiv | kNoStringCharAt;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001169 return TrySetVectorLength(8);
1170 case Primitive::kPrimInt:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001171 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001172 return TrySetVectorLength(4);
1173 case Primitive::kPrimLong:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001174 *restrictions |= kNoDiv;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001175 return TrySetVectorLength(2);
1176 case Primitive::kPrimFloat:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001177 *restrictions |= kNoMinMax; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001178 return TrySetVectorLength(4);
1179 case Primitive::kPrimDouble:
Goran Jakovljevic8fea1e12017-06-06 13:28:42 +02001180 *restrictions |= kNoMinMax; // min/max(x, NaN)
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001181 return TrySetVectorLength(2);
1182 default:
1183 break;
1184 } // switch type
1185 }
1186 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001187 default:
1188 return false;
1189 } // switch instruction set
1190}
1191
1192bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1193 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1194 // First time set?
1195 if (vector_length_ == 0) {
1196 vector_length_ = length;
1197 }
1198 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1199 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1200 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1201 return vector_length_ == length;
1202}
1203
1204void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
1205 if (vector_map_->find(org) == vector_map_->end()) {
1206 // In scalar code, just use a self pass-through for scalar invariants
1207 // (viz. expression remains itself).
1208 if (vector_mode_ == kSequential) {
1209 vector_map_->Put(org, org);
1210 return;
1211 }
1212 // In vector code, explicit scalar expansion is needed.
1213 HInstruction* vector = new (global_allocator_) HVecReplicateScalar(
1214 global_allocator_, org, type, vector_length_);
1215 vector_map_->Put(org, Insert(vector_preheader_, vector));
1216 }
1217}
1218
1219void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1220 if (vector_map_->find(org) == vector_map_->end()) {
Aart Bik14a68b42017-06-08 14:06:58 -07001221 HInstruction* subscript = vector_index_;
Aart Bik37dc4df2017-06-28 14:08:00 -07001222 int64_t value = 0;
1223 if (!IsInt64AndGet(offset, &value) || value != 0) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001224 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
1225 if (org->IsPhi()) {
1226 Insert(vector_body_, subscript); // lacks layout placeholder
1227 }
1228 }
1229 vector_map_->Put(org, subscript);
1230 }
1231}
1232
1233void HLoopOptimization::GenerateVecMem(HInstruction* org,
1234 HInstruction* opa,
1235 HInstruction* opb,
Aart Bik14a68b42017-06-08 14:06:58 -07001236 HInstruction* offset,
Aart Bikf8f5a162017-02-06 15:35:29 -08001237 Primitive::Type type) {
1238 HInstruction* vector = nullptr;
1239 if (vector_mode_ == kVector) {
1240 // Vector store or load.
Aart Bik14a68b42017-06-08 14:06:58 -07001241 HInstruction* base = org->InputAt(0);
Aart Bikf8f5a162017-02-06 15:35:29 -08001242 if (opb != nullptr) {
1243 vector = new (global_allocator_) HVecStore(
Aart Bik14a68b42017-06-08 14:06:58 -07001244 global_allocator_, base, opa, opb, type, vector_length_);
Aart Bikf8f5a162017-02-06 15:35:29 -08001245 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001246 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001247 vector = new (global_allocator_) HVecLoad(
Aart Bik14a68b42017-06-08 14:06:58 -07001248 global_allocator_, base, opa, type, vector_length_, is_string_char_at);
1249 }
1250 // Known dynamically enforced alignment?
1251 // TODO: detect offset + constant differences.
1252 // TODO: long run, static alignment analysis?
1253 if (vector_peeling_candidate_ != nullptr &&
1254 vector_peeling_candidate_->base == base &&
1255 vector_peeling_candidate_->offset == offset) {
1256 vector->AsVecMemoryOperation()->SetAlignment(Alignment(kAlignedBase, 0));
Aart Bikf8f5a162017-02-06 15:35:29 -08001257 }
1258 } else {
1259 // Scalar store or load.
1260 DCHECK(vector_mode_ == kSequential);
1261 if (opb != nullptr) {
1262 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1263 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001264 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1265 vector = new (global_allocator_) HArrayGet(
1266 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001267 }
1268 }
1269 vector_map_->Put(org, vector);
1270}
1271
1272#define GENERATE_VEC(x, y) \
1273 if (vector_mode_ == kVector) { \
1274 vector = (x); \
1275 } else { \
1276 DCHECK(vector_mode_ == kSequential); \
1277 vector = (y); \
1278 } \
1279 break;
1280
1281void HLoopOptimization::GenerateVecOp(HInstruction* org,
1282 HInstruction* opa,
1283 HInstruction* opb,
Aart Bik304c8a52017-05-23 11:01:13 -07001284 Primitive::Type type,
1285 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001286 if (vector_mode_ == kSequential) {
Aart Bik304c8a52017-05-23 11:01:13 -07001287 // Non-converting scalar code follows implicit integral promotion.
1288 if (!org->IsTypeConversion() && (type == Primitive::kPrimBoolean ||
1289 type == Primitive::kPrimByte ||
1290 type == Primitive::kPrimChar ||
1291 type == Primitive::kPrimShort)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001292 type = Primitive::kPrimInt;
1293 }
1294 }
1295 HInstruction* vector = nullptr;
1296 switch (org->GetKind()) {
1297 case HInstruction::kNeg:
1298 DCHECK(opb == nullptr);
1299 GENERATE_VEC(
1300 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
1301 new (global_allocator_) HNeg(type, opa));
1302 case HInstruction::kNot:
1303 DCHECK(opb == nullptr);
1304 GENERATE_VEC(
1305 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1306 new (global_allocator_) HNot(type, opa));
1307 case HInstruction::kBooleanNot:
1308 DCHECK(opb == nullptr);
1309 GENERATE_VEC(
1310 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1311 new (global_allocator_) HBooleanNot(opa));
1312 case HInstruction::kTypeConversion:
1313 DCHECK(opb == nullptr);
1314 GENERATE_VEC(
1315 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
1316 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
1317 case HInstruction::kAdd:
1318 GENERATE_VEC(
1319 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
1320 new (global_allocator_) HAdd(type, opa, opb));
1321 case HInstruction::kSub:
1322 GENERATE_VEC(
1323 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
1324 new (global_allocator_) HSub(type, opa, opb));
1325 case HInstruction::kMul:
1326 GENERATE_VEC(
1327 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
1328 new (global_allocator_) HMul(type, opa, opb));
1329 case HInstruction::kDiv:
1330 GENERATE_VEC(
1331 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
1332 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
1333 case HInstruction::kAnd:
1334 GENERATE_VEC(
1335 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
1336 new (global_allocator_) HAnd(type, opa, opb));
1337 case HInstruction::kOr:
1338 GENERATE_VEC(
1339 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
1340 new (global_allocator_) HOr(type, opa, opb));
1341 case HInstruction::kXor:
1342 GENERATE_VEC(
1343 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
1344 new (global_allocator_) HXor(type, opa, opb));
1345 case HInstruction::kShl:
1346 GENERATE_VEC(
1347 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
1348 new (global_allocator_) HShl(type, opa, opb));
1349 case HInstruction::kShr:
1350 GENERATE_VEC(
1351 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
1352 new (global_allocator_) HShr(type, opa, opb));
1353 case HInstruction::kUShr:
1354 GENERATE_VEC(
1355 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
1356 new (global_allocator_) HUShr(type, opa, opb));
1357 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001358 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1359 if (vector_mode_ == kVector) {
1360 switch (invoke->GetIntrinsic()) {
1361 case Intrinsics::kMathAbsInt:
1362 case Intrinsics::kMathAbsLong:
1363 case Intrinsics::kMathAbsFloat:
1364 case Intrinsics::kMathAbsDouble:
1365 DCHECK(opb == nullptr);
1366 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1367 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001368 case Intrinsics::kMathMinIntInt:
1369 case Intrinsics::kMathMinLongLong:
1370 case Intrinsics::kMathMinFloatFloat:
1371 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001372 vector = new (global_allocator_)
1373 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1374 break;
1375 }
1376 case Intrinsics::kMathMaxIntInt:
1377 case Intrinsics::kMathMaxLongLong:
1378 case Intrinsics::kMathMaxFloatFloat:
1379 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001380 vector = new (global_allocator_)
1381 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1382 break;
1383 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001384 default:
1385 LOG(FATAL) << "Unsupported SIMD intrinsic";
1386 UNREACHABLE();
1387 } // switch invoke
1388 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001389 // In scalar code, simply clone the method invoke, and replace its operands with the
1390 // corresponding new scalar instructions in the loop. The instruction will get an
1391 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001392 DCHECK(vector_mode_ == kSequential);
Aart Bik6e92fb32017-06-05 14:05:09 -07001393 size_t num_args = invoke->GetNumberOfArguments();
Aart Bik6daebeb2017-04-03 14:35:41 -07001394 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1395 global_allocator_,
Aart Bik6e92fb32017-06-05 14:05:09 -07001396 num_args,
Aart Bik6daebeb2017-04-03 14:35:41 -07001397 invoke->GetType(),
1398 invoke->GetDexPc(),
1399 invoke->GetDexMethodIndex(),
1400 invoke->GetResolvedMethod(),
1401 invoke->GetDispatchInfo(),
1402 invoke->GetInvokeType(),
1403 invoke->GetTargetMethod(),
1404 invoke->GetClinitCheckRequirement());
1405 HInputsRef inputs = invoke->GetInputs();
Aart Bik6e92fb32017-06-05 14:05:09 -07001406 size_t num_inputs = inputs.size();
1407 DCHECK_LE(num_args, num_inputs);
1408 DCHECK_EQ(num_inputs, new_invoke->GetInputs().size()); // both invokes agree
1409 for (size_t index = 0; index < num_inputs; ++index) {
1410 HInstruction* new_input = index < num_args
1411 ? vector_map_->Get(inputs[index])
1412 : inputs[index]; // beyond arguments: just pass through
1413 new_invoke->SetArgumentAt(index, new_input);
Aart Bik6daebeb2017-04-03 14:35:41 -07001414 }
Aart Bik98990262017-04-10 13:15:57 -07001415 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1416 kNeedsEnvironmentOrCache,
1417 kNoSideEffects,
1418 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001419 vector = new_invoke;
1420 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001421 break;
1422 }
1423 default:
1424 break;
1425 } // switch
1426 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1427 vector_map_->Put(org, vector);
1428}
1429
1430#undef GENERATE_VEC
1431
1432//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001433// Vectorization idioms.
1434//
1435
1436// Method recognizes the following idioms:
1437// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1438// regular halving add (a + b) >> 1 for unsigned/signed operands a, b
1439// Provided that the operands are promoted to a wider form to do the arithmetic and
1440// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1441// implementation that operates directly in narrower form (plus one extra bit).
1442// TODO: current version recognizes implicit byte/short/char widening only;
1443// explicit widening from int to long could be added later.
1444bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1445 HInstruction* instruction,
1446 bool generate_code,
1447 Primitive::Type type,
1448 uint64_t restrictions) {
1449 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001450 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001451 // on the narrow precision computed by the idiom).
Aart Bik5f805002017-05-16 16:42:41 -07001452 int64_t distance = 0;
Aart Bikf3e61ee2017-04-12 17:09:20 -07001453 if ((instruction->IsShr() ||
1454 instruction->IsUShr()) &&
Aart Bik5f805002017-05-16 16:42:41 -07001455 IsInt64AndGet(instruction->InputAt(1), /*out*/ &distance) && distance == 1) {
1456 // Test for (a + b + c) >> 1 for optional constant c.
1457 HInstruction* a = nullptr;
1458 HInstruction* b = nullptr;
1459 int64_t c = 0;
1460 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001461 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001462 // Accept c == 1 (rounded) or c == 0 (not rounded).
1463 bool is_rounded = false;
1464 if (c == 1) {
1465 is_rounded = true;
1466 } else if (c != 0) {
1467 return false;
1468 }
1469 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001470 HInstruction* r = nullptr;
1471 HInstruction* s = nullptr;
1472 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001473 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001474 return false;
1475 }
1476 // Deal with vector restrictions.
1477 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1478 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1479 return false;
1480 }
1481 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1482 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
1483 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001484 if (generate_code && vector_mode_ != kVector) { // de-idiom
1485 r = instruction->InputAt(0);
1486 s = instruction->InputAt(1);
1487 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001488 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1489 VectorizeUse(node, s, generate_code, type, restrictions)) {
1490 if (generate_code) {
1491 if (vector_mode_ == kVector) {
1492 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1493 global_allocator_,
1494 vector_map_->Get(r),
1495 vector_map_->Get(s),
1496 type,
1497 vector_length_,
1498 is_unsigned,
1499 is_rounded));
1500 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001501 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001502 }
1503 }
1504 return true;
1505 }
1506 }
1507 }
1508 return false;
1509}
1510
1511//
Aart Bik14a68b42017-06-08 14:06:58 -07001512// Vectorization heuristics.
1513//
1514
1515bool HLoopOptimization::IsVectorizationProfitable(int64_t trip_count) {
1516 // Current heuristic: non-empty body with sufficient number
1517 // of iterations (if known).
1518 // TODO: refine by looking at e.g. operation count, alignment, etc.
1519 if (vector_length_ == 0) {
1520 return false; // nothing found
1521 } else if (0 < trip_count && trip_count < vector_length_) {
1522 return false; // insufficient iterations
1523 }
1524 return true;
1525}
1526
1527void HLoopOptimization::SetPeelingCandidate(int64_t trip_count ATTRIBUTE_UNUSED) {
1528 // Current heuristic: none.
1529 // TODO: implement
1530}
1531
1532uint32_t HLoopOptimization::GetUnrollingFactor(HBasicBlock* block, int64_t trip_count) {
1533 // Current heuristic: unroll by 2 on ARM64/X86 for large known trip
1534 // counts and small loop bodies.
1535 // TODO: refine with operation count, remaining iterations, etc.
1536 // Artem had some really cool ideas for this already.
1537 switch (compiler_driver_->GetInstructionSet()) {
1538 case kArm64:
1539 case kX86:
1540 case kX86_64: {
1541 size_t num_instructions = block->GetInstructions().CountSize();
1542 if (num_instructions <= 10 && trip_count >= 4 * vector_length_) {
1543 return 2;
1544 }
1545 return 1;
1546 }
1547 default:
1548 return 1;
1549 }
1550}
1551
1552//
Aart Bikf8f5a162017-02-06 15:35:29 -08001553// Helpers.
1554//
1555
1556bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
Nicolas Geoffrayf57c1ae2017-06-28 17:40:18 +01001557 // Special case Phis that have equivalent in a debuggable setup. Our graph checker isn't
1558 // smart enough to follow strongly connected components (and it's probably not worth
1559 // it to make it so). See b/33775412.
1560 if (graph_->IsDebuggable() && phi->HasEquivalentPhi()) {
1561 return false;
1562 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001563 DCHECK(iset_->empty());
Aart Bikcc42be02016-10-20 16:14:16 -07001564 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1565 if (set != nullptr) {
1566 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001567 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001568 // each instruction is removable and, when restrict uses are requested, other than for phi,
1569 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001570 if (!i->IsInBlock()) {
1571 continue;
1572 } else if (!i->IsRemovable()) {
1573 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001574 } else if (i != phi && restrict_uses) {
Aart Bikcc42be02016-10-20 16:14:16 -07001575 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1576 if (set->find(use.GetUser()) == set->end()) {
1577 return false;
1578 }
1579 }
1580 }
Aart Bike3dedc52016-11-02 17:50:27 -07001581 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001582 }
Aart Bikcc42be02016-10-20 16:14:16 -07001583 return true;
1584 }
1585 return false;
1586}
1587
1588// Find: phi: Phi(init, addsub)
1589// s: SuspendCheck
1590// c: Condition(phi, bound)
1591// i: If(c)
1592// TODO: Find a less pattern matching approach?
Aart Bikf8f5a162017-02-06 15:35:29 -08001593bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block) {
Aart Bikcc42be02016-10-20 16:14:16 -07001594 DCHECK(iset_->empty());
1595 HInstruction* phi = block->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -08001596 if (phi != nullptr &&
1597 phi->GetNext() == nullptr &&
1598 TrySetPhiInduction(phi->AsPhi(), /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001599 HInstruction* s = block->GetFirstInstruction();
1600 if (s != nullptr && s->IsSuspendCheck()) {
1601 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07001602 if (c != nullptr &&
1603 c->IsCondition() &&
1604 c->GetUses().HasExactlyOneElement() && // only used for termination
1605 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07001606 HInstruction* i = c->GetNext();
1607 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1608 iset_->insert(c);
1609 iset_->insert(s);
1610 return true;
1611 }
1612 }
1613 }
1614 }
1615 return false;
1616}
1617
1618bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001619 if (!block->GetPhis().IsEmpty()) {
1620 return false;
1621 }
1622 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1623 HInstruction* instruction = it.Current();
1624 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1625 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001626 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001627 }
1628 return true;
1629}
1630
1631bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1632 HInstruction* instruction) {
1633 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1634 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1635 return true;
1636 }
Aart Bikcc42be02016-10-20 16:14:16 -07001637 }
1638 return false;
1639}
1640
Aart Bik482095d2016-10-10 15:39:10 -07001641bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001642 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001643 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001644 /*out*/ int32_t* use_count) {
1645 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1646 HInstruction* user = use.GetUser();
1647 if (iset_->find(user) == iset_->end()) { // not excluded?
1648 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001649 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001650 // If collect_loop_uses is set, simply keep adding those uses to the set.
1651 // Otherwise, reject uses inside the loop that were not already in the set.
1652 if (collect_loop_uses) {
1653 iset_->insert(user);
1654 continue;
1655 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001656 return false;
1657 }
1658 ++*use_count;
1659 }
1660 }
1661 return true;
1662}
1663
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001664bool HLoopOptimization::TryReplaceWithLastValue(HLoopInformation* loop_info,
1665 HInstruction* instruction,
1666 HBasicBlock* block) {
1667 // Try to replace outside uses with the last value.
Aart Bik807868e2016-11-03 17:51:43 -07001668 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001669 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
1670 const HUseList<HInstruction*>& uses = instruction->GetUses();
1671 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1672 HInstruction* user = it->GetUser();
1673 size_t index = it->GetIndex();
1674 ++it; // increment before replacing
1675 if (iset_->find(user) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001676 if (kIsDebugBuild) {
1677 // We have checked earlier in 'IsOnlyUsedAfterLoop' that the use is after the loop.
1678 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
1679 CHECK(other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info));
1680 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001681 user->ReplaceInput(replacement, index);
1682 induction_range_.Replace(user, instruction, replacement); // update induction
1683 }
1684 }
1685 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1686 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1687 HEnvironment* user = it->GetUser();
1688 size_t index = it->GetIndex();
1689 ++it; // increment before replacing
1690 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001691 // Only update environment uses after the loop.
Aart Bik14a68b42017-06-08 14:06:58 -07001692 HLoopInformation* other_loop_info = user->GetHolder()->GetBlock()->GetLoopInformation();
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001693 if (other_loop_info == nullptr || !other_loop_info->IsIn(*loop_info)) {
1694 user->RemoveAsUserOfInput(index);
1695 user->SetRawEnvAt(index, replacement);
1696 replacement->AddEnvUseAt(user, index);
1697 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001698 }
1699 }
1700 induction_simplication_count_++;
Aart Bik807868e2016-11-03 17:51:43 -07001701 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001702 }
Aart Bik807868e2016-11-03 17:51:43 -07001703 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001704}
1705
Aart Bikf8f5a162017-02-06 15:35:29 -08001706bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1707 HInstruction* instruction,
1708 HBasicBlock* block,
1709 bool collect_loop_uses) {
1710 // Assigning the last value is always successful if there are no uses.
1711 // Otherwise, it succeeds in a no early-exit loop by generating the
1712 // proper last value assignment.
1713 int32_t use_count = 0;
1714 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
1715 (use_count == 0 ||
Nicolas Geoffray1a0a5192017-06-22 11:56:01 +01001716 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(loop_info, instruction, block)));
Aart Bikf8f5a162017-02-06 15:35:29 -08001717}
1718
Aart Bik6b69e0a2017-01-11 10:20:43 -08001719void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
1720 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
1721 HInstruction* instruction = i.Current();
1722 if (instruction->IsDeadAndRemovable()) {
1723 simplified_ = true;
1724 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
1725 }
1726 }
1727}
1728
Aart Bik14a68b42017-06-08 14:06:58 -07001729bool HLoopOptimization::CanRemoveCycle() {
1730 for (HInstruction* i : *iset_) {
1731 // We can never remove instructions that have environment
1732 // uses when we compile 'debuggable'.
1733 if (i->HasEnvironmentUses() && graph_->IsDebuggable()) {
1734 return false;
1735 }
1736 // A deoptimization should never have an environment input removed.
1737 for (const HUseListNode<HEnvironment*>& use : i->GetEnvUses()) {
1738 if (use.GetUser()->GetHolder()->IsDeoptimize()) {
1739 return false;
1740 }
1741 }
1742 }
1743 return true;
1744}
1745
Aart Bik281c6812016-08-26 11:31:48 -07001746} // namespace art