blob: ae102f7fc5b7472f4bf9b5293ad82e73f7120dae [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 Bik9abf8942016-10-14 09:49:42 -070034// Remove the instruction from the graph. A bit more elaborate than the usual
35// instruction removal, since there may be a cycle in the use structure.
Aart Bik281c6812016-08-26 11:31:48 -070036static void RemoveFromCycle(HInstruction* instruction) {
Aart Bik281c6812016-08-26 11:31:48 -070037 instruction->RemoveAsUserOfAllInputs();
38 instruction->RemoveEnvironmentUsers();
39 instruction->GetBlock()->RemoveInstructionOrPhi(instruction, /*ensure_safety=*/ false);
40}
41
Aart Bik807868e2016-11-03 17:51:43 -070042// Detect a goto block and sets succ to the single successor.
Aart Bike3dedc52016-11-02 17:50:27 -070043static bool IsGotoBlock(HBasicBlock* block, /*out*/ HBasicBlock** succ) {
44 if (block->GetPredecessors().size() == 1 &&
45 block->GetSuccessors().size() == 1 &&
46 block->IsSingleGoto()) {
47 *succ = block->GetSingleSuccessor();
48 return true;
49 }
50 return false;
51}
52
Aart Bik807868e2016-11-03 17:51:43 -070053// Detect an early exit loop.
54static bool IsEarlyExit(HLoopInformation* loop_info) {
55 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
56 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
57 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
58 if (!loop_info->Contains(*successor)) {
59 return true;
60 }
61 }
62 }
63 return false;
64}
65
Aart Bikf3e61ee2017-04-12 17:09:20 -070066// Detect a sign extension from the given type. Returns the promoted operand on success.
67static bool IsSignExtensionAndGet(HInstruction* instruction,
68 Primitive::Type type,
69 /*out*/ HInstruction** operand) {
70 // Accept any already wider constant that would be handled properly by sign
71 // extension when represented in the *width* of the given narrower data type
72 // (the fact that char normally zero extends does not matter here).
73 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -070074 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -070075 switch (type) {
76 case Primitive::kPrimByte:
77 if (std::numeric_limits<int8_t>::min() <= value &&
78 std::numeric_limits<int8_t>::max() >= value) {
79 *operand = instruction;
80 return true;
81 }
82 return false;
83 case Primitive::kPrimChar:
84 case Primitive::kPrimShort:
85 if (std::numeric_limits<int16_t>::min() <= value &&
86 std::numeric_limits<int16_t>::max() <= value) {
87 *operand = instruction;
88 return true;
89 }
90 return false;
91 default:
92 return false;
93 }
94 }
95 // An implicit widening conversion of a signed integer to an integral type sign-extends
96 // the two's-complement representation of the integer value to fill the wider format.
97 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
98 instruction->IsStaticFieldGet() ||
99 instruction->IsInstanceFieldGet())) {
100 switch (type) {
101 case Primitive::kPrimByte:
102 case Primitive::kPrimShort:
103 *operand = instruction;
104 return true;
105 default:
106 return false;
107 }
108 }
109 // TODO: perhaps explicit conversions later too?
110 // (this may return something different from instruction)
111 return false;
112}
113
114// Detect a zero extension from the given type. Returns the promoted operand on success.
115static bool IsZeroExtensionAndGet(HInstruction* instruction,
116 Primitive::Type type,
117 /*out*/ HInstruction** operand) {
118 // Accept any already wider constant that would be handled properly by zero
119 // extension when represented in the *width* of the given narrower data type
120 // (the fact that byte/short normally sign extend does not matter here).
121 int64_t value = 0;
Aart Bik50e20d52017-05-05 14:07:29 -0700122 if (IsInt64AndGet(instruction, /*out*/ &value)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700123 switch (type) {
124 case Primitive::kPrimByte:
125 if (std::numeric_limits<uint8_t>::min() <= value &&
126 std::numeric_limits<uint8_t>::max() >= value) {
127 *operand = instruction;
128 return true;
129 }
130 return false;
131 case Primitive::kPrimChar:
132 case Primitive::kPrimShort:
133 if (std::numeric_limits<uint16_t>::min() <= value &&
134 std::numeric_limits<uint16_t>::max() <= value) {
135 *operand = instruction;
136 return true;
137 }
138 return false;
139 default:
140 return false;
141 }
142 }
143 // An implicit widening conversion of a char to an integral type zero-extends
144 // the representation of the char value to fill the wider format.
145 if (instruction->GetType() == type && (instruction->IsArrayGet() ||
146 instruction->IsStaticFieldGet() ||
147 instruction->IsInstanceFieldGet())) {
148 if (type == Primitive::kPrimChar) {
149 *operand = instruction;
150 return true;
151 }
152 }
153 // A sign (or zero) extension followed by an explicit removal of just the
154 // higher sign bits is equivalent to a zero extension of the underlying operand.
155 if (instruction->IsAnd()) {
156 int64_t mask = 0;
157 HInstruction* a = instruction->InputAt(0);
158 HInstruction* b = instruction->InputAt(1);
159 // In (a & b) find (mask & b) or (a & mask) with sign or zero extension on the non-mask.
160 if ((IsInt64AndGet(a, /*out*/ &mask) && (IsSignExtensionAndGet(b, type, /*out*/ operand) ||
161 IsZeroExtensionAndGet(b, type, /*out*/ operand))) ||
162 (IsInt64AndGet(b, /*out*/ &mask) && (IsSignExtensionAndGet(a, type, /*out*/ operand) ||
163 IsZeroExtensionAndGet(a, type, /*out*/ operand)))) {
164 switch ((*operand)->GetType()) {
165 case Primitive::kPrimByte: return mask == std::numeric_limits<uint8_t>::max();
166 case Primitive::kPrimChar:
167 case Primitive::kPrimShort: return mask == std::numeric_limits<uint16_t>::max();
168 default: return false;
169 }
170 }
171 }
172 // TODO: perhaps explicit conversions later too?
173 return false;
174}
175
Aart Bik304c8a52017-05-23 11:01:13 -0700176// Detect situations with same-extension narrower operands.
177// Returns true on success and sets is_unsigned accordingly.
178static bool IsNarrowerOperands(HInstruction* a,
179 HInstruction* b,
180 Primitive::Type type,
181 /*out*/ HInstruction** r,
182 /*out*/ HInstruction** s,
183 /*out*/ bool* is_unsigned) {
184 if (IsSignExtensionAndGet(a, type, r) && IsSignExtensionAndGet(b, type, s)) {
185 *is_unsigned = false;
186 return true;
187 } else if (IsZeroExtensionAndGet(a, type, r) && IsZeroExtensionAndGet(b, type, s)) {
188 *is_unsigned = true;
189 return true;
190 }
191 return false;
192}
193
194// As above, single operand.
195static bool IsNarrowerOperand(HInstruction* a,
196 Primitive::Type type,
197 /*out*/ HInstruction** r,
198 /*out*/ bool* is_unsigned) {
199 if (IsSignExtensionAndGet(a, type, r)) {
200 *is_unsigned = false;
201 return true;
202 } else if (IsZeroExtensionAndGet(a, type, r)) {
203 *is_unsigned = true;
204 return true;
205 }
206 return false;
207}
208
Aart Bik5f805002017-05-16 16:42:41 -0700209// Detect up to two instructions a and b, and an acccumulated constant c.
210static bool IsAddConstHelper(HInstruction* instruction,
211 /*out*/ HInstruction** a,
212 /*out*/ HInstruction** b,
213 /*out*/ int64_t* c,
214 int32_t depth) {
215 static constexpr int32_t kMaxDepth = 8; // don't search too deep
216 int64_t value = 0;
217 if (IsInt64AndGet(instruction, &value)) {
218 *c += value;
219 return true;
220 } else if (instruction->IsAdd() && depth <= kMaxDepth) {
221 return IsAddConstHelper(instruction->InputAt(0), a, b, c, depth + 1) &&
222 IsAddConstHelper(instruction->InputAt(1), a, b, c, depth + 1);
223 } else if (*a == nullptr) {
224 *a = instruction;
225 return true;
226 } else if (*b == nullptr) {
227 *b = instruction;
228 return true;
229 }
230 return false; // too many non-const operands
231}
232
233// Detect a + b + c for an optional constant c.
234static bool IsAddConst(HInstruction* instruction,
235 /*out*/ HInstruction** a,
236 /*out*/ HInstruction** b,
237 /*out*/ int64_t* c) {
238 if (instruction->IsAdd()) {
239 // Try to find a + b and accumulated c.
240 if (IsAddConstHelper(instruction->InputAt(0), a, b, c, /*depth*/ 0) &&
241 IsAddConstHelper(instruction->InputAt(1), a, b, c, /*depth*/ 0) &&
242 *b != nullptr) {
243 return true;
244 }
245 // Found a + b.
246 *a = instruction->InputAt(0);
247 *b = instruction->InputAt(1);
248 *c = 0;
249 return true;
250 }
251 return false;
252}
253
Aart Bikf8f5a162017-02-06 15:35:29 -0800254// Test vector restrictions.
255static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
256 return (restrictions & tested) != 0;
257}
258
Aart Bikf3e61ee2017-04-12 17:09:20 -0700259// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800260static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
261 DCHECK(block != nullptr);
262 DCHECK(instruction != nullptr);
263 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
264 return instruction;
265}
266
Aart Bik281c6812016-08-26 11:31:48 -0700267//
268// Class methods.
269//
270
271HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800272 CompilerDriver* compiler_driver,
Aart Bik281c6812016-08-26 11:31:48 -0700273 HInductionVarAnalysis* induction_analysis)
274 : HOptimization(graph, kLoopOptimizationPassName),
Aart Bik92685a82017-03-06 11:13:43 -0800275 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700276 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700277 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800278 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -0700279 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700280 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700281 iset_(nullptr),
Aart Bikdf7822e2016-12-06 10:05:30 -0800282 induction_simplication_count_(0),
Aart Bikf8f5a162017-02-06 15:35:29 -0800283 simplified_(false),
284 vector_length_(0),
285 vector_refs_(nullptr),
286 vector_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700287}
288
289void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800290 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700291 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800292 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700293 return;
294 }
295
Aart Bik96202302016-10-04 17:33:56 -0700296 // Phase-local allocator that draws from the global pool. Since the allocator
297 // itself resides on the stack, it is destructed on exiting Run(), which
298 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800299 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700300 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100301
Aart Bik96202302016-10-04 17:33:56 -0700302 // Perform loop optimizations.
303 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800304 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800305 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800306 }
307
Aart Bik96202302016-10-04 17:33:56 -0700308 // Detach.
309 loop_allocator_ = nullptr;
310 last_loop_ = top_loop_ = nullptr;
311}
312
313void HLoopOptimization::LocalRun() {
314 // Build the linear order using the phase-local allocator. This step enables building
315 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
316 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
317 LinearizeGraph(graph_, loop_allocator_, &linear_order);
318
Aart Bik281c6812016-08-26 11:31:48 -0700319 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700320 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700321 if (block->IsLoopHeader()) {
322 AddLoop(block->GetLoopInformation());
323 }
324 }
Aart Bik96202302016-10-04 17:33:56 -0700325
Aart Bik8c4a8542016-10-06 11:36:57 -0700326 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800327 // temporary data structures using the phase-local allocator. All new HIR
328 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700329 if (top_loop_ != nullptr) {
330 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800331 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
332 ArenaSafeMap<HInstruction*, HInstruction*> map(
333 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
334 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700335 iset_ = &iset;
Aart Bikf8f5a162017-02-06 15:35:29 -0800336 vector_refs_ = &refs;
337 vector_map_ = &map;
338 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700339 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800340 // Detach.
341 iset_ = nullptr;
342 vector_refs_ = nullptr;
343 vector_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700344 }
Aart Bik281c6812016-08-26 11:31:48 -0700345}
346
347void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
348 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800349 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700350 if (last_loop_ == nullptr) {
351 // First loop.
352 DCHECK(top_loop_ == nullptr);
353 last_loop_ = top_loop_ = node;
354 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
355 // Inner loop.
356 node->outer = last_loop_;
357 DCHECK(last_loop_->inner == nullptr);
358 last_loop_ = last_loop_->inner = node;
359 } else {
360 // Subsequent loop.
361 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
362 last_loop_ = last_loop_->outer;
363 }
364 node->outer = last_loop_->outer;
365 node->previous = last_loop_;
366 DCHECK(last_loop_->next == nullptr);
367 last_loop_ = last_loop_->next = node;
368 }
369}
370
371void HLoopOptimization::RemoveLoop(LoopNode* node) {
372 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700373 DCHECK(node->inner == nullptr);
374 if (node->previous != nullptr) {
375 // Within sequence.
376 node->previous->next = node->next;
377 if (node->next != nullptr) {
378 node->next->previous = node->previous;
379 }
380 } else {
381 // First of sequence.
382 if (node->outer != nullptr) {
383 node->outer->inner = node->next;
384 } else {
385 top_loop_ = node->next;
386 }
387 if (node->next != nullptr) {
388 node->next->outer = node->outer;
389 node->next->previous = nullptr;
390 }
391 }
Aart Bik281c6812016-08-26 11:31:48 -0700392}
393
394void HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
395 for ( ; node != nullptr; node = node->next) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800396 // Visit inner loops first.
Aart Bikf8f5a162017-02-06 15:35:29 -0800397 uint32_t current_induction_simplification_count = induction_simplication_count_;
Aart Bik281c6812016-08-26 11:31:48 -0700398 if (node->inner != nullptr) {
399 TraverseLoopsInnerToOuter(node->inner);
400 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800401 // Recompute induction information of this loop if the induction
402 // of any inner loop has been simplified.
Aart Bik482095d2016-10-10 15:39:10 -0700403 if (current_induction_simplification_count != induction_simplication_count_) {
404 induction_range_.ReVisit(node->loop_info);
405 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800406 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800407 // Note that since each simplification consists of eliminating code (without
408 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800409 do {
410 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800411 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800412 SimplifyBlocks(node);
Aart Bikdf7822e2016-12-06 10:05:30 -0800413 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800414 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700415 if (node->inner == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800416 OptimizeInnerLoop(node);
Aart Bik9abf8942016-10-14 09:49:42 -0700417 }
Aart Bik281c6812016-08-26 11:31:48 -0700418 }
419}
420
Aart Bikf8f5a162017-02-06 15:35:29 -0800421//
422// Optimization.
423//
424
Aart Bik281c6812016-08-26 11:31:48 -0700425void HLoopOptimization::SimplifyInduction(LoopNode* node) {
426 HBasicBlock* header = node->loop_info->GetHeader();
427 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700428 // Scan the phis in the header to find opportunities to simplify an induction
429 // cycle that is only used outside the loop. Replace these uses, if any, with
430 // the last value and remove the induction cycle.
431 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
432 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700433 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
434 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800435 iset_->clear(); // prepare phi induction
436 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
437 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik8c4a8542016-10-06 11:36:57 -0700438 for (HInstruction* i : *iset_) {
439 RemoveFromCycle(i);
Aart Bik281c6812016-08-26 11:31:48 -0700440 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800441 simplified_ = true;
Aart Bik482095d2016-10-10 15:39:10 -0700442 }
443 }
444}
445
446void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800447 // Iterate over all basic blocks in the loop-body.
448 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
449 HBasicBlock* block = it.Current();
450 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800451 RemoveDeadInstructions(block->GetPhis());
452 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800453 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800454 if (block->GetPredecessors().size() == 1 &&
455 block->GetSuccessors().size() == 1 &&
456 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800457 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800458 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800459 } else if (block->GetSuccessors().size() == 2) {
460 // Trivial if block can be bypassed to either branch.
461 HBasicBlock* succ0 = block->GetSuccessors()[0];
462 HBasicBlock* succ1 = block->GetSuccessors()[1];
463 HBasicBlock* meet0 = nullptr;
464 HBasicBlock* meet1 = nullptr;
465 if (succ0 != succ1 &&
466 IsGotoBlock(succ0, &meet0) &&
467 IsGotoBlock(succ1, &meet1) &&
468 meet0 == meet1 && // meets again
469 meet0 != block && // no self-loop
470 meet0->GetPhis().IsEmpty()) { // not used for merging
471 simplified_ = true;
472 succ0->DisconnectAndDelete();
473 if (block->Dominates(meet0)) {
474 block->RemoveDominatedBlock(meet0);
475 succ1->AddDominatedBlock(meet0);
476 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700477 }
Aart Bik482095d2016-10-10 15:39:10 -0700478 }
Aart Bik281c6812016-08-26 11:31:48 -0700479 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800480 }
Aart Bik281c6812016-08-26 11:31:48 -0700481}
482
Aart Bikf8f5a162017-02-06 15:35:29 -0800483void HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700484 HBasicBlock* header = node->loop_info->GetHeader();
485 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700486 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800487 int64_t trip_count = 0;
488 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
489 return;
Aart Bik9abf8942016-10-14 09:49:42 -0700490 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800491
Aart Bik281c6812016-08-26 11:31:48 -0700492 // Ensure there is only a single loop-body (besides the header).
493 HBasicBlock* body = nullptr;
494 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
495 if (it.Current() != header) {
496 if (body != nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800497 return;
Aart Bik281c6812016-08-26 11:31:48 -0700498 }
499 body = it.Current();
500 }
501 }
502 // Ensure there is only a single exit point.
503 if (header->GetSuccessors().size() != 2) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800504 return;
Aart Bik281c6812016-08-26 11:31:48 -0700505 }
506 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
507 ? header->GetSuccessors()[1]
508 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700509 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700510 if (exit->GetPredecessors().size() != 1) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800511 return;
Aart Bik281c6812016-08-26 11:31:48 -0700512 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800513 // Detect either an empty loop (no side effects other than plain iteration) or
514 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
515 // with the last value and remove the loop, possibly after unrolling its body.
516 HInstruction* phi = header->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800517 iset_->clear(); // prepare phi induction
518 if (TrySetSimpleLoopHeader(header)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800519 bool is_empty = IsEmptyBody(body);
Aart Bikf8f5a162017-02-06 15:35:29 -0800520 if ((is_empty || trip_count == 1) &&
521 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800522 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800523 // Unroll the loop-body, which sees initial value of the index.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800524 phi->ReplaceWith(phi->InputAt(0));
525 preheader->MergeInstructionsWith(body);
526 }
527 body->DisconnectAndDelete();
528 exit->RemovePredecessor(header);
529 header->RemoveSuccessor(exit);
530 header->RemoveDominatedBlock(exit);
531 header->DisconnectAndDelete();
532 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800533 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800534 preheader->AddDominatedBlock(exit);
535 exit->SetDominator(preheader);
536 RemoveLoop(node); // update hierarchy
Aart Bikf8f5a162017-02-06 15:35:29 -0800537 return;
538 }
539 }
540
541 // Vectorize loop, if possible and valid.
542 if (kEnableVectorization) {
543 iset_->clear(); // prepare phi induction
544 if (TrySetSimpleLoopHeader(header) &&
545 CanVectorize(node, body, trip_count) &&
546 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
547 Vectorize(node, body, exit, trip_count);
548 graph_->SetHasSIMD(true); // flag SIMD usage
549 return;
550 }
551 }
552}
553
554//
555// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
556// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
557// Intel Press, June, 2004 (http://www.aartbik.com/).
558//
559
560bool HLoopOptimization::CanVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
561 // Reset vector bookkeeping.
562 vector_length_ = 0;
563 vector_refs_->clear();
564 vector_runtime_test_a_ =
565 vector_runtime_test_b_= nullptr;
566
567 // Phis in the loop-body prevent vectorization.
568 if (!block->GetPhis().IsEmpty()) {
569 return false;
570 }
571
572 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
573 // occurrence, which allows passing down attributes down the use tree.
574 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
575 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
576 return false; // failure to vectorize a left-hand-side
577 }
578 }
579
580 // Heuristics. Does vectorization seem profitable?
581 // TODO: refine
582 if (vector_length_ == 0) {
583 return false; // nothing found
584 } else if (0 < trip_count && trip_count < vector_length_) {
585 return false; // insufficient iterations
586 }
587
588 // Data dependence analysis. Find each pair of references with same type, where
589 // at least one is a write. Each such pair denotes a possible data dependence.
590 // This analysis exploits the property that differently typed arrays cannot be
591 // aliased, as well as the property that references either point to the same
592 // array or to two completely disjoint arrays, i.e., no partial aliasing.
593 // Other than a few simply heuristics, no detailed subscript analysis is done.
594 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
595 for (auto j = i; ++j != vector_refs_->end(); ) {
596 if (i->type == j->type && (i->lhs || j->lhs)) {
597 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
598 HInstruction* a = i->base;
599 HInstruction* b = j->base;
600 HInstruction* x = i->offset;
601 HInstruction* y = j->offset;
602 if (a == b) {
603 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
604 // Conservatively assume a loop-carried data dependence otherwise, and reject.
605 if (x != y) {
606 return false;
607 }
608 } else {
609 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
610 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
611 // generating an explicit a != b disambiguation runtime test on the two references.
612 if (x != y) {
613 // For now, we reject after one test to avoid excessive overhead.
614 if (vector_runtime_test_a_ != nullptr) {
615 return false;
616 }
617 vector_runtime_test_a_ = a;
618 vector_runtime_test_b_ = b;
619 }
620 }
621 }
622 }
623 }
624
625 // Success!
626 return true;
627}
628
629void HLoopOptimization::Vectorize(LoopNode* node,
630 HBasicBlock* block,
631 HBasicBlock* exit,
632 int64_t trip_count) {
633 Primitive::Type induc_type = Primitive::kPrimInt;
634 HBasicBlock* header = node->loop_info->GetHeader();
635 HBasicBlock* preheader = node->loop_info->GetPreHeader();
636
637 // A cleanup is needed for any unknown trip count or for a known trip count
638 // with remainder iterations after vectorization.
639 bool needs_cleanup = trip_count == 0 || (trip_count % vector_length_) != 0;
640
641 // Adjust vector bookkeeping.
642 iset_->clear(); // prepare phi induction
643 bool is_simple_loop_header = TrySetSimpleLoopHeader(header); // fills iset_
644 DCHECK(is_simple_loop_header);
645
646 // Generate preheader:
647 // stc = <trip-count>;
648 // vtc = stc - stc % VL;
649 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
650 HInstruction* vtc = stc;
651 if (needs_cleanup) {
652 DCHECK(IsPowerOfTwo(vector_length_));
653 HInstruction* rem = Insert(
654 preheader, new (global_allocator_) HAnd(induc_type,
655 stc,
656 graph_->GetIntConstant(vector_length_ - 1)));
657 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
658 }
659
660 // Generate runtime disambiguation test:
661 // vtc = a != b ? vtc : 0;
662 if (vector_runtime_test_a_ != nullptr) {
663 HInstruction* rt = Insert(
664 preheader,
665 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
666 vtc = Insert(preheader,
667 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
668 needs_cleanup = true;
669 }
670
671 // Generate vector loop:
672 // for (i = 0; i < vtc; i += VL)
673 // <vectorized-loop-body>
674 vector_mode_ = kVector;
675 GenerateNewLoop(node,
676 block,
677 graph_->TransformLoopForVectorization(header, block, exit),
678 graph_->GetIntConstant(0),
679 vtc,
680 graph_->GetIntConstant(vector_length_));
681 HLoopInformation* vloop = vector_header_->GetLoopInformation();
682
683 // Generate cleanup loop, if needed:
684 // for ( ; i < stc; i += 1)
685 // <loop-body>
686 if (needs_cleanup) {
687 vector_mode_ = kSequential;
688 GenerateNewLoop(node,
689 block,
690 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
691 vector_phi_,
692 stc,
693 graph_->GetIntConstant(1));
694 }
695
696 // Remove the original loop by disconnecting the body block
697 // and removing all instructions from the header.
698 block->DisconnectAndDelete();
699 while (!header->GetFirstInstruction()->IsGoto()) {
700 header->RemoveInstruction(header->GetFirstInstruction());
701 }
702 // Update loop hierarchy: the old header now resides in the
703 // same outer loop as the old preheader.
704 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
705 node->loop_info = vloop;
706}
707
708void HLoopOptimization::GenerateNewLoop(LoopNode* node,
709 HBasicBlock* block,
710 HBasicBlock* new_preheader,
711 HInstruction* lo,
712 HInstruction* hi,
713 HInstruction* step) {
714 Primitive::Type induc_type = Primitive::kPrimInt;
715 // Prepare new loop.
716 vector_map_->clear();
717 vector_preheader_ = new_preheader,
718 vector_header_ = vector_preheader_->GetSingleSuccessor();
719 vector_body_ = vector_header_->GetSuccessors()[1];
720 vector_phi_ = new (global_allocator_) HPhi(global_allocator_,
721 kNoRegNumber,
722 0,
723 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700724 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800725 // for (i = lo; i < hi; i += step)
726 // <loop-body>
727 HInstruction* cond = new (global_allocator_) HAboveOrEqual(vector_phi_, hi);
728 vector_header_->AddPhi(vector_phi_);
729 vector_header_->AddInstruction(cond);
730 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bikf8f5a162017-02-06 15:35:29 -0800731 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
732 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
733 DCHECK(vectorized_def);
734 }
Aart Bik24b905f2017-04-06 09:59:06 -0700735 // Generate body from the instruction map, but in original program order.
Aart Bikb07d1bc2017-04-05 10:03:15 -0700736 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
Aart Bikf8f5a162017-02-06 15:35:29 -0800737 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
738 auto i = vector_map_->find(it.Current());
739 if (i != vector_map_->end() && !i->second->IsInBlock()) {
Aart Bik24b905f2017-04-06 09:59:06 -0700740 Insert(vector_body_, i->second);
741 // Deal with instructions that need an environment, such as the scalar intrinsics.
Aart Bikf8f5a162017-02-06 15:35:29 -0800742 if (i->second->NeedsEnvironment()) {
Aart Bikb07d1bc2017-04-05 10:03:15 -0700743 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800744 }
745 }
746 }
747 // Finalize increment and phi.
748 HInstruction* inc = new (global_allocator_) HAdd(induc_type, vector_phi_, step);
749 vector_phi_->AddInput(lo);
750 vector_phi_->AddInput(Insert(vector_body_, inc));
751}
752
753// TODO: accept reductions at left-hand-side, mixed-type store idioms, etc.
754bool HLoopOptimization::VectorizeDef(LoopNode* node,
755 HInstruction* instruction,
756 bool generate_code) {
757 // Accept a left-hand-side array base[index] for
758 // (1) supported vector type,
759 // (2) loop-invariant base,
760 // (3) unit stride index,
761 // (4) vectorizable right-hand-side value.
762 uint64_t restrictions = kNone;
763 if (instruction->IsArraySet()) {
764 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
765 HInstruction* base = instruction->InputAt(0);
766 HInstruction* index = instruction->InputAt(1);
767 HInstruction* value = instruction->InputAt(2);
768 HInstruction* offset = nullptr;
769 if (TrySetVectorType(type, &restrictions) &&
770 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bikfa762962017-04-07 11:33:37 -0700771 induction_range_.IsUnitStride(instruction, index, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800772 VectorizeUse(node, value, generate_code, type, restrictions)) {
773 if (generate_code) {
774 GenerateVecSub(index, offset);
775 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), type);
776 } else {
777 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
778 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800779 return true;
780 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800781 return false;
782 }
783 // Branch back okay.
784 if (instruction->IsGoto()) {
785 return true;
786 }
787 // Otherwise accept only expressions with no effects outside the immediate loop-body.
788 // Note that actual uses are inspected during right-hand-side tree traversal.
789 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
790}
791
Aart Bik304c8a52017-05-23 11:01:13 -0700792// TODO: saturation arithmetic.
Aart Bikf8f5a162017-02-06 15:35:29 -0800793bool HLoopOptimization::VectorizeUse(LoopNode* node,
794 HInstruction* instruction,
795 bool generate_code,
796 Primitive::Type type,
797 uint64_t restrictions) {
798 // Accept anything for which code has already been generated.
799 if (generate_code) {
800 if (vector_map_->find(instruction) != vector_map_->end()) {
801 return true;
802 }
803 }
804 // Continue the right-hand-side tree traversal, passing in proper
805 // types and vector restrictions along the way. During code generation,
806 // all new nodes are drawn from the global allocator.
807 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
808 // Accept invariant use, using scalar expansion.
809 if (generate_code) {
810 GenerateVecInv(instruction, type);
811 }
812 return true;
813 } else if (instruction->IsArrayGet()) {
Goran Jakovljevic19680d32017-05-11 10:38:36 +0200814 // Deal with vector restrictions.
815 if (instruction->AsArrayGet()->IsStringCharAt() &&
816 HasVectorRestrictions(restrictions, kNoStringCharAt)) {
817 return false;
818 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800819 // Accept a right-hand-side array base[index] for
820 // (1) exact matching vector type,
821 // (2) loop-invariant base,
822 // (3) unit stride index,
823 // (4) vectorizable right-hand-side value.
824 HInstruction* base = instruction->InputAt(0);
825 HInstruction* index = instruction->InputAt(1);
826 HInstruction* offset = nullptr;
827 if (type == instruction->GetType() &&
828 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bikfa762962017-04-07 11:33:37 -0700829 induction_range_.IsUnitStride(instruction, index, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800830 if (generate_code) {
831 GenerateVecSub(index, offset);
832 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, type);
833 } else {
834 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
835 }
836 return true;
837 }
838 } else if (instruction->IsTypeConversion()) {
839 // Accept particular type conversions.
840 HTypeConversion* conversion = instruction->AsTypeConversion();
841 HInstruction* opa = conversion->InputAt(0);
842 Primitive::Type from = conversion->GetInputType();
843 Primitive::Type to = conversion->GetResultType();
844 if ((to == Primitive::kPrimByte ||
845 to == Primitive::kPrimChar ||
846 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
847 // Accept a "narrowing" type conversion from a "wider" computation for
848 // (1) conversion into final required type,
849 // (2) vectorizable operand,
850 // (3) "wider" operations cannot bring in higher order bits.
851 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
852 if (generate_code) {
853 if (vector_mode_ == kVector) {
854 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
855 } else {
856 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
857 }
858 }
859 return true;
860 }
861 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
862 DCHECK_EQ(to, type);
863 // Accept int to float conversion for
864 // (1) supported int,
865 // (2) vectorizable operand.
866 if (TrySetVectorType(from, &restrictions) &&
867 VectorizeUse(node, opa, generate_code, from, restrictions)) {
868 if (generate_code) {
869 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
870 }
871 return true;
872 }
873 }
874 return false;
875 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
876 // Accept unary operator for vectorizable operand.
877 HInstruction* opa = instruction->InputAt(0);
878 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
879 if (generate_code) {
880 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
881 }
882 return true;
883 }
884 } else if (instruction->IsAdd() || instruction->IsSub() ||
885 instruction->IsMul() || instruction->IsDiv() ||
886 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
887 // Deal with vector restrictions.
888 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
889 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
890 return false;
891 }
892 // Accept binary operator for vectorizable operands.
893 HInstruction* opa = instruction->InputAt(0);
894 HInstruction* opb = instruction->InputAt(1);
895 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
896 VectorizeUse(node, opb, generate_code, type, restrictions)) {
897 if (generate_code) {
898 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
899 }
900 return true;
901 }
902 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700903 // Recognize vectorization idioms.
904 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
905 return true;
906 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800907 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -0700908 HInstruction* opa = instruction->InputAt(0);
909 HInstruction* opb = instruction->InputAt(1);
910 HInstruction* r = opa;
911 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800912 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
913 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
914 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -0700915 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
916 // Shifts right need extra care to account for higher order bits.
917 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
918 if (instruction->IsShr() &&
919 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
920 return false; // reject, unless all operands are sign-extension narrower
921 } else if (instruction->IsUShr() &&
922 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
923 return false; // reject, unless all operands are zero-extension narrower
924 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800925 }
926 // Accept shift operator for vectorizable/invariant operands.
927 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -0700928 DCHECK(r != nullptr);
929 if (generate_code && vector_mode_ != kVector) { // de-idiom
930 r = opa;
931 }
Aart Bik50e20d52017-05-05 14:07:29 -0700932 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -0700933 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -0700934 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -0700935 // Restrict shift distance to packed data type width.
936 int64_t max_distance = Primitive::ComponentSize(type) * 8;
937 if (0 <= distance && distance < max_distance) {
938 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -0700939 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -0700940 }
941 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800942 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800943 }
944 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700945 // Accept particular intrinsics.
946 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
947 switch (invoke->GetIntrinsic()) {
948 case Intrinsics::kMathAbsInt:
949 case Intrinsics::kMathAbsLong:
950 case Intrinsics::kMathAbsFloat:
951 case Intrinsics::kMathAbsDouble: {
952 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -0700953 HInstruction* opa = instruction->InputAt(0);
954 HInstruction* r = opa;
955 bool is_unsigned = false;
956 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700957 return false;
Aart Bik304c8a52017-05-23 11:01:13 -0700958 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
959 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
960 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -0700961 }
962 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -0700963 DCHECK(r != nullptr);
964 if (generate_code && vector_mode_ != kVector) { // de-idiom
965 r = opa;
966 }
967 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700968 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -0700969 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -0700970 }
971 return true;
972 }
973 return false;
974 }
Aart Bikc8e93c72017-05-10 10:49:22 -0700975 case Intrinsics::kMathMinIntInt:
976 case Intrinsics::kMathMinLongLong:
977 case Intrinsics::kMathMinFloatFloat:
978 case Intrinsics::kMathMinDoubleDouble:
979 case Intrinsics::kMathMaxIntInt:
980 case Intrinsics::kMathMaxLongLong:
981 case Intrinsics::kMathMaxFloatFloat:
982 case Intrinsics::kMathMaxDoubleDouble: {
983 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +0000984 HInstruction* opa = instruction->InputAt(0);
985 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -0700986 HInstruction* r = opa;
987 HInstruction* s = opb;
988 bool is_unsigned = false;
989 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
990 return false;
991 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
992 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
993 return false; // reject, unless all operands are same-extension narrower
994 }
995 // Accept MIN/MAX(x, y) for vectorizable operands.
996 DCHECK(r != nullptr && s != nullptr);
997 if (generate_code && vector_mode_ != kVector) { // de-idiom
998 r = opa;
999 s = opb;
1000 }
1001 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1002 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -07001003 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -07001004 GenerateVecOp(
1005 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001006 }
1007 return true;
1008 }
1009 return false;
1010 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001011 default:
1012 return false;
1013 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001014 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001015 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001016}
1017
Aart Bikf8f5a162017-02-06 15:35:29 -08001018bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
1019 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1020 switch (compiler_driver_->GetInstructionSet()) {
1021 case kArm:
1022 case kThumb2:
1023 return false;
1024 case kArm64:
1025 // Allow vectorization for all ARM devices, because Android assumes that
Artem Serovd4bccf12017-04-03 18:47:32 +01001026 // ARMv8 AArch64 always supports advanced SIMD.
Aart Bikf8f5a162017-02-06 15:35:29 -08001027 switch (type) {
1028 case Primitive::kPrimBoolean:
1029 case Primitive::kPrimByte:
Aart Bik304c8a52017-05-23 11:01:13 -07001030 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001031 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -08001032 case Primitive::kPrimChar:
1033 case Primitive::kPrimShort:
Aart Bik304c8a52017-05-23 11:01:13 -07001034 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001035 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -08001036 case Primitive::kPrimInt:
1037 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001038 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001039 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001040 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001041 return TrySetVectorLength(2);
1042 case Primitive::kPrimFloat:
Artem Serovd4bccf12017-04-03 18:47:32 +01001043 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001044 case Primitive::kPrimDouble:
Aart Bikf8f5a162017-02-06 15:35:29 -08001045 return TrySetVectorLength(2);
1046 default:
1047 return false;
1048 }
1049 case kX86:
1050 case kX86_64:
1051 // Allow vectorization for SSE4-enabled X86 devices only (128-bit vectors).
1052 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1053 switch (type) {
1054 case Primitive::kPrimBoolean:
1055 case Primitive::kPrimByte:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001056 *restrictions |= kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001057 return TrySetVectorLength(16);
1058 case Primitive::kPrimChar:
1059 case Primitive::kPrimShort:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001060 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001061 return TrySetVectorLength(8);
1062 case Primitive::kPrimInt:
1063 *restrictions |= kNoDiv;
1064 return TrySetVectorLength(4);
1065 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001066 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001067 return TrySetVectorLength(2);
1068 case Primitive::kPrimFloat:
Aart Bikc8e93c72017-05-10 10:49:22 -07001069 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001070 return TrySetVectorLength(4);
1071 case Primitive::kPrimDouble:
Aart Bikc8e93c72017-05-10 10:49:22 -07001072 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001073 return TrySetVectorLength(2);
1074 default:
1075 break;
1076 } // switch type
1077 }
1078 return false;
1079 case kMips:
Aart Bikf8f5a162017-02-06 15:35:29 -08001080 // TODO: implement MIPS SIMD.
1081 return false;
Goran Jakovljevic19680d32017-05-11 10:38:36 +02001082 case kMips64:
1083 if (features->AsMips64InstructionSetFeatures()->HasMsa()) {
1084 switch (type) {
1085 case Primitive::kPrimBoolean:
1086 case Primitive::kPrimByte:
1087 *restrictions |= kNoDiv | kNoMinMax;
1088 return TrySetVectorLength(16);
1089 case Primitive::kPrimChar:
1090 case Primitive::kPrimShort:
1091 *restrictions |= kNoDiv | kNoMinMax | kNoStringCharAt;
1092 return TrySetVectorLength(8);
1093 case Primitive::kPrimInt:
1094 *restrictions |= kNoDiv | kNoMinMax;
1095 return TrySetVectorLength(4);
1096 case Primitive::kPrimLong:
1097 *restrictions |= kNoDiv | kNoMinMax;
1098 return TrySetVectorLength(2);
1099 case Primitive::kPrimFloat:
1100 *restrictions |= kNoMinMax;
1101 return TrySetVectorLength(4);
1102 case Primitive::kPrimDouble:
1103 *restrictions |= kNoMinMax;
1104 return TrySetVectorLength(2);
1105 default:
1106 break;
1107 } // switch type
1108 }
1109 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001110 default:
1111 return false;
1112 } // switch instruction set
1113}
1114
1115bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1116 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1117 // First time set?
1118 if (vector_length_ == 0) {
1119 vector_length_ = length;
1120 }
1121 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1122 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1123 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1124 return vector_length_ == length;
1125}
1126
1127void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
1128 if (vector_map_->find(org) == vector_map_->end()) {
1129 // In scalar code, just use a self pass-through for scalar invariants
1130 // (viz. expression remains itself).
1131 if (vector_mode_ == kSequential) {
1132 vector_map_->Put(org, org);
1133 return;
1134 }
1135 // In vector code, explicit scalar expansion is needed.
1136 HInstruction* vector = new (global_allocator_) HVecReplicateScalar(
1137 global_allocator_, org, type, vector_length_);
1138 vector_map_->Put(org, Insert(vector_preheader_, vector));
1139 }
1140}
1141
1142void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1143 if (vector_map_->find(org) == vector_map_->end()) {
1144 HInstruction* subscript = vector_phi_;
1145 if (offset != nullptr) {
1146 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
1147 if (org->IsPhi()) {
1148 Insert(vector_body_, subscript); // lacks layout placeholder
1149 }
1150 }
1151 vector_map_->Put(org, subscript);
1152 }
1153}
1154
1155void HLoopOptimization::GenerateVecMem(HInstruction* org,
1156 HInstruction* opa,
1157 HInstruction* opb,
1158 Primitive::Type type) {
1159 HInstruction* vector = nullptr;
1160 if (vector_mode_ == kVector) {
1161 // Vector store or load.
1162 if (opb != nullptr) {
1163 vector = new (global_allocator_) HVecStore(
1164 global_allocator_, org->InputAt(0), opa, opb, type, vector_length_);
1165 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001166 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001167 vector = new (global_allocator_) HVecLoad(
Aart Bikdb14fcf2017-04-25 15:53:58 -07001168 global_allocator_, org->InputAt(0), opa, type, vector_length_, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001169 }
1170 } else {
1171 // Scalar store or load.
1172 DCHECK(vector_mode_ == kSequential);
1173 if (opb != nullptr) {
1174 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1175 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001176 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1177 vector = new (global_allocator_) HArrayGet(
1178 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001179 }
1180 }
1181 vector_map_->Put(org, vector);
1182}
1183
1184#define GENERATE_VEC(x, y) \
1185 if (vector_mode_ == kVector) { \
1186 vector = (x); \
1187 } else { \
1188 DCHECK(vector_mode_ == kSequential); \
1189 vector = (y); \
1190 } \
1191 break;
1192
1193void HLoopOptimization::GenerateVecOp(HInstruction* org,
1194 HInstruction* opa,
1195 HInstruction* opb,
Aart Bik304c8a52017-05-23 11:01:13 -07001196 Primitive::Type type,
1197 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001198 if (vector_mode_ == kSequential) {
Aart Bik304c8a52017-05-23 11:01:13 -07001199 // Non-converting scalar code follows implicit integral promotion.
1200 if (!org->IsTypeConversion() && (type == Primitive::kPrimBoolean ||
1201 type == Primitive::kPrimByte ||
1202 type == Primitive::kPrimChar ||
1203 type == Primitive::kPrimShort)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001204 type = Primitive::kPrimInt;
1205 }
1206 }
1207 HInstruction* vector = nullptr;
1208 switch (org->GetKind()) {
1209 case HInstruction::kNeg:
1210 DCHECK(opb == nullptr);
1211 GENERATE_VEC(
1212 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
1213 new (global_allocator_) HNeg(type, opa));
1214 case HInstruction::kNot:
1215 DCHECK(opb == nullptr);
1216 GENERATE_VEC(
1217 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1218 new (global_allocator_) HNot(type, opa));
1219 case HInstruction::kBooleanNot:
1220 DCHECK(opb == nullptr);
1221 GENERATE_VEC(
1222 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1223 new (global_allocator_) HBooleanNot(opa));
1224 case HInstruction::kTypeConversion:
1225 DCHECK(opb == nullptr);
1226 GENERATE_VEC(
1227 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
1228 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
1229 case HInstruction::kAdd:
1230 GENERATE_VEC(
1231 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
1232 new (global_allocator_) HAdd(type, opa, opb));
1233 case HInstruction::kSub:
1234 GENERATE_VEC(
1235 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
1236 new (global_allocator_) HSub(type, opa, opb));
1237 case HInstruction::kMul:
1238 GENERATE_VEC(
1239 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
1240 new (global_allocator_) HMul(type, opa, opb));
1241 case HInstruction::kDiv:
1242 GENERATE_VEC(
1243 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
1244 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
1245 case HInstruction::kAnd:
1246 GENERATE_VEC(
1247 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
1248 new (global_allocator_) HAnd(type, opa, opb));
1249 case HInstruction::kOr:
1250 GENERATE_VEC(
1251 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
1252 new (global_allocator_) HOr(type, opa, opb));
1253 case HInstruction::kXor:
1254 GENERATE_VEC(
1255 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
1256 new (global_allocator_) HXor(type, opa, opb));
1257 case HInstruction::kShl:
1258 GENERATE_VEC(
1259 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
1260 new (global_allocator_) HShl(type, opa, opb));
1261 case HInstruction::kShr:
1262 GENERATE_VEC(
1263 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
1264 new (global_allocator_) HShr(type, opa, opb));
1265 case HInstruction::kUShr:
1266 GENERATE_VEC(
1267 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
1268 new (global_allocator_) HUShr(type, opa, opb));
1269 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001270 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1271 if (vector_mode_ == kVector) {
1272 switch (invoke->GetIntrinsic()) {
1273 case Intrinsics::kMathAbsInt:
1274 case Intrinsics::kMathAbsLong:
1275 case Intrinsics::kMathAbsFloat:
1276 case Intrinsics::kMathAbsDouble:
1277 DCHECK(opb == nullptr);
1278 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1279 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001280 case Intrinsics::kMathMinIntInt:
1281 case Intrinsics::kMathMinLongLong:
1282 case Intrinsics::kMathMinFloatFloat:
1283 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001284 vector = new (global_allocator_)
1285 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1286 break;
1287 }
1288 case Intrinsics::kMathMaxIntInt:
1289 case Intrinsics::kMathMaxLongLong:
1290 case Intrinsics::kMathMaxFloatFloat:
1291 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001292 vector = new (global_allocator_)
1293 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1294 break;
1295 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001296 default:
1297 LOG(FATAL) << "Unsupported SIMD intrinsic";
1298 UNREACHABLE();
1299 } // switch invoke
1300 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001301 // In scalar code, simply clone the method invoke, and replace its operands with the
1302 // corresponding new scalar instructions in the loop. The instruction will get an
1303 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001304 DCHECK(vector_mode_ == kSequential);
1305 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1306 global_allocator_,
1307 invoke->GetNumberOfArguments(),
1308 invoke->GetType(),
1309 invoke->GetDexPc(),
1310 invoke->GetDexMethodIndex(),
1311 invoke->GetResolvedMethod(),
1312 invoke->GetDispatchInfo(),
1313 invoke->GetInvokeType(),
1314 invoke->GetTargetMethod(),
1315 invoke->GetClinitCheckRequirement());
1316 HInputsRef inputs = invoke->GetInputs();
1317 for (size_t index = 0; index < inputs.size(); ++index) {
1318 new_invoke->SetArgumentAt(index, vector_map_->Get(inputs[index]));
1319 }
Aart Bik98990262017-04-10 13:15:57 -07001320 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1321 kNeedsEnvironmentOrCache,
1322 kNoSideEffects,
1323 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001324 vector = new_invoke;
1325 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001326 break;
1327 }
1328 default:
1329 break;
1330 } // switch
1331 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1332 vector_map_->Put(org, vector);
1333}
1334
1335#undef GENERATE_VEC
1336
1337//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001338// Vectorization idioms.
1339//
1340
1341// Method recognizes the following idioms:
1342// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1343// regular halving add (a + b) >> 1 for unsigned/signed operands a, b
1344// Provided that the operands are promoted to a wider form to do the arithmetic and
1345// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1346// implementation that operates directly in narrower form (plus one extra bit).
1347// TODO: current version recognizes implicit byte/short/char widening only;
1348// explicit widening from int to long could be added later.
1349bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1350 HInstruction* instruction,
1351 bool generate_code,
1352 Primitive::Type type,
1353 uint64_t restrictions) {
1354 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001355 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001356 // on the narrow precision computed by the idiom).
Aart Bik5f805002017-05-16 16:42:41 -07001357 int64_t distance = 0;
Aart Bikf3e61ee2017-04-12 17:09:20 -07001358 if ((instruction->IsShr() ||
1359 instruction->IsUShr()) &&
Aart Bik5f805002017-05-16 16:42:41 -07001360 IsInt64AndGet(instruction->InputAt(1), /*out*/ &distance) && distance == 1) {
1361 // Test for (a + b + c) >> 1 for optional constant c.
1362 HInstruction* a = nullptr;
1363 HInstruction* b = nullptr;
1364 int64_t c = 0;
1365 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001366 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001367 // Accept c == 1 (rounded) or c == 0 (not rounded).
1368 bool is_rounded = false;
1369 if (c == 1) {
1370 is_rounded = true;
1371 } else if (c != 0) {
1372 return false;
1373 }
1374 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001375 HInstruction* r = nullptr;
1376 HInstruction* s = nullptr;
1377 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001378 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001379 return false;
1380 }
1381 // Deal with vector restrictions.
1382 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1383 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1384 return false;
1385 }
1386 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1387 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
1388 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001389 if (generate_code && vector_mode_ != kVector) { // de-idiom
1390 r = instruction->InputAt(0);
1391 s = instruction->InputAt(1);
1392 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001393 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1394 VectorizeUse(node, s, generate_code, type, restrictions)) {
1395 if (generate_code) {
1396 if (vector_mode_ == kVector) {
1397 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1398 global_allocator_,
1399 vector_map_->Get(r),
1400 vector_map_->Get(s),
1401 type,
1402 vector_length_,
1403 is_unsigned,
1404 is_rounded));
1405 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001406 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001407 }
1408 }
1409 return true;
1410 }
1411 }
1412 }
1413 return false;
1414}
1415
1416//
Aart Bikf8f5a162017-02-06 15:35:29 -08001417// Helpers.
1418//
1419
1420bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
1421 DCHECK(iset_->empty());
Aart Bikcc42be02016-10-20 16:14:16 -07001422 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1423 if (set != nullptr) {
1424 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001425 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001426 // each instruction is removable and, when restrict uses are requested, other than for phi,
1427 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001428 if (!i->IsInBlock()) {
1429 continue;
1430 } else if (!i->IsRemovable()) {
1431 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001432 } else if (i != phi && restrict_uses) {
Aart Bikcc42be02016-10-20 16:14:16 -07001433 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1434 if (set->find(use.GetUser()) == set->end()) {
1435 return false;
1436 }
1437 }
1438 }
Aart Bike3dedc52016-11-02 17:50:27 -07001439 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001440 }
Aart Bikcc42be02016-10-20 16:14:16 -07001441 return true;
1442 }
1443 return false;
1444}
1445
1446// Find: phi: Phi(init, addsub)
1447// s: SuspendCheck
1448// c: Condition(phi, bound)
1449// i: If(c)
1450// TODO: Find a less pattern matching approach?
Aart Bikf8f5a162017-02-06 15:35:29 -08001451bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block) {
Aart Bikcc42be02016-10-20 16:14:16 -07001452 DCHECK(iset_->empty());
1453 HInstruction* phi = block->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -08001454 if (phi != nullptr &&
1455 phi->GetNext() == nullptr &&
1456 TrySetPhiInduction(phi->AsPhi(), /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001457 HInstruction* s = block->GetFirstInstruction();
1458 if (s != nullptr && s->IsSuspendCheck()) {
1459 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07001460 if (c != nullptr &&
1461 c->IsCondition() &&
1462 c->GetUses().HasExactlyOneElement() && // only used for termination
1463 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07001464 HInstruction* i = c->GetNext();
1465 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1466 iset_->insert(c);
1467 iset_->insert(s);
1468 return true;
1469 }
1470 }
1471 }
1472 }
1473 return false;
1474}
1475
1476bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001477 if (!block->GetPhis().IsEmpty()) {
1478 return false;
1479 }
1480 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1481 HInstruction* instruction = it.Current();
1482 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1483 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001484 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001485 }
1486 return true;
1487}
1488
1489bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1490 HInstruction* instruction) {
1491 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1492 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1493 return true;
1494 }
Aart Bikcc42be02016-10-20 16:14:16 -07001495 }
1496 return false;
1497}
1498
Aart Bik482095d2016-10-10 15:39:10 -07001499bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001500 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001501 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001502 /*out*/ int32_t* use_count) {
1503 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1504 HInstruction* user = use.GetUser();
1505 if (iset_->find(user) == iset_->end()) { // not excluded?
1506 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001507 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001508 // If collect_loop_uses is set, simply keep adding those uses to the set.
1509 // Otherwise, reject uses inside the loop that were not already in the set.
1510 if (collect_loop_uses) {
1511 iset_->insert(user);
1512 continue;
1513 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001514 return false;
1515 }
1516 ++*use_count;
1517 }
1518 }
1519 return true;
1520}
1521
Aart Bik807868e2016-11-03 17:51:43 -07001522bool HLoopOptimization::TryReplaceWithLastValue(HInstruction* instruction, HBasicBlock* block) {
1523 // Try to replace outside uses with the last value. Environment uses can consume this
1524 // value too, since any first true use is outside the loop (although this may imply
1525 // that de-opting may look "ahead" a bit on the phi value). If there are only environment
1526 // uses, the value is dropped altogether, since the computations have no effect.
1527 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001528 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
1529 const HUseList<HInstruction*>& uses = instruction->GetUses();
1530 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1531 HInstruction* user = it->GetUser();
1532 size_t index = it->GetIndex();
1533 ++it; // increment before replacing
1534 if (iset_->find(user) == iset_->end()) { // not excluded?
1535 user->ReplaceInput(replacement, index);
1536 induction_range_.Replace(user, instruction, replacement); // update induction
1537 }
1538 }
1539 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1540 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1541 HEnvironment* user = it->GetUser();
1542 size_t index = it->GetIndex();
1543 ++it; // increment before replacing
1544 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
1545 user->RemoveAsUserOfInput(index);
1546 user->SetRawEnvAt(index, replacement);
1547 replacement->AddEnvUseAt(user, index);
1548 }
1549 }
1550 induction_simplication_count_++;
Aart Bik807868e2016-11-03 17:51:43 -07001551 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001552 }
Aart Bik807868e2016-11-03 17:51:43 -07001553 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001554}
1555
Aart Bikf8f5a162017-02-06 15:35:29 -08001556bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1557 HInstruction* instruction,
1558 HBasicBlock* block,
1559 bool collect_loop_uses) {
1560 // Assigning the last value is always successful if there are no uses.
1561 // Otherwise, it succeeds in a no early-exit loop by generating the
1562 // proper last value assignment.
1563 int32_t use_count = 0;
1564 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
1565 (use_count == 0 ||
1566 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(instruction, block)));
1567}
1568
Aart Bik6b69e0a2017-01-11 10:20:43 -08001569void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
1570 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
1571 HInstruction* instruction = i.Current();
1572 if (instruction->IsDeadAndRemovable()) {
1573 simplified_ = true;
1574 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
1575 }
1576 }
1577}
1578
Aart Bik281c6812016-08-26 11:31:48 -07001579} // namespace art