blob: 94787c99b2f347fc3a0e7535f8164e5173bd29f6 [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()) {
814 // Accept a right-hand-side array base[index] for
815 // (1) exact matching vector type,
816 // (2) loop-invariant base,
817 // (3) unit stride index,
818 // (4) vectorizable right-hand-side value.
819 HInstruction* base = instruction->InputAt(0);
820 HInstruction* index = instruction->InputAt(1);
821 HInstruction* offset = nullptr;
822 if (type == instruction->GetType() &&
823 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bikfa762962017-04-07 11:33:37 -0700824 induction_range_.IsUnitStride(instruction, index, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800825 if (generate_code) {
826 GenerateVecSub(index, offset);
827 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, type);
828 } else {
829 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
830 }
831 return true;
832 }
833 } else if (instruction->IsTypeConversion()) {
834 // Accept particular type conversions.
835 HTypeConversion* conversion = instruction->AsTypeConversion();
836 HInstruction* opa = conversion->InputAt(0);
837 Primitive::Type from = conversion->GetInputType();
838 Primitive::Type to = conversion->GetResultType();
839 if ((to == Primitive::kPrimByte ||
840 to == Primitive::kPrimChar ||
841 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
842 // Accept a "narrowing" type conversion from a "wider" computation for
843 // (1) conversion into final required type,
844 // (2) vectorizable operand,
845 // (3) "wider" operations cannot bring in higher order bits.
846 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
847 if (generate_code) {
848 if (vector_mode_ == kVector) {
849 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
850 } else {
851 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
852 }
853 }
854 return true;
855 }
856 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
857 DCHECK_EQ(to, type);
858 // Accept int to float conversion for
859 // (1) supported int,
860 // (2) vectorizable operand.
861 if (TrySetVectorType(from, &restrictions) &&
862 VectorizeUse(node, opa, generate_code, from, restrictions)) {
863 if (generate_code) {
864 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
865 }
866 return true;
867 }
868 }
869 return false;
870 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
871 // Accept unary operator for vectorizable operand.
872 HInstruction* opa = instruction->InputAt(0);
873 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
874 if (generate_code) {
875 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
876 }
877 return true;
878 }
879 } else if (instruction->IsAdd() || instruction->IsSub() ||
880 instruction->IsMul() || instruction->IsDiv() ||
881 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
882 // Deal with vector restrictions.
883 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
884 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
885 return false;
886 }
887 // Accept binary operator for vectorizable operands.
888 HInstruction* opa = instruction->InputAt(0);
889 HInstruction* opb = instruction->InputAt(1);
890 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
891 VectorizeUse(node, opb, generate_code, type, restrictions)) {
892 if (generate_code) {
893 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
894 }
895 return true;
896 }
897 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700898 // Recognize vectorization idioms.
899 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
900 return true;
901 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800902 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -0700903 HInstruction* opa = instruction->InputAt(0);
904 HInstruction* opb = instruction->InputAt(1);
905 HInstruction* r = opa;
906 bool is_unsigned = false;
Aart Bikf8f5a162017-02-06 15:35:29 -0800907 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
908 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
909 return false; // unsupported instruction
Aart Bik304c8a52017-05-23 11:01:13 -0700910 } else if (HasVectorRestrictions(restrictions, kNoHiBits)) {
911 // Shifts right need extra care to account for higher order bits.
912 // TODO: less likely shr/unsigned and ushr/signed can by flipping signess.
913 if (instruction->IsShr() &&
914 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
915 return false; // reject, unless all operands are sign-extension narrower
916 } else if (instruction->IsUShr() &&
917 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || !is_unsigned)) {
918 return false; // reject, unless all operands are zero-extension narrower
919 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800920 }
921 // Accept shift operator for vectorizable/invariant operands.
922 // TODO: accept symbolic, albeit loop invariant shift factors.
Aart Bik304c8a52017-05-23 11:01:13 -0700923 DCHECK(r != nullptr);
924 if (generate_code && vector_mode_ != kVector) { // de-idiom
925 r = opa;
926 }
Aart Bik50e20d52017-05-05 14:07:29 -0700927 int64_t distance = 0;
Aart Bik304c8a52017-05-23 11:01:13 -0700928 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
Aart Bik50e20d52017-05-05 14:07:29 -0700929 IsInt64AndGet(opb, /*out*/ &distance)) {
Aart Bik65ffd8e2017-05-01 16:50:45 -0700930 // Restrict shift distance to packed data type width.
931 int64_t max_distance = Primitive::ComponentSize(type) * 8;
932 if (0 <= distance && distance < max_distance) {
933 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -0700934 GenerateVecOp(instruction, vector_map_->Get(r), opb, type);
Aart Bik65ffd8e2017-05-01 16:50:45 -0700935 }
936 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800937 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800938 }
939 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700940 // Accept particular intrinsics.
941 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
942 switch (invoke->GetIntrinsic()) {
943 case Intrinsics::kMathAbsInt:
944 case Intrinsics::kMathAbsLong:
945 case Intrinsics::kMathAbsFloat:
946 case Intrinsics::kMathAbsDouble: {
947 // Deal with vector restrictions.
Aart Bik304c8a52017-05-23 11:01:13 -0700948 HInstruction* opa = instruction->InputAt(0);
949 HInstruction* r = opa;
950 bool is_unsigned = false;
951 if (HasVectorRestrictions(restrictions, kNoAbs)) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700952 return false;
Aart Bik304c8a52017-05-23 11:01:13 -0700953 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
954 (!IsNarrowerOperand(opa, type, &r, &is_unsigned) || is_unsigned)) {
955 return false; // reject, unless operand is sign-extension narrower
Aart Bik6daebeb2017-04-03 14:35:41 -0700956 }
957 // Accept ABS(x) for vectorizable operand.
Aart Bik304c8a52017-05-23 11:01:13 -0700958 DCHECK(r != nullptr);
959 if (generate_code && vector_mode_ != kVector) { // de-idiom
960 r = opa;
961 }
962 if (VectorizeUse(node, r, generate_code, type, restrictions)) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700963 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -0700964 GenerateVecOp(instruction, vector_map_->Get(r), nullptr, type);
Aart Bik6daebeb2017-04-03 14:35:41 -0700965 }
966 return true;
967 }
968 return false;
969 }
Aart Bikc8e93c72017-05-10 10:49:22 -0700970 case Intrinsics::kMathMinIntInt:
971 case Intrinsics::kMathMinLongLong:
972 case Intrinsics::kMathMinFloatFloat:
973 case Intrinsics::kMathMinDoubleDouble:
974 case Intrinsics::kMathMaxIntInt:
975 case Intrinsics::kMathMaxLongLong:
976 case Intrinsics::kMathMaxFloatFloat:
977 case Intrinsics::kMathMaxDoubleDouble: {
978 // Deal with vector restrictions.
Nicolas Geoffray92316902017-05-23 08:06:07 +0000979 HInstruction* opa = instruction->InputAt(0);
980 HInstruction* opb = instruction->InputAt(1);
Aart Bik304c8a52017-05-23 11:01:13 -0700981 HInstruction* r = opa;
982 HInstruction* s = opb;
983 bool is_unsigned = false;
984 if (HasVectorRestrictions(restrictions, kNoMinMax)) {
985 return false;
986 } else if (HasVectorRestrictions(restrictions, kNoHiBits) &&
987 !IsNarrowerOperands(opa, opb, type, &r, &s, &is_unsigned)) {
988 return false; // reject, unless all operands are same-extension narrower
989 }
990 // Accept MIN/MAX(x, y) for vectorizable operands.
991 DCHECK(r != nullptr && s != nullptr);
992 if (generate_code && vector_mode_ != kVector) { // de-idiom
993 r = opa;
994 s = opb;
995 }
996 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
997 VectorizeUse(node, s, generate_code, type, restrictions)) {
Aart Bikc8e93c72017-05-10 10:49:22 -0700998 if (generate_code) {
Aart Bik304c8a52017-05-23 11:01:13 -0700999 GenerateVecOp(
1000 instruction, vector_map_->Get(r), vector_map_->Get(s), type, is_unsigned);
Aart Bikc8e93c72017-05-10 10:49:22 -07001001 }
1002 return true;
1003 }
1004 return false;
1005 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001006 default:
1007 return false;
1008 } // switch
Aart Bik281c6812016-08-26 11:31:48 -07001009 }
Aart Bik6b69e0a2017-01-11 10:20:43 -08001010 return false;
Aart Bik281c6812016-08-26 11:31:48 -07001011}
1012
Aart Bikf8f5a162017-02-06 15:35:29 -08001013bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
1014 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
1015 switch (compiler_driver_->GetInstructionSet()) {
1016 case kArm:
1017 case kThumb2:
1018 return false;
1019 case kArm64:
1020 // Allow vectorization for all ARM devices, because Android assumes that
Artem Serovd4bccf12017-04-03 18:47:32 +01001021 // ARMv8 AArch64 always supports advanced SIMD.
Aart Bikf8f5a162017-02-06 15:35:29 -08001022 switch (type) {
1023 case Primitive::kPrimBoolean:
1024 case Primitive::kPrimByte:
Aart Bik304c8a52017-05-23 11:01:13 -07001025 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001026 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -08001027 case Primitive::kPrimChar:
1028 case Primitive::kPrimShort:
Aart Bik304c8a52017-05-23 11:01:13 -07001029 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001030 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -08001031 case Primitive::kPrimInt:
1032 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +01001033 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001034 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001035 *restrictions |= kNoDiv | kNoMul | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001036 return TrySetVectorLength(2);
1037 case Primitive::kPrimFloat:
Artem Serovd4bccf12017-04-03 18:47:32 +01001038 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +01001039 case Primitive::kPrimDouble:
Aart Bikf8f5a162017-02-06 15:35:29 -08001040 return TrySetVectorLength(2);
1041 default:
1042 return false;
1043 }
1044 case kX86:
1045 case kX86_64:
1046 // Allow vectorization for SSE4-enabled X86 devices only (128-bit vectors).
1047 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
1048 switch (type) {
1049 case Primitive::kPrimBoolean:
1050 case Primitive::kPrimByte:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001051 *restrictions |= kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001052 return TrySetVectorLength(16);
1053 case Primitive::kPrimChar:
1054 case Primitive::kPrimShort:
Aart Bikf3e61ee2017-04-12 17:09:20 -07001055 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -08001056 return TrySetVectorLength(8);
1057 case Primitive::kPrimInt:
1058 *restrictions |= kNoDiv;
1059 return TrySetVectorLength(4);
1060 case Primitive::kPrimLong:
Aart Bikc8e93c72017-05-10 10:49:22 -07001061 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs | kNoMinMax;
Aart Bikf8f5a162017-02-06 15:35:29 -08001062 return TrySetVectorLength(2);
1063 case Primitive::kPrimFloat:
Aart Bikc8e93c72017-05-10 10:49:22 -07001064 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001065 return TrySetVectorLength(4);
1066 case Primitive::kPrimDouble:
Aart Bikc8e93c72017-05-10 10:49:22 -07001067 *restrictions |= kNoMinMax; // -0.0 vs +0.0
Aart Bikf8f5a162017-02-06 15:35:29 -08001068 return TrySetVectorLength(2);
1069 default:
1070 break;
1071 } // switch type
1072 }
1073 return false;
1074 case kMips:
1075 case kMips64:
1076 // TODO: implement MIPS SIMD.
1077 return false;
1078 default:
1079 return false;
1080 } // switch instruction set
1081}
1082
1083bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
1084 DCHECK(IsPowerOfTwo(length) && length >= 2u);
1085 // First time set?
1086 if (vector_length_ == 0) {
1087 vector_length_ = length;
1088 }
1089 // Different types are acceptable within a loop-body, as long as all the corresponding vector
1090 // lengths match exactly to obtain a uniform traversal through the vector iteration space
1091 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
1092 return vector_length_ == length;
1093}
1094
1095void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
1096 if (vector_map_->find(org) == vector_map_->end()) {
1097 // In scalar code, just use a self pass-through for scalar invariants
1098 // (viz. expression remains itself).
1099 if (vector_mode_ == kSequential) {
1100 vector_map_->Put(org, org);
1101 return;
1102 }
1103 // In vector code, explicit scalar expansion is needed.
1104 HInstruction* vector = new (global_allocator_) HVecReplicateScalar(
1105 global_allocator_, org, type, vector_length_);
1106 vector_map_->Put(org, Insert(vector_preheader_, vector));
1107 }
1108}
1109
1110void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
1111 if (vector_map_->find(org) == vector_map_->end()) {
1112 HInstruction* subscript = vector_phi_;
1113 if (offset != nullptr) {
1114 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
1115 if (org->IsPhi()) {
1116 Insert(vector_body_, subscript); // lacks layout placeholder
1117 }
1118 }
1119 vector_map_->Put(org, subscript);
1120 }
1121}
1122
1123void HLoopOptimization::GenerateVecMem(HInstruction* org,
1124 HInstruction* opa,
1125 HInstruction* opb,
1126 Primitive::Type type) {
1127 HInstruction* vector = nullptr;
1128 if (vector_mode_ == kVector) {
1129 // Vector store or load.
1130 if (opb != nullptr) {
1131 vector = new (global_allocator_) HVecStore(
1132 global_allocator_, org->InputAt(0), opa, opb, type, vector_length_);
1133 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001134 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001135 vector = new (global_allocator_) HVecLoad(
Aart Bikdb14fcf2017-04-25 15:53:58 -07001136 global_allocator_, org->InputAt(0), opa, type, vector_length_, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001137 }
1138 } else {
1139 // Scalar store or load.
1140 DCHECK(vector_mode_ == kSequential);
1141 if (opb != nullptr) {
1142 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1143 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001144 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1145 vector = new (global_allocator_) HArrayGet(
1146 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001147 }
1148 }
1149 vector_map_->Put(org, vector);
1150}
1151
1152#define GENERATE_VEC(x, y) \
1153 if (vector_mode_ == kVector) { \
1154 vector = (x); \
1155 } else { \
1156 DCHECK(vector_mode_ == kSequential); \
1157 vector = (y); \
1158 } \
1159 break;
1160
1161void HLoopOptimization::GenerateVecOp(HInstruction* org,
1162 HInstruction* opa,
1163 HInstruction* opb,
Aart Bik304c8a52017-05-23 11:01:13 -07001164 Primitive::Type type,
1165 bool is_unsigned) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001166 if (vector_mode_ == kSequential) {
Aart Bik304c8a52017-05-23 11:01:13 -07001167 // Non-converting scalar code follows implicit integral promotion.
1168 if (!org->IsTypeConversion() && (type == Primitive::kPrimBoolean ||
1169 type == Primitive::kPrimByte ||
1170 type == Primitive::kPrimChar ||
1171 type == Primitive::kPrimShort)) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001172 type = Primitive::kPrimInt;
1173 }
1174 }
1175 HInstruction* vector = nullptr;
1176 switch (org->GetKind()) {
1177 case HInstruction::kNeg:
1178 DCHECK(opb == nullptr);
1179 GENERATE_VEC(
1180 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
1181 new (global_allocator_) HNeg(type, opa));
1182 case HInstruction::kNot:
1183 DCHECK(opb == nullptr);
1184 GENERATE_VEC(
1185 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1186 new (global_allocator_) HNot(type, opa));
1187 case HInstruction::kBooleanNot:
1188 DCHECK(opb == nullptr);
1189 GENERATE_VEC(
1190 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1191 new (global_allocator_) HBooleanNot(opa));
1192 case HInstruction::kTypeConversion:
1193 DCHECK(opb == nullptr);
1194 GENERATE_VEC(
1195 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
1196 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
1197 case HInstruction::kAdd:
1198 GENERATE_VEC(
1199 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
1200 new (global_allocator_) HAdd(type, opa, opb));
1201 case HInstruction::kSub:
1202 GENERATE_VEC(
1203 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
1204 new (global_allocator_) HSub(type, opa, opb));
1205 case HInstruction::kMul:
1206 GENERATE_VEC(
1207 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
1208 new (global_allocator_) HMul(type, opa, opb));
1209 case HInstruction::kDiv:
1210 GENERATE_VEC(
1211 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
1212 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
1213 case HInstruction::kAnd:
1214 GENERATE_VEC(
1215 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
1216 new (global_allocator_) HAnd(type, opa, opb));
1217 case HInstruction::kOr:
1218 GENERATE_VEC(
1219 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
1220 new (global_allocator_) HOr(type, opa, opb));
1221 case HInstruction::kXor:
1222 GENERATE_VEC(
1223 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
1224 new (global_allocator_) HXor(type, opa, opb));
1225 case HInstruction::kShl:
1226 GENERATE_VEC(
1227 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
1228 new (global_allocator_) HShl(type, opa, opb));
1229 case HInstruction::kShr:
1230 GENERATE_VEC(
1231 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
1232 new (global_allocator_) HShr(type, opa, opb));
1233 case HInstruction::kUShr:
1234 GENERATE_VEC(
1235 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
1236 new (global_allocator_) HUShr(type, opa, opb));
1237 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001238 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1239 if (vector_mode_ == kVector) {
1240 switch (invoke->GetIntrinsic()) {
1241 case Intrinsics::kMathAbsInt:
1242 case Intrinsics::kMathAbsLong:
1243 case Intrinsics::kMathAbsFloat:
1244 case Intrinsics::kMathAbsDouble:
1245 DCHECK(opb == nullptr);
1246 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1247 break;
Aart Bikc8e93c72017-05-10 10:49:22 -07001248 case Intrinsics::kMathMinIntInt:
1249 case Intrinsics::kMathMinLongLong:
1250 case Intrinsics::kMathMinFloatFloat:
1251 case Intrinsics::kMathMinDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001252 vector = new (global_allocator_)
1253 HVecMin(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1254 break;
1255 }
1256 case Intrinsics::kMathMaxIntInt:
1257 case Intrinsics::kMathMaxLongLong:
1258 case Intrinsics::kMathMaxFloatFloat:
1259 case Intrinsics::kMathMaxDoubleDouble: {
Aart Bikc8e93c72017-05-10 10:49:22 -07001260 vector = new (global_allocator_)
1261 HVecMax(global_allocator_, opa, opb, type, vector_length_, is_unsigned);
1262 break;
1263 }
Aart Bik6daebeb2017-04-03 14:35:41 -07001264 default:
1265 LOG(FATAL) << "Unsupported SIMD intrinsic";
1266 UNREACHABLE();
1267 } // switch invoke
1268 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001269 // In scalar code, simply clone the method invoke, and replace its operands with the
1270 // corresponding new scalar instructions in the loop. The instruction will get an
1271 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001272 DCHECK(vector_mode_ == kSequential);
1273 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1274 global_allocator_,
1275 invoke->GetNumberOfArguments(),
1276 invoke->GetType(),
1277 invoke->GetDexPc(),
1278 invoke->GetDexMethodIndex(),
1279 invoke->GetResolvedMethod(),
1280 invoke->GetDispatchInfo(),
1281 invoke->GetInvokeType(),
1282 invoke->GetTargetMethod(),
1283 invoke->GetClinitCheckRequirement());
1284 HInputsRef inputs = invoke->GetInputs();
1285 for (size_t index = 0; index < inputs.size(); ++index) {
1286 new_invoke->SetArgumentAt(index, vector_map_->Get(inputs[index]));
1287 }
Aart Bik98990262017-04-10 13:15:57 -07001288 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1289 kNeedsEnvironmentOrCache,
1290 kNoSideEffects,
1291 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001292 vector = new_invoke;
1293 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001294 break;
1295 }
1296 default:
1297 break;
1298 } // switch
1299 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1300 vector_map_->Put(org, vector);
1301}
1302
1303#undef GENERATE_VEC
1304
1305//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001306// Vectorization idioms.
1307//
1308
1309// Method recognizes the following idioms:
1310// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1311// regular halving add (a + b) >> 1 for unsigned/signed operands a, b
1312// Provided that the operands are promoted to a wider form to do the arithmetic and
1313// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1314// implementation that operates directly in narrower form (plus one extra bit).
1315// TODO: current version recognizes implicit byte/short/char widening only;
1316// explicit widening from int to long could be added later.
1317bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1318 HInstruction* instruction,
1319 bool generate_code,
1320 Primitive::Type type,
1321 uint64_t restrictions) {
1322 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
Aart Bik304c8a52017-05-23 11:01:13 -07001323 // (note whether the sign bit in wider precision is shifted in has no effect
Aart Bikf3e61ee2017-04-12 17:09:20 -07001324 // on the narrow precision computed by the idiom).
Aart Bik5f805002017-05-16 16:42:41 -07001325 int64_t distance = 0;
Aart Bikf3e61ee2017-04-12 17:09:20 -07001326 if ((instruction->IsShr() ||
1327 instruction->IsUShr()) &&
Aart Bik5f805002017-05-16 16:42:41 -07001328 IsInt64AndGet(instruction->InputAt(1), /*out*/ &distance) && distance == 1) {
1329 // Test for (a + b + c) >> 1 for optional constant c.
1330 HInstruction* a = nullptr;
1331 HInstruction* b = nullptr;
1332 int64_t c = 0;
1333 if (IsAddConst(instruction->InputAt(0), /*out*/ &a, /*out*/ &b, /*out*/ &c)) {
Aart Bik304c8a52017-05-23 11:01:13 -07001334 DCHECK(a != nullptr && b != nullptr);
Aart Bik5f805002017-05-16 16:42:41 -07001335 // Accept c == 1 (rounded) or c == 0 (not rounded).
1336 bool is_rounded = false;
1337 if (c == 1) {
1338 is_rounded = true;
1339 } else if (c != 0) {
1340 return false;
1341 }
1342 // Accept consistent zero or sign extension on operands a and b.
Aart Bikf3e61ee2017-04-12 17:09:20 -07001343 HInstruction* r = nullptr;
1344 HInstruction* s = nullptr;
1345 bool is_unsigned = false;
Aart Bik304c8a52017-05-23 11:01:13 -07001346 if (!IsNarrowerOperands(a, b, type, &r, &s, &is_unsigned)) {
Aart Bikf3e61ee2017-04-12 17:09:20 -07001347 return false;
1348 }
1349 // Deal with vector restrictions.
1350 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1351 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1352 return false;
1353 }
1354 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1355 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
1356 DCHECK(r != nullptr && s != nullptr);
Aart Bik304c8a52017-05-23 11:01:13 -07001357 if (generate_code && vector_mode_ != kVector) { // de-idiom
1358 r = instruction->InputAt(0);
1359 s = instruction->InputAt(1);
1360 }
Aart Bikf3e61ee2017-04-12 17:09:20 -07001361 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1362 VectorizeUse(node, s, generate_code, type, restrictions)) {
1363 if (generate_code) {
1364 if (vector_mode_ == kVector) {
1365 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1366 global_allocator_,
1367 vector_map_->Get(r),
1368 vector_map_->Get(s),
1369 type,
1370 vector_length_,
1371 is_unsigned,
1372 is_rounded));
1373 } else {
Aart Bik304c8a52017-05-23 11:01:13 -07001374 GenerateVecOp(instruction, vector_map_->Get(r), vector_map_->Get(s), type);
Aart Bikf3e61ee2017-04-12 17:09:20 -07001375 }
1376 }
1377 return true;
1378 }
1379 }
1380 }
1381 return false;
1382}
1383
1384//
Aart Bikf8f5a162017-02-06 15:35:29 -08001385// Helpers.
1386//
1387
1388bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
1389 DCHECK(iset_->empty());
Aart Bikcc42be02016-10-20 16:14:16 -07001390 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1391 if (set != nullptr) {
1392 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001393 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001394 // each instruction is removable and, when restrict uses are requested, other than for phi,
1395 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001396 if (!i->IsInBlock()) {
1397 continue;
1398 } else if (!i->IsRemovable()) {
1399 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001400 } else if (i != phi && restrict_uses) {
Aart Bikcc42be02016-10-20 16:14:16 -07001401 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1402 if (set->find(use.GetUser()) == set->end()) {
1403 return false;
1404 }
1405 }
1406 }
Aart Bike3dedc52016-11-02 17:50:27 -07001407 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001408 }
Aart Bikcc42be02016-10-20 16:14:16 -07001409 return true;
1410 }
1411 return false;
1412}
1413
1414// Find: phi: Phi(init, addsub)
1415// s: SuspendCheck
1416// c: Condition(phi, bound)
1417// i: If(c)
1418// TODO: Find a less pattern matching approach?
Aart Bikf8f5a162017-02-06 15:35:29 -08001419bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block) {
Aart Bikcc42be02016-10-20 16:14:16 -07001420 DCHECK(iset_->empty());
1421 HInstruction* phi = block->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -08001422 if (phi != nullptr &&
1423 phi->GetNext() == nullptr &&
1424 TrySetPhiInduction(phi->AsPhi(), /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001425 HInstruction* s = block->GetFirstInstruction();
1426 if (s != nullptr && s->IsSuspendCheck()) {
1427 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07001428 if (c != nullptr &&
1429 c->IsCondition() &&
1430 c->GetUses().HasExactlyOneElement() && // only used for termination
1431 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07001432 HInstruction* i = c->GetNext();
1433 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1434 iset_->insert(c);
1435 iset_->insert(s);
1436 return true;
1437 }
1438 }
1439 }
1440 }
1441 return false;
1442}
1443
1444bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001445 if (!block->GetPhis().IsEmpty()) {
1446 return false;
1447 }
1448 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1449 HInstruction* instruction = it.Current();
1450 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1451 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001452 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001453 }
1454 return true;
1455}
1456
1457bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1458 HInstruction* instruction) {
1459 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1460 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1461 return true;
1462 }
Aart Bikcc42be02016-10-20 16:14:16 -07001463 }
1464 return false;
1465}
1466
Aart Bik482095d2016-10-10 15:39:10 -07001467bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001468 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001469 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001470 /*out*/ int32_t* use_count) {
1471 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1472 HInstruction* user = use.GetUser();
1473 if (iset_->find(user) == iset_->end()) { // not excluded?
1474 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001475 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001476 // If collect_loop_uses is set, simply keep adding those uses to the set.
1477 // Otherwise, reject uses inside the loop that were not already in the set.
1478 if (collect_loop_uses) {
1479 iset_->insert(user);
1480 continue;
1481 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001482 return false;
1483 }
1484 ++*use_count;
1485 }
1486 }
1487 return true;
1488}
1489
Aart Bik807868e2016-11-03 17:51:43 -07001490bool HLoopOptimization::TryReplaceWithLastValue(HInstruction* instruction, HBasicBlock* block) {
1491 // Try to replace outside uses with the last value. Environment uses can consume this
1492 // value too, since any first true use is outside the loop (although this may imply
1493 // that de-opting may look "ahead" a bit on the phi value). If there are only environment
1494 // uses, the value is dropped altogether, since the computations have no effect.
1495 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001496 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
1497 const HUseList<HInstruction*>& uses = instruction->GetUses();
1498 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1499 HInstruction* user = it->GetUser();
1500 size_t index = it->GetIndex();
1501 ++it; // increment before replacing
1502 if (iset_->find(user) == iset_->end()) { // not excluded?
1503 user->ReplaceInput(replacement, index);
1504 induction_range_.Replace(user, instruction, replacement); // update induction
1505 }
1506 }
1507 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1508 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1509 HEnvironment* user = it->GetUser();
1510 size_t index = it->GetIndex();
1511 ++it; // increment before replacing
1512 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
1513 user->RemoveAsUserOfInput(index);
1514 user->SetRawEnvAt(index, replacement);
1515 replacement->AddEnvUseAt(user, index);
1516 }
1517 }
1518 induction_simplication_count_++;
Aart Bik807868e2016-11-03 17:51:43 -07001519 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001520 }
Aart Bik807868e2016-11-03 17:51:43 -07001521 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001522}
1523
Aart Bikf8f5a162017-02-06 15:35:29 -08001524bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1525 HInstruction* instruction,
1526 HBasicBlock* block,
1527 bool collect_loop_uses) {
1528 // Assigning the last value is always successful if there are no uses.
1529 // Otherwise, it succeeds in a no early-exit loop by generating the
1530 // proper last value assignment.
1531 int32_t use_count = 0;
1532 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
1533 (use_count == 0 ||
1534 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(instruction, block)));
1535}
1536
Aart Bik6b69e0a2017-01-11 10:20:43 -08001537void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
1538 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
1539 HInstruction* instruction = i.Current();
1540 if (instruction->IsDeadAndRemovable()) {
1541 simplified_ = true;
1542 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
1543 }
1544 }
1545}
1546
Aart Bik281c6812016-08-26 11:31:48 -07001547} // namespace art