blob: bbc55dd16f8b0b1dbc5409002aef21ce873e45e0 [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;
74 if (IsInt64AndGet(instruction, &value)) {
75 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;
122 if (IsInt64AndGet(instruction, &value)) {
123 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 Bikf8f5a162017-02-06 15:35:29 -0800176// Test vector restrictions.
177static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
178 return (restrictions & tested) != 0;
179}
180
Aart Bikf3e61ee2017-04-12 17:09:20 -0700181// Insert an instruction.
Aart Bikf8f5a162017-02-06 15:35:29 -0800182static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
183 DCHECK(block != nullptr);
184 DCHECK(instruction != nullptr);
185 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
186 return instruction;
187}
188
Aart Bik281c6812016-08-26 11:31:48 -0700189//
190// Class methods.
191//
192
193HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -0800194 CompilerDriver* compiler_driver,
Aart Bik281c6812016-08-26 11:31:48 -0700195 HInductionVarAnalysis* induction_analysis)
196 : HOptimization(graph, kLoopOptimizationPassName),
Aart Bik92685a82017-03-06 11:13:43 -0800197 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -0700198 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -0700199 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -0800200 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -0700201 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -0700202 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -0700203 iset_(nullptr),
Aart Bikdf7822e2016-12-06 10:05:30 -0800204 induction_simplication_count_(0),
Aart Bikf8f5a162017-02-06 15:35:29 -0800205 simplified_(false),
206 vector_length_(0),
207 vector_refs_(nullptr),
208 vector_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -0700209}
210
211void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800212 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700213 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800214 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700215 return;
216 }
217
Aart Bik96202302016-10-04 17:33:56 -0700218 // Phase-local allocator that draws from the global pool. Since the allocator
219 // itself resides on the stack, it is destructed on exiting Run(), which
220 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800221 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700222 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100223
Aart Bik96202302016-10-04 17:33:56 -0700224 // Perform loop optimizations.
225 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800226 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800227 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800228 }
229
Aart Bik96202302016-10-04 17:33:56 -0700230 // Detach.
231 loop_allocator_ = nullptr;
232 last_loop_ = top_loop_ = nullptr;
233}
234
235void HLoopOptimization::LocalRun() {
236 // Build the linear order using the phase-local allocator. This step enables building
237 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
238 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
239 LinearizeGraph(graph_, loop_allocator_, &linear_order);
240
Aart Bik281c6812016-08-26 11:31:48 -0700241 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700242 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700243 if (block->IsLoopHeader()) {
244 AddLoop(block->GetLoopInformation());
245 }
246 }
Aart Bik96202302016-10-04 17:33:56 -0700247
Aart Bik8c4a8542016-10-06 11:36:57 -0700248 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800249 // temporary data structures using the phase-local allocator. All new HIR
250 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700251 if (top_loop_ != nullptr) {
252 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800253 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
254 ArenaSafeMap<HInstruction*, HInstruction*> map(
255 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
256 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700257 iset_ = &iset;
Aart Bikf8f5a162017-02-06 15:35:29 -0800258 vector_refs_ = &refs;
259 vector_map_ = &map;
260 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700261 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800262 // Detach.
263 iset_ = nullptr;
264 vector_refs_ = nullptr;
265 vector_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700266 }
Aart Bik281c6812016-08-26 11:31:48 -0700267}
268
269void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
270 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800271 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700272 if (last_loop_ == nullptr) {
273 // First loop.
274 DCHECK(top_loop_ == nullptr);
275 last_loop_ = top_loop_ = node;
276 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
277 // Inner loop.
278 node->outer = last_loop_;
279 DCHECK(last_loop_->inner == nullptr);
280 last_loop_ = last_loop_->inner = node;
281 } else {
282 // Subsequent loop.
283 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
284 last_loop_ = last_loop_->outer;
285 }
286 node->outer = last_loop_->outer;
287 node->previous = last_loop_;
288 DCHECK(last_loop_->next == nullptr);
289 last_loop_ = last_loop_->next = node;
290 }
291}
292
293void HLoopOptimization::RemoveLoop(LoopNode* node) {
294 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700295 DCHECK(node->inner == nullptr);
296 if (node->previous != nullptr) {
297 // Within sequence.
298 node->previous->next = node->next;
299 if (node->next != nullptr) {
300 node->next->previous = node->previous;
301 }
302 } else {
303 // First of sequence.
304 if (node->outer != nullptr) {
305 node->outer->inner = node->next;
306 } else {
307 top_loop_ = node->next;
308 }
309 if (node->next != nullptr) {
310 node->next->outer = node->outer;
311 node->next->previous = nullptr;
312 }
313 }
Aart Bik281c6812016-08-26 11:31:48 -0700314}
315
316void HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
317 for ( ; node != nullptr; node = node->next) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800318 // Visit inner loops first.
Aart Bikf8f5a162017-02-06 15:35:29 -0800319 uint32_t current_induction_simplification_count = induction_simplication_count_;
Aart Bik281c6812016-08-26 11:31:48 -0700320 if (node->inner != nullptr) {
321 TraverseLoopsInnerToOuter(node->inner);
322 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800323 // Recompute induction information of this loop if the induction
324 // of any inner loop has been simplified.
Aart Bik482095d2016-10-10 15:39:10 -0700325 if (current_induction_simplification_count != induction_simplication_count_) {
326 induction_range_.ReVisit(node->loop_info);
327 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800328 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800329 // Note that since each simplification consists of eliminating code (without
330 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800331 do {
332 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800333 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800334 SimplifyBlocks(node);
Aart Bikdf7822e2016-12-06 10:05:30 -0800335 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800336 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700337 if (node->inner == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800338 OptimizeInnerLoop(node);
Aart Bik9abf8942016-10-14 09:49:42 -0700339 }
Aart Bik281c6812016-08-26 11:31:48 -0700340 }
341}
342
Aart Bikf8f5a162017-02-06 15:35:29 -0800343//
344// Optimization.
345//
346
Aart Bik281c6812016-08-26 11:31:48 -0700347void HLoopOptimization::SimplifyInduction(LoopNode* node) {
348 HBasicBlock* header = node->loop_info->GetHeader();
349 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700350 // Scan the phis in the header to find opportunities to simplify an induction
351 // cycle that is only used outside the loop. Replace these uses, if any, with
352 // the last value and remove the induction cycle.
353 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
354 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700355 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
356 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800357 iset_->clear(); // prepare phi induction
358 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
359 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik8c4a8542016-10-06 11:36:57 -0700360 for (HInstruction* i : *iset_) {
361 RemoveFromCycle(i);
Aart Bik281c6812016-08-26 11:31:48 -0700362 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800363 simplified_ = true;
Aart Bik482095d2016-10-10 15:39:10 -0700364 }
365 }
366}
367
368void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800369 // Iterate over all basic blocks in the loop-body.
370 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
371 HBasicBlock* block = it.Current();
372 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800373 RemoveDeadInstructions(block->GetPhis());
374 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800375 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800376 if (block->GetPredecessors().size() == 1 &&
377 block->GetSuccessors().size() == 1 &&
378 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800379 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800380 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800381 } else if (block->GetSuccessors().size() == 2) {
382 // Trivial if block can be bypassed to either branch.
383 HBasicBlock* succ0 = block->GetSuccessors()[0];
384 HBasicBlock* succ1 = block->GetSuccessors()[1];
385 HBasicBlock* meet0 = nullptr;
386 HBasicBlock* meet1 = nullptr;
387 if (succ0 != succ1 &&
388 IsGotoBlock(succ0, &meet0) &&
389 IsGotoBlock(succ1, &meet1) &&
390 meet0 == meet1 && // meets again
391 meet0 != block && // no self-loop
392 meet0->GetPhis().IsEmpty()) { // not used for merging
393 simplified_ = true;
394 succ0->DisconnectAndDelete();
395 if (block->Dominates(meet0)) {
396 block->RemoveDominatedBlock(meet0);
397 succ1->AddDominatedBlock(meet0);
398 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700399 }
Aart Bik482095d2016-10-10 15:39:10 -0700400 }
Aart Bik281c6812016-08-26 11:31:48 -0700401 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800402 }
Aart Bik281c6812016-08-26 11:31:48 -0700403}
404
Aart Bikf8f5a162017-02-06 15:35:29 -0800405void HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700406 HBasicBlock* header = node->loop_info->GetHeader();
407 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700408 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800409 int64_t trip_count = 0;
410 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
411 return;
Aart Bik9abf8942016-10-14 09:49:42 -0700412 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800413
Aart Bik281c6812016-08-26 11:31:48 -0700414 // Ensure there is only a single loop-body (besides the header).
415 HBasicBlock* body = nullptr;
416 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
417 if (it.Current() != header) {
418 if (body != nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800419 return;
Aart Bik281c6812016-08-26 11:31:48 -0700420 }
421 body = it.Current();
422 }
423 }
424 // Ensure there is only a single exit point.
425 if (header->GetSuccessors().size() != 2) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800426 return;
Aart Bik281c6812016-08-26 11:31:48 -0700427 }
428 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
429 ? header->GetSuccessors()[1]
430 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700431 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700432 if (exit->GetPredecessors().size() != 1) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800433 return;
Aart Bik281c6812016-08-26 11:31:48 -0700434 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800435 // Detect either an empty loop (no side effects other than plain iteration) or
436 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
437 // with the last value and remove the loop, possibly after unrolling its body.
438 HInstruction* phi = header->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800439 iset_->clear(); // prepare phi induction
440 if (TrySetSimpleLoopHeader(header)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800441 bool is_empty = IsEmptyBody(body);
Aart Bikf8f5a162017-02-06 15:35:29 -0800442 if ((is_empty || trip_count == 1) &&
443 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800444 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800445 // Unroll the loop-body, which sees initial value of the index.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800446 phi->ReplaceWith(phi->InputAt(0));
447 preheader->MergeInstructionsWith(body);
448 }
449 body->DisconnectAndDelete();
450 exit->RemovePredecessor(header);
451 header->RemoveSuccessor(exit);
452 header->RemoveDominatedBlock(exit);
453 header->DisconnectAndDelete();
454 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800455 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800456 preheader->AddDominatedBlock(exit);
457 exit->SetDominator(preheader);
458 RemoveLoop(node); // update hierarchy
Aart Bikf8f5a162017-02-06 15:35:29 -0800459 return;
460 }
461 }
462
463 // Vectorize loop, if possible and valid.
464 if (kEnableVectorization) {
465 iset_->clear(); // prepare phi induction
466 if (TrySetSimpleLoopHeader(header) &&
467 CanVectorize(node, body, trip_count) &&
468 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
469 Vectorize(node, body, exit, trip_count);
470 graph_->SetHasSIMD(true); // flag SIMD usage
471 return;
472 }
473 }
474}
475
476//
477// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
478// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
479// Intel Press, June, 2004 (http://www.aartbik.com/).
480//
481
482bool HLoopOptimization::CanVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
483 // Reset vector bookkeeping.
484 vector_length_ = 0;
485 vector_refs_->clear();
486 vector_runtime_test_a_ =
487 vector_runtime_test_b_= nullptr;
488
489 // Phis in the loop-body prevent vectorization.
490 if (!block->GetPhis().IsEmpty()) {
491 return false;
492 }
493
494 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
495 // occurrence, which allows passing down attributes down the use tree.
496 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
497 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
498 return false; // failure to vectorize a left-hand-side
499 }
500 }
501
502 // Heuristics. Does vectorization seem profitable?
503 // TODO: refine
504 if (vector_length_ == 0) {
505 return false; // nothing found
506 } else if (0 < trip_count && trip_count < vector_length_) {
507 return false; // insufficient iterations
508 }
509
510 // Data dependence analysis. Find each pair of references with same type, where
511 // at least one is a write. Each such pair denotes a possible data dependence.
512 // This analysis exploits the property that differently typed arrays cannot be
513 // aliased, as well as the property that references either point to the same
514 // array or to two completely disjoint arrays, i.e., no partial aliasing.
515 // Other than a few simply heuristics, no detailed subscript analysis is done.
516 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
517 for (auto j = i; ++j != vector_refs_->end(); ) {
518 if (i->type == j->type && (i->lhs || j->lhs)) {
519 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
520 HInstruction* a = i->base;
521 HInstruction* b = j->base;
522 HInstruction* x = i->offset;
523 HInstruction* y = j->offset;
524 if (a == b) {
525 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
526 // Conservatively assume a loop-carried data dependence otherwise, and reject.
527 if (x != y) {
528 return false;
529 }
530 } else {
531 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
532 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
533 // generating an explicit a != b disambiguation runtime test on the two references.
534 if (x != y) {
535 // For now, we reject after one test to avoid excessive overhead.
536 if (vector_runtime_test_a_ != nullptr) {
537 return false;
538 }
539 vector_runtime_test_a_ = a;
540 vector_runtime_test_b_ = b;
541 }
542 }
543 }
544 }
545 }
546
547 // Success!
548 return true;
549}
550
551void HLoopOptimization::Vectorize(LoopNode* node,
552 HBasicBlock* block,
553 HBasicBlock* exit,
554 int64_t trip_count) {
555 Primitive::Type induc_type = Primitive::kPrimInt;
556 HBasicBlock* header = node->loop_info->GetHeader();
557 HBasicBlock* preheader = node->loop_info->GetPreHeader();
558
559 // A cleanup is needed for any unknown trip count or for a known trip count
560 // with remainder iterations after vectorization.
561 bool needs_cleanup = trip_count == 0 || (trip_count % vector_length_) != 0;
562
563 // Adjust vector bookkeeping.
564 iset_->clear(); // prepare phi induction
565 bool is_simple_loop_header = TrySetSimpleLoopHeader(header); // fills iset_
566 DCHECK(is_simple_loop_header);
567
568 // Generate preheader:
569 // stc = <trip-count>;
570 // vtc = stc - stc % VL;
571 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
572 HInstruction* vtc = stc;
573 if (needs_cleanup) {
574 DCHECK(IsPowerOfTwo(vector_length_));
575 HInstruction* rem = Insert(
576 preheader, new (global_allocator_) HAnd(induc_type,
577 stc,
578 graph_->GetIntConstant(vector_length_ - 1)));
579 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
580 }
581
582 // Generate runtime disambiguation test:
583 // vtc = a != b ? vtc : 0;
584 if (vector_runtime_test_a_ != nullptr) {
585 HInstruction* rt = Insert(
586 preheader,
587 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
588 vtc = Insert(preheader,
589 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
590 needs_cleanup = true;
591 }
592
593 // Generate vector loop:
594 // for (i = 0; i < vtc; i += VL)
595 // <vectorized-loop-body>
596 vector_mode_ = kVector;
597 GenerateNewLoop(node,
598 block,
599 graph_->TransformLoopForVectorization(header, block, exit),
600 graph_->GetIntConstant(0),
601 vtc,
602 graph_->GetIntConstant(vector_length_));
603 HLoopInformation* vloop = vector_header_->GetLoopInformation();
604
605 // Generate cleanup loop, if needed:
606 // for ( ; i < stc; i += 1)
607 // <loop-body>
608 if (needs_cleanup) {
609 vector_mode_ = kSequential;
610 GenerateNewLoop(node,
611 block,
612 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
613 vector_phi_,
614 stc,
615 graph_->GetIntConstant(1));
616 }
617
618 // Remove the original loop by disconnecting the body block
619 // and removing all instructions from the header.
620 block->DisconnectAndDelete();
621 while (!header->GetFirstInstruction()->IsGoto()) {
622 header->RemoveInstruction(header->GetFirstInstruction());
623 }
624 // Update loop hierarchy: the old header now resides in the
625 // same outer loop as the old preheader.
626 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
627 node->loop_info = vloop;
628}
629
630void HLoopOptimization::GenerateNewLoop(LoopNode* node,
631 HBasicBlock* block,
632 HBasicBlock* new_preheader,
633 HInstruction* lo,
634 HInstruction* hi,
635 HInstruction* step) {
636 Primitive::Type induc_type = Primitive::kPrimInt;
637 // Prepare new loop.
638 vector_map_->clear();
639 vector_preheader_ = new_preheader,
640 vector_header_ = vector_preheader_->GetSingleSuccessor();
641 vector_body_ = vector_header_->GetSuccessors()[1];
642 vector_phi_ = new (global_allocator_) HPhi(global_allocator_,
643 kNoRegNumber,
644 0,
645 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700646 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800647 // for (i = lo; i < hi; i += step)
648 // <loop-body>
649 HInstruction* cond = new (global_allocator_) HAboveOrEqual(vector_phi_, hi);
650 vector_header_->AddPhi(vector_phi_);
651 vector_header_->AddInstruction(cond);
652 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bikf8f5a162017-02-06 15:35:29 -0800653 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
654 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
655 DCHECK(vectorized_def);
656 }
Aart Bik24b905f2017-04-06 09:59:06 -0700657 // Generate body from the instruction map, but in original program order.
Aart Bikb07d1bc2017-04-05 10:03:15 -0700658 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
Aart Bikf8f5a162017-02-06 15:35:29 -0800659 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
660 auto i = vector_map_->find(it.Current());
661 if (i != vector_map_->end() && !i->second->IsInBlock()) {
Aart Bik24b905f2017-04-06 09:59:06 -0700662 Insert(vector_body_, i->second);
663 // Deal with instructions that need an environment, such as the scalar intrinsics.
Aart Bikf8f5a162017-02-06 15:35:29 -0800664 if (i->second->NeedsEnvironment()) {
Aart Bikb07d1bc2017-04-05 10:03:15 -0700665 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800666 }
667 }
668 }
669 // Finalize increment and phi.
670 HInstruction* inc = new (global_allocator_) HAdd(induc_type, vector_phi_, step);
671 vector_phi_->AddInput(lo);
672 vector_phi_->AddInput(Insert(vector_body_, inc));
673}
674
675// TODO: accept reductions at left-hand-side, mixed-type store idioms, etc.
676bool HLoopOptimization::VectorizeDef(LoopNode* node,
677 HInstruction* instruction,
678 bool generate_code) {
679 // Accept a left-hand-side array base[index] for
680 // (1) supported vector type,
681 // (2) loop-invariant base,
682 // (3) unit stride index,
683 // (4) vectorizable right-hand-side value.
684 uint64_t restrictions = kNone;
685 if (instruction->IsArraySet()) {
686 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
687 HInstruction* base = instruction->InputAt(0);
688 HInstruction* index = instruction->InputAt(1);
689 HInstruction* value = instruction->InputAt(2);
690 HInstruction* offset = nullptr;
691 if (TrySetVectorType(type, &restrictions) &&
692 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bikfa762962017-04-07 11:33:37 -0700693 induction_range_.IsUnitStride(instruction, index, &offset) &&
Aart Bikf8f5a162017-02-06 15:35:29 -0800694 VectorizeUse(node, value, generate_code, type, restrictions)) {
695 if (generate_code) {
696 GenerateVecSub(index, offset);
697 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), type);
698 } else {
699 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
700 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800701 return true;
702 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800703 return false;
704 }
705 // Branch back okay.
706 if (instruction->IsGoto()) {
707 return true;
708 }
709 // Otherwise accept only expressions with no effects outside the immediate loop-body.
710 // Note that actual uses are inspected during right-hand-side tree traversal.
711 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
712}
713
714// TODO: more operations and intrinsics, detect saturation arithmetic, etc.
715bool HLoopOptimization::VectorizeUse(LoopNode* node,
716 HInstruction* instruction,
717 bool generate_code,
718 Primitive::Type type,
719 uint64_t restrictions) {
720 // Accept anything for which code has already been generated.
721 if (generate_code) {
722 if (vector_map_->find(instruction) != vector_map_->end()) {
723 return true;
724 }
725 }
726 // Continue the right-hand-side tree traversal, passing in proper
727 // types and vector restrictions along the way. During code generation,
728 // all new nodes are drawn from the global allocator.
729 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
730 // Accept invariant use, using scalar expansion.
731 if (generate_code) {
732 GenerateVecInv(instruction, type);
733 }
734 return true;
735 } else if (instruction->IsArrayGet()) {
736 // Accept a right-hand-side array base[index] for
737 // (1) exact matching vector type,
738 // (2) loop-invariant base,
739 // (3) unit stride index,
740 // (4) vectorizable right-hand-side value.
741 HInstruction* base = instruction->InputAt(0);
742 HInstruction* index = instruction->InputAt(1);
743 HInstruction* offset = nullptr;
744 if (type == instruction->GetType() &&
745 node->loop_info->IsDefinedOutOfTheLoop(base) &&
Aart Bikfa762962017-04-07 11:33:37 -0700746 induction_range_.IsUnitStride(instruction, index, &offset)) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800747 if (generate_code) {
748 GenerateVecSub(index, offset);
749 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, type);
750 } else {
751 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
752 }
753 return true;
754 }
755 } else if (instruction->IsTypeConversion()) {
756 // Accept particular type conversions.
757 HTypeConversion* conversion = instruction->AsTypeConversion();
758 HInstruction* opa = conversion->InputAt(0);
759 Primitive::Type from = conversion->GetInputType();
760 Primitive::Type to = conversion->GetResultType();
761 if ((to == Primitive::kPrimByte ||
762 to == Primitive::kPrimChar ||
763 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
764 // Accept a "narrowing" type conversion from a "wider" computation for
765 // (1) conversion into final required type,
766 // (2) vectorizable operand,
767 // (3) "wider" operations cannot bring in higher order bits.
768 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
769 if (generate_code) {
770 if (vector_mode_ == kVector) {
771 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
772 } else {
773 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
774 }
775 }
776 return true;
777 }
778 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
779 DCHECK_EQ(to, type);
780 // Accept int to float conversion for
781 // (1) supported int,
782 // (2) vectorizable operand.
783 if (TrySetVectorType(from, &restrictions) &&
784 VectorizeUse(node, opa, generate_code, from, restrictions)) {
785 if (generate_code) {
786 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
787 }
788 return true;
789 }
790 }
791 return false;
792 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
793 // Accept unary operator for vectorizable operand.
794 HInstruction* opa = instruction->InputAt(0);
795 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
796 if (generate_code) {
797 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
798 }
799 return true;
800 }
801 } else if (instruction->IsAdd() || instruction->IsSub() ||
802 instruction->IsMul() || instruction->IsDiv() ||
803 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
804 // Deal with vector restrictions.
805 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
806 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
807 return false;
808 }
809 // Accept binary operator for vectorizable operands.
810 HInstruction* opa = instruction->InputAt(0);
811 HInstruction* opb = instruction->InputAt(1);
812 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
813 VectorizeUse(node, opb, generate_code, type, restrictions)) {
814 if (generate_code) {
815 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
816 }
817 return true;
818 }
819 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
Aart Bikf3e61ee2017-04-12 17:09:20 -0700820 // Recognize vectorization idioms.
821 if (VectorizeHalvingAddIdiom(node, instruction, generate_code, type, restrictions)) {
822 return true;
823 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800824 // Deal with vector restrictions.
825 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
826 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
827 return false; // unsupported instruction
828 } else if ((instruction->IsShr() || instruction->IsUShr()) &&
829 HasVectorRestrictions(restrictions, kNoHiBits)) {
830 return false; // hibits may impact lobits; TODO: we can do better!
831 }
832 // Accept shift operator for vectorizable/invariant operands.
833 // TODO: accept symbolic, albeit loop invariant shift factors.
834 HInstruction* opa = instruction->InputAt(0);
835 HInstruction* opb = instruction->InputAt(1);
Aart Bik65ffd8e2017-05-01 16:50:45 -0700836 int64_t value = 0;
837 if (VectorizeUse(node, opa, generate_code, type, restrictions) && IsInt64AndGet(opb, &value)) {
838 // Make sure shift distance only looks at lower bits, as defined for sequential shifts.
839 int64_t mask = (instruction->GetType() == Primitive::kPrimLong)
840 ? kMaxLongShiftDistance
841 : kMaxIntShiftDistance;
842 int64_t distance = value & mask;
843 // Restrict shift distance to packed data type width.
844 int64_t max_distance = Primitive::ComponentSize(type) * 8;
845 if (0 <= distance && distance < max_distance) {
846 if (generate_code) {
847 HInstruction* s = graph_->GetIntConstant(distance);
848 GenerateVecOp(instruction, vector_map_->Get(opa), s, type);
849 }
850 return true;
Aart Bikf8f5a162017-02-06 15:35:29 -0800851 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800852 }
853 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700854 // Accept particular intrinsics.
855 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
856 switch (invoke->GetIntrinsic()) {
857 case Intrinsics::kMathAbsInt:
858 case Intrinsics::kMathAbsLong:
859 case Intrinsics::kMathAbsFloat:
860 case Intrinsics::kMathAbsDouble: {
861 // Deal with vector restrictions.
862 if (HasVectorRestrictions(restrictions, kNoAbs) ||
863 HasVectorRestrictions(restrictions, kNoHiBits)) {
864 // TODO: we can do better for some hibits cases.
865 return false;
866 }
867 // Accept ABS(x) for vectorizable operand.
868 HInstruction* opa = instruction->InputAt(0);
869 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
870 if (generate_code) {
871 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
872 }
873 return true;
874 }
875 return false;
876 }
877 default:
878 return false;
879 } // switch
Aart Bik281c6812016-08-26 11:31:48 -0700880 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800881 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700882}
883
Aart Bikf8f5a162017-02-06 15:35:29 -0800884bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
885 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
886 switch (compiler_driver_->GetInstructionSet()) {
887 case kArm:
888 case kThumb2:
889 return false;
890 case kArm64:
891 // Allow vectorization for all ARM devices, because Android assumes that
Artem Serovd4bccf12017-04-03 18:47:32 +0100892 // ARMv8 AArch64 always supports advanced SIMD.
Aart Bikf8f5a162017-02-06 15:35:29 -0800893 switch (type) {
894 case Primitive::kPrimBoolean:
895 case Primitive::kPrimByte:
Aart Bik6daebeb2017-04-03 14:35:41 -0700896 *restrictions |= kNoDiv | kNoAbs;
Artem Serovd4bccf12017-04-03 18:47:32 +0100897 return TrySetVectorLength(16);
Aart Bikf8f5a162017-02-06 15:35:29 -0800898 case Primitive::kPrimChar:
899 case Primitive::kPrimShort:
Aart Bik6daebeb2017-04-03 14:35:41 -0700900 *restrictions |= kNoDiv | kNoAbs;
Artem Serovd4bccf12017-04-03 18:47:32 +0100901 return TrySetVectorLength(8);
Aart Bikf8f5a162017-02-06 15:35:29 -0800902 case Primitive::kPrimInt:
903 *restrictions |= kNoDiv;
Artem Serovd4bccf12017-04-03 18:47:32 +0100904 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +0100905 case Primitive::kPrimLong:
906 *restrictions |= kNoDiv | kNoMul;
Aart Bikf8f5a162017-02-06 15:35:29 -0800907 return TrySetVectorLength(2);
908 case Primitive::kPrimFloat:
Artem Serovd4bccf12017-04-03 18:47:32 +0100909 return TrySetVectorLength(4);
Artem Serovb31f91f2017-04-05 11:31:19 +0100910 case Primitive::kPrimDouble:
Aart Bikf8f5a162017-02-06 15:35:29 -0800911 return TrySetVectorLength(2);
912 default:
913 return false;
914 }
915 case kX86:
916 case kX86_64:
917 // Allow vectorization for SSE4-enabled X86 devices only (128-bit vectors).
918 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
919 switch (type) {
920 case Primitive::kPrimBoolean:
921 case Primitive::kPrimByte:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700922 *restrictions |= kNoMul | kNoDiv | kNoShift | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -0800923 return TrySetVectorLength(16);
924 case Primitive::kPrimChar:
925 case Primitive::kPrimShort:
Aart Bikf3e61ee2017-04-12 17:09:20 -0700926 *restrictions |= kNoDiv | kNoAbs | kNoSignedHAdd | kNoUnroundedHAdd;
Aart Bikf8f5a162017-02-06 15:35:29 -0800927 return TrySetVectorLength(8);
928 case Primitive::kPrimInt:
929 *restrictions |= kNoDiv;
930 return TrySetVectorLength(4);
931 case Primitive::kPrimLong:
Aart Bik6daebeb2017-04-03 14:35:41 -0700932 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs;
Aart Bikf8f5a162017-02-06 15:35:29 -0800933 return TrySetVectorLength(2);
934 case Primitive::kPrimFloat:
935 return TrySetVectorLength(4);
936 case Primitive::kPrimDouble:
937 return TrySetVectorLength(2);
938 default:
939 break;
940 } // switch type
941 }
942 return false;
943 case kMips:
944 case kMips64:
945 // TODO: implement MIPS SIMD.
946 return false;
947 default:
948 return false;
949 } // switch instruction set
950}
951
952bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
953 DCHECK(IsPowerOfTwo(length) && length >= 2u);
954 // First time set?
955 if (vector_length_ == 0) {
956 vector_length_ = length;
957 }
958 // Different types are acceptable within a loop-body, as long as all the corresponding vector
959 // lengths match exactly to obtain a uniform traversal through the vector iteration space
960 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
961 return vector_length_ == length;
962}
963
964void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
965 if (vector_map_->find(org) == vector_map_->end()) {
966 // In scalar code, just use a self pass-through for scalar invariants
967 // (viz. expression remains itself).
968 if (vector_mode_ == kSequential) {
969 vector_map_->Put(org, org);
970 return;
971 }
972 // In vector code, explicit scalar expansion is needed.
973 HInstruction* vector = new (global_allocator_) HVecReplicateScalar(
974 global_allocator_, org, type, vector_length_);
975 vector_map_->Put(org, Insert(vector_preheader_, vector));
976 }
977}
978
979void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
980 if (vector_map_->find(org) == vector_map_->end()) {
981 HInstruction* subscript = vector_phi_;
982 if (offset != nullptr) {
983 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
984 if (org->IsPhi()) {
985 Insert(vector_body_, subscript); // lacks layout placeholder
986 }
987 }
988 vector_map_->Put(org, subscript);
989 }
990}
991
992void HLoopOptimization::GenerateVecMem(HInstruction* org,
993 HInstruction* opa,
994 HInstruction* opb,
995 Primitive::Type type) {
996 HInstruction* vector = nullptr;
997 if (vector_mode_ == kVector) {
998 // Vector store or load.
999 if (opb != nullptr) {
1000 vector = new (global_allocator_) HVecStore(
1001 global_allocator_, org->InputAt(0), opa, opb, type, vector_length_);
1002 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001003 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
Aart Bikf8f5a162017-02-06 15:35:29 -08001004 vector = new (global_allocator_) HVecLoad(
Aart Bikdb14fcf2017-04-25 15:53:58 -07001005 global_allocator_, org->InputAt(0), opa, type, vector_length_, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001006 }
1007 } else {
1008 // Scalar store or load.
1009 DCHECK(vector_mode_ == kSequential);
1010 if (opb != nullptr) {
1011 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
1012 } else {
Aart Bikdb14fcf2017-04-25 15:53:58 -07001013 bool is_string_char_at = org->AsArrayGet()->IsStringCharAt();
1014 vector = new (global_allocator_) HArrayGet(
1015 org->InputAt(0), opa, type, kNoDexPc, is_string_char_at);
Aart Bikf8f5a162017-02-06 15:35:29 -08001016 }
1017 }
1018 vector_map_->Put(org, vector);
1019}
1020
1021#define GENERATE_VEC(x, y) \
1022 if (vector_mode_ == kVector) { \
1023 vector = (x); \
1024 } else { \
1025 DCHECK(vector_mode_ == kSequential); \
1026 vector = (y); \
1027 } \
1028 break;
1029
1030void HLoopOptimization::GenerateVecOp(HInstruction* org,
1031 HInstruction* opa,
1032 HInstruction* opb,
1033 Primitive::Type type) {
1034 if (vector_mode_ == kSequential) {
1035 // Scalar code follows implicit integral promotion.
1036 if (type == Primitive::kPrimBoolean ||
1037 type == Primitive::kPrimByte ||
1038 type == Primitive::kPrimChar ||
1039 type == Primitive::kPrimShort) {
1040 type = Primitive::kPrimInt;
1041 }
1042 }
1043 HInstruction* vector = nullptr;
1044 switch (org->GetKind()) {
1045 case HInstruction::kNeg:
1046 DCHECK(opb == nullptr);
1047 GENERATE_VEC(
1048 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
1049 new (global_allocator_) HNeg(type, opa));
1050 case HInstruction::kNot:
1051 DCHECK(opb == nullptr);
1052 GENERATE_VEC(
1053 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1054 new (global_allocator_) HNot(type, opa));
1055 case HInstruction::kBooleanNot:
1056 DCHECK(opb == nullptr);
1057 GENERATE_VEC(
1058 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
1059 new (global_allocator_) HBooleanNot(opa));
1060 case HInstruction::kTypeConversion:
1061 DCHECK(opb == nullptr);
1062 GENERATE_VEC(
1063 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
1064 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
1065 case HInstruction::kAdd:
1066 GENERATE_VEC(
1067 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
1068 new (global_allocator_) HAdd(type, opa, opb));
1069 case HInstruction::kSub:
1070 GENERATE_VEC(
1071 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
1072 new (global_allocator_) HSub(type, opa, opb));
1073 case HInstruction::kMul:
1074 GENERATE_VEC(
1075 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
1076 new (global_allocator_) HMul(type, opa, opb));
1077 case HInstruction::kDiv:
1078 GENERATE_VEC(
1079 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
1080 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
1081 case HInstruction::kAnd:
1082 GENERATE_VEC(
1083 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
1084 new (global_allocator_) HAnd(type, opa, opb));
1085 case HInstruction::kOr:
1086 GENERATE_VEC(
1087 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
1088 new (global_allocator_) HOr(type, opa, opb));
1089 case HInstruction::kXor:
1090 GENERATE_VEC(
1091 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
1092 new (global_allocator_) HXor(type, opa, opb));
1093 case HInstruction::kShl:
1094 GENERATE_VEC(
1095 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
1096 new (global_allocator_) HShl(type, opa, opb));
1097 case HInstruction::kShr:
1098 GENERATE_VEC(
1099 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
1100 new (global_allocator_) HShr(type, opa, opb));
1101 case HInstruction::kUShr:
1102 GENERATE_VEC(
1103 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
1104 new (global_allocator_) HUShr(type, opa, opb));
1105 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -07001106 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
1107 if (vector_mode_ == kVector) {
1108 switch (invoke->GetIntrinsic()) {
1109 case Intrinsics::kMathAbsInt:
1110 case Intrinsics::kMathAbsLong:
1111 case Intrinsics::kMathAbsFloat:
1112 case Intrinsics::kMathAbsDouble:
1113 DCHECK(opb == nullptr);
1114 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
1115 break;
1116 default:
1117 LOG(FATAL) << "Unsupported SIMD intrinsic";
1118 UNREACHABLE();
1119 } // switch invoke
1120 } else {
Aart Bik24b905f2017-04-06 09:59:06 -07001121 // In scalar code, simply clone the method invoke, and replace its operands with the
1122 // corresponding new scalar instructions in the loop. The instruction will get an
1123 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -07001124 DCHECK(vector_mode_ == kSequential);
1125 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1126 global_allocator_,
1127 invoke->GetNumberOfArguments(),
1128 invoke->GetType(),
1129 invoke->GetDexPc(),
1130 invoke->GetDexMethodIndex(),
1131 invoke->GetResolvedMethod(),
1132 invoke->GetDispatchInfo(),
1133 invoke->GetInvokeType(),
1134 invoke->GetTargetMethod(),
1135 invoke->GetClinitCheckRequirement());
1136 HInputsRef inputs = invoke->GetInputs();
1137 for (size_t index = 0; index < inputs.size(); ++index) {
1138 new_invoke->SetArgumentAt(index, vector_map_->Get(inputs[index]));
1139 }
Aart Bik98990262017-04-10 13:15:57 -07001140 new_invoke->SetIntrinsic(invoke->GetIntrinsic(),
1141 kNeedsEnvironmentOrCache,
1142 kNoSideEffects,
1143 kNoThrow);
Aart Bik6daebeb2017-04-03 14:35:41 -07001144 vector = new_invoke;
1145 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001146 break;
1147 }
1148 default:
1149 break;
1150 } // switch
1151 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1152 vector_map_->Put(org, vector);
1153}
1154
1155#undef GENERATE_VEC
1156
1157//
Aart Bikf3e61ee2017-04-12 17:09:20 -07001158// Vectorization idioms.
1159//
1160
1161// Method recognizes the following idioms:
1162// rounding halving add (a + b + 1) >> 1 for unsigned/signed operands a, b
1163// regular halving add (a + b) >> 1 for unsigned/signed operands a, b
1164// Provided that the operands are promoted to a wider form to do the arithmetic and
1165// then cast back to narrower form, the idioms can be mapped into efficient SIMD
1166// implementation that operates directly in narrower form (plus one extra bit).
1167// TODO: current version recognizes implicit byte/short/char widening only;
1168// explicit widening from int to long could be added later.
1169bool HLoopOptimization::VectorizeHalvingAddIdiom(LoopNode* node,
1170 HInstruction* instruction,
1171 bool generate_code,
1172 Primitive::Type type,
1173 uint64_t restrictions) {
1174 // Test for top level arithmetic shift right x >> 1 or logical shift right x >>> 1
1175 // (note whether the sign bit in higher precision is shifted in has no effect
1176 // on the narrow precision computed by the idiom).
1177 int64_t value = 0;
1178 if ((instruction->IsShr() ||
1179 instruction->IsUShr()) &&
1180 IsInt64AndGet(instruction->InputAt(1), &value) && value == 1) {
1181 //
1182 // TODO: make following code less sensitive to associativity and commutativity differences.
1183 //
1184 HInstruction* x = instruction->InputAt(0);
1185 // Test for an optional rounding part (x + 1) >> 1.
1186 bool is_rounded = false;
1187 if (x->IsAdd() && IsInt64AndGet(x->InputAt(1), &value) && value == 1) {
1188 x = x->InputAt(0);
1189 is_rounded = true;
1190 }
1191 // Test for a core addition (a + b) >> 1 (possibly rounded), either unsigned or signed.
1192 if (x->IsAdd()) {
1193 HInstruction* a = x->InputAt(0);
1194 HInstruction* b = x->InputAt(1);
1195 HInstruction* r = nullptr;
1196 HInstruction* s = nullptr;
1197 bool is_unsigned = false;
1198 if (IsZeroExtensionAndGet(a, type, &r) && IsZeroExtensionAndGet(b, type, &s)) {
1199 is_unsigned = true;
1200 } else if (IsSignExtensionAndGet(a, type, &r) && IsSignExtensionAndGet(b, type, &s)) {
1201 is_unsigned = false;
1202 } else {
1203 return false;
1204 }
1205 // Deal with vector restrictions.
1206 if ((!is_unsigned && HasVectorRestrictions(restrictions, kNoSignedHAdd)) ||
1207 (!is_rounded && HasVectorRestrictions(restrictions, kNoUnroundedHAdd))) {
1208 return false;
1209 }
1210 // Accept recognized halving add for vectorizable operands. Vectorized code uses the
1211 // shorthand idiomatic operation. Sequential code uses the original scalar expressions.
1212 DCHECK(r != nullptr && s != nullptr);
1213 if (VectorizeUse(node, r, generate_code, type, restrictions) &&
1214 VectorizeUse(node, s, generate_code, type, restrictions)) {
1215 if (generate_code) {
1216 if (vector_mode_ == kVector) {
1217 vector_map_->Put(instruction, new (global_allocator_) HVecHalvingAdd(
1218 global_allocator_,
1219 vector_map_->Get(r),
1220 vector_map_->Get(s),
1221 type,
1222 vector_length_,
1223 is_unsigned,
1224 is_rounded));
1225 } else {
1226 VectorizeUse(node, instruction->InputAt(0), generate_code, type, restrictions);
1227 VectorizeUse(node, instruction->InputAt(1), generate_code, type, restrictions);
1228 GenerateVecOp(instruction,
1229 vector_map_->Get(instruction->InputAt(0)),
1230 vector_map_->Get(instruction->InputAt(1)),
1231 type);
1232 }
1233 }
1234 return true;
1235 }
1236 }
1237 }
1238 return false;
1239}
1240
1241//
Aart Bikf8f5a162017-02-06 15:35:29 -08001242// Helpers.
1243//
1244
1245bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
1246 DCHECK(iset_->empty());
Aart Bikcc42be02016-10-20 16:14:16 -07001247 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1248 if (set != nullptr) {
1249 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001250 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001251 // each instruction is removable and, when restrict uses are requested, other than for phi,
1252 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001253 if (!i->IsInBlock()) {
1254 continue;
1255 } else if (!i->IsRemovable()) {
1256 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001257 } else if (i != phi && restrict_uses) {
Aart Bikcc42be02016-10-20 16:14:16 -07001258 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1259 if (set->find(use.GetUser()) == set->end()) {
1260 return false;
1261 }
1262 }
1263 }
Aart Bike3dedc52016-11-02 17:50:27 -07001264 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001265 }
Aart Bikcc42be02016-10-20 16:14:16 -07001266 return true;
1267 }
1268 return false;
1269}
1270
1271// Find: phi: Phi(init, addsub)
1272// s: SuspendCheck
1273// c: Condition(phi, bound)
1274// i: If(c)
1275// TODO: Find a less pattern matching approach?
Aart Bikf8f5a162017-02-06 15:35:29 -08001276bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block) {
Aart Bikcc42be02016-10-20 16:14:16 -07001277 DCHECK(iset_->empty());
1278 HInstruction* phi = block->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -08001279 if (phi != nullptr &&
1280 phi->GetNext() == nullptr &&
1281 TrySetPhiInduction(phi->AsPhi(), /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001282 HInstruction* s = block->GetFirstInstruction();
1283 if (s != nullptr && s->IsSuspendCheck()) {
1284 HInstruction* c = s->GetNext();
Aart Bikd86c0852017-04-14 12:00:15 -07001285 if (c != nullptr &&
1286 c->IsCondition() &&
1287 c->GetUses().HasExactlyOneElement() && // only used for termination
1288 !c->HasEnvironmentUses()) { // unlikely, but not impossible
Aart Bikcc42be02016-10-20 16:14:16 -07001289 HInstruction* i = c->GetNext();
1290 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1291 iset_->insert(c);
1292 iset_->insert(s);
1293 return true;
1294 }
1295 }
1296 }
1297 }
1298 return false;
1299}
1300
1301bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001302 if (!block->GetPhis().IsEmpty()) {
1303 return false;
1304 }
1305 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1306 HInstruction* instruction = it.Current();
1307 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1308 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001309 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001310 }
1311 return true;
1312}
1313
1314bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1315 HInstruction* instruction) {
1316 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1317 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1318 return true;
1319 }
Aart Bikcc42be02016-10-20 16:14:16 -07001320 }
1321 return false;
1322}
1323
Aart Bik482095d2016-10-10 15:39:10 -07001324bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001325 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001326 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001327 /*out*/ int32_t* use_count) {
1328 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1329 HInstruction* user = use.GetUser();
1330 if (iset_->find(user) == iset_->end()) { // not excluded?
1331 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001332 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001333 // If collect_loop_uses is set, simply keep adding those uses to the set.
1334 // Otherwise, reject uses inside the loop that were not already in the set.
1335 if (collect_loop_uses) {
1336 iset_->insert(user);
1337 continue;
1338 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001339 return false;
1340 }
1341 ++*use_count;
1342 }
1343 }
1344 return true;
1345}
1346
Aart Bik807868e2016-11-03 17:51:43 -07001347bool HLoopOptimization::TryReplaceWithLastValue(HInstruction* instruction, HBasicBlock* block) {
1348 // Try to replace outside uses with the last value. Environment uses can consume this
1349 // value too, since any first true use is outside the loop (although this may imply
1350 // that de-opting may look "ahead" a bit on the phi value). If there are only environment
1351 // uses, the value is dropped altogether, since the computations have no effect.
1352 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001353 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
1354 const HUseList<HInstruction*>& uses = instruction->GetUses();
1355 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1356 HInstruction* user = it->GetUser();
1357 size_t index = it->GetIndex();
1358 ++it; // increment before replacing
1359 if (iset_->find(user) == iset_->end()) { // not excluded?
1360 user->ReplaceInput(replacement, index);
1361 induction_range_.Replace(user, instruction, replacement); // update induction
1362 }
1363 }
1364 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1365 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1366 HEnvironment* user = it->GetUser();
1367 size_t index = it->GetIndex();
1368 ++it; // increment before replacing
1369 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
1370 user->RemoveAsUserOfInput(index);
1371 user->SetRawEnvAt(index, replacement);
1372 replacement->AddEnvUseAt(user, index);
1373 }
1374 }
1375 induction_simplication_count_++;
Aart Bik807868e2016-11-03 17:51:43 -07001376 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001377 }
Aart Bik807868e2016-11-03 17:51:43 -07001378 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001379}
1380
Aart Bikf8f5a162017-02-06 15:35:29 -08001381bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1382 HInstruction* instruction,
1383 HBasicBlock* block,
1384 bool collect_loop_uses) {
1385 // Assigning the last value is always successful if there are no uses.
1386 // Otherwise, it succeeds in a no early-exit loop by generating the
1387 // proper last value assignment.
1388 int32_t use_count = 0;
1389 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
1390 (use_count == 0 ||
1391 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(instruction, block)));
1392}
1393
Aart Bik6b69e0a2017-01-11 10:20:43 -08001394void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
1395 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
1396 HInstruction* instruction = i.Current();
1397 if (instruction->IsDeadAndRemovable()) {
1398 simplified_ = true;
1399 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
1400 }
1401 }
1402}
1403
Aart Bik281c6812016-08-26 11:31:48 -07001404} // namespace art