blob: ca31bf89e6bbf944dcb865d5c35513f6ea3df6fb [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 Bikf8f5a162017-02-06 15:35:29 -080066// Test vector restrictions.
67static bool HasVectorRestrictions(uint64_t restrictions, uint64_t tested) {
68 return (restrictions & tested) != 0;
69}
70
71// Inserts an instruction.
72static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
73 DCHECK(block != nullptr);
74 DCHECK(instruction != nullptr);
75 block->InsertInstructionBefore(instruction, block->GetLastInstruction());
76 return instruction;
77}
78
Aart Bik281c6812016-08-26 11:31:48 -070079//
80// Class methods.
81//
82
83HLoopOptimization::HLoopOptimization(HGraph* graph,
Aart Bik92685a82017-03-06 11:13:43 -080084 CompilerDriver* compiler_driver,
Aart Bik281c6812016-08-26 11:31:48 -070085 HInductionVarAnalysis* induction_analysis)
86 : HOptimization(graph, kLoopOptimizationPassName),
Aart Bik92685a82017-03-06 11:13:43 -080087 compiler_driver_(compiler_driver),
Aart Bik281c6812016-08-26 11:31:48 -070088 induction_range_(induction_analysis),
Aart Bik96202302016-10-04 17:33:56 -070089 loop_allocator_(nullptr),
Aart Bikf8f5a162017-02-06 15:35:29 -080090 global_allocator_(graph_->GetArena()),
Aart Bik281c6812016-08-26 11:31:48 -070091 top_loop_(nullptr),
Aart Bik8c4a8542016-10-06 11:36:57 -070092 last_loop_(nullptr),
Aart Bik482095d2016-10-10 15:39:10 -070093 iset_(nullptr),
Aart Bikdf7822e2016-12-06 10:05:30 -080094 induction_simplication_count_(0),
Aart Bikf8f5a162017-02-06 15:35:29 -080095 simplified_(false),
96 vector_length_(0),
97 vector_refs_(nullptr),
98 vector_map_(nullptr) {
Aart Bik281c6812016-08-26 11:31:48 -070099}
100
101void HLoopOptimization::Run() {
Mingyao Yang01b47b02017-02-03 12:09:57 -0800102 // Skip if there is no loop or the graph has try-catch/irreducible loops.
Aart Bik281c6812016-08-26 11:31:48 -0700103 // TODO: make this less of a sledgehammer.
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800104 if (!graph_->HasLoops() || graph_->HasTryCatch() || graph_->HasIrreducibleLoops()) {
Aart Bik281c6812016-08-26 11:31:48 -0700105 return;
106 }
107
Aart Bik96202302016-10-04 17:33:56 -0700108 // Phase-local allocator that draws from the global pool. Since the allocator
109 // itself resides on the stack, it is destructed on exiting Run(), which
110 // implies its underlying memory is released immediately.
Aart Bikf8f5a162017-02-06 15:35:29 -0800111 ArenaAllocator allocator(global_allocator_->GetArenaPool());
Aart Bik96202302016-10-04 17:33:56 -0700112 loop_allocator_ = &allocator;
Nicolas Geoffrayebe16742016-10-05 09:55:42 +0100113
Aart Bik96202302016-10-04 17:33:56 -0700114 // Perform loop optimizations.
115 LocalRun();
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800116 if (top_loop_ == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800117 graph_->SetHasLoops(false); // no more loops
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800118 }
119
Aart Bik96202302016-10-04 17:33:56 -0700120 // Detach.
121 loop_allocator_ = nullptr;
122 last_loop_ = top_loop_ = nullptr;
123}
124
125void HLoopOptimization::LocalRun() {
126 // Build the linear order using the phase-local allocator. This step enables building
127 // a loop hierarchy that properly reflects the outer-inner and previous-next relation.
128 ArenaVector<HBasicBlock*> linear_order(loop_allocator_->Adapter(kArenaAllocLinearOrder));
129 LinearizeGraph(graph_, loop_allocator_, &linear_order);
130
Aart Bik281c6812016-08-26 11:31:48 -0700131 // Build the loop hierarchy.
Aart Bik96202302016-10-04 17:33:56 -0700132 for (HBasicBlock* block : linear_order) {
Aart Bik281c6812016-08-26 11:31:48 -0700133 if (block->IsLoopHeader()) {
134 AddLoop(block->GetLoopInformation());
135 }
136 }
Aart Bik96202302016-10-04 17:33:56 -0700137
Aart Bik8c4a8542016-10-06 11:36:57 -0700138 // Traverse the loop hierarchy inner-to-outer and optimize. Traversal can use
Aart Bikf8f5a162017-02-06 15:35:29 -0800139 // temporary data structures using the phase-local allocator. All new HIR
140 // should use the global allocator.
Aart Bik8c4a8542016-10-06 11:36:57 -0700141 if (top_loop_ != nullptr) {
142 ArenaSet<HInstruction*> iset(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
Aart Bikf8f5a162017-02-06 15:35:29 -0800143 ArenaSet<ArrayReference> refs(loop_allocator_->Adapter(kArenaAllocLoopOptimization));
144 ArenaSafeMap<HInstruction*, HInstruction*> map(
145 std::less<HInstruction*>(), loop_allocator_->Adapter(kArenaAllocLoopOptimization));
146 // Attach.
Aart Bik8c4a8542016-10-06 11:36:57 -0700147 iset_ = &iset;
Aart Bikf8f5a162017-02-06 15:35:29 -0800148 vector_refs_ = &refs;
149 vector_map_ = &map;
150 // Traverse.
Aart Bik8c4a8542016-10-06 11:36:57 -0700151 TraverseLoopsInnerToOuter(top_loop_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800152 // Detach.
153 iset_ = nullptr;
154 vector_refs_ = nullptr;
155 vector_map_ = nullptr;
Aart Bik8c4a8542016-10-06 11:36:57 -0700156 }
Aart Bik281c6812016-08-26 11:31:48 -0700157}
158
159void HLoopOptimization::AddLoop(HLoopInformation* loop_info) {
160 DCHECK(loop_info != nullptr);
Aart Bikf8f5a162017-02-06 15:35:29 -0800161 LoopNode* node = new (loop_allocator_) LoopNode(loop_info);
Aart Bik281c6812016-08-26 11:31:48 -0700162 if (last_loop_ == nullptr) {
163 // First loop.
164 DCHECK(top_loop_ == nullptr);
165 last_loop_ = top_loop_ = node;
166 } else if (loop_info->IsIn(*last_loop_->loop_info)) {
167 // Inner loop.
168 node->outer = last_loop_;
169 DCHECK(last_loop_->inner == nullptr);
170 last_loop_ = last_loop_->inner = node;
171 } else {
172 // Subsequent loop.
173 while (last_loop_->outer != nullptr && !loop_info->IsIn(*last_loop_->outer->loop_info)) {
174 last_loop_ = last_loop_->outer;
175 }
176 node->outer = last_loop_->outer;
177 node->previous = last_loop_;
178 DCHECK(last_loop_->next == nullptr);
179 last_loop_ = last_loop_->next = node;
180 }
181}
182
183void HLoopOptimization::RemoveLoop(LoopNode* node) {
184 DCHECK(node != nullptr);
Aart Bik8c4a8542016-10-06 11:36:57 -0700185 DCHECK(node->inner == nullptr);
186 if (node->previous != nullptr) {
187 // Within sequence.
188 node->previous->next = node->next;
189 if (node->next != nullptr) {
190 node->next->previous = node->previous;
191 }
192 } else {
193 // First of sequence.
194 if (node->outer != nullptr) {
195 node->outer->inner = node->next;
196 } else {
197 top_loop_ = node->next;
198 }
199 if (node->next != nullptr) {
200 node->next->outer = node->outer;
201 node->next->previous = nullptr;
202 }
203 }
Aart Bik281c6812016-08-26 11:31:48 -0700204}
205
206void HLoopOptimization::TraverseLoopsInnerToOuter(LoopNode* node) {
207 for ( ; node != nullptr; node = node->next) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800208 // Visit inner loops first.
Aart Bikf8f5a162017-02-06 15:35:29 -0800209 uint32_t current_induction_simplification_count = induction_simplication_count_;
Aart Bik281c6812016-08-26 11:31:48 -0700210 if (node->inner != nullptr) {
211 TraverseLoopsInnerToOuter(node->inner);
212 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800213 // Recompute induction information of this loop if the induction
214 // of any inner loop has been simplified.
Aart Bik482095d2016-10-10 15:39:10 -0700215 if (current_induction_simplification_count != induction_simplication_count_) {
216 induction_range_.ReVisit(node->loop_info);
217 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800218 // Repeat simplifications in the loop-body until no more changes occur.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800219 // Note that since each simplification consists of eliminating code (without
220 // introducing new code), this process is always finite.
Aart Bikdf7822e2016-12-06 10:05:30 -0800221 do {
222 simplified_ = false;
Aart Bikdf7822e2016-12-06 10:05:30 -0800223 SimplifyInduction(node);
Aart Bik6b69e0a2017-01-11 10:20:43 -0800224 SimplifyBlocks(node);
Aart Bikdf7822e2016-12-06 10:05:30 -0800225 } while (simplified_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800226 // Optimize inner loop.
Aart Bik9abf8942016-10-14 09:49:42 -0700227 if (node->inner == nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800228 OptimizeInnerLoop(node);
Aart Bik9abf8942016-10-14 09:49:42 -0700229 }
Aart Bik281c6812016-08-26 11:31:48 -0700230 }
231}
232
Aart Bikf8f5a162017-02-06 15:35:29 -0800233//
234// Optimization.
235//
236
Aart Bik281c6812016-08-26 11:31:48 -0700237void HLoopOptimization::SimplifyInduction(LoopNode* node) {
238 HBasicBlock* header = node->loop_info->GetHeader();
239 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik8c4a8542016-10-06 11:36:57 -0700240 // Scan the phis in the header to find opportunities to simplify an induction
241 // cycle that is only used outside the loop. Replace these uses, if any, with
242 // the last value and remove the induction cycle.
243 // Examples: for (int i = 0; x != null; i++) { .... no i .... }
244 // for (int i = 0; i < 10; i++, k++) { .... no k .... } return k;
Aart Bik281c6812016-08-26 11:31:48 -0700245 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
246 HPhi* phi = it.Current()->AsPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800247 iset_->clear(); // prepare phi induction
248 if (TrySetPhiInduction(phi, /*restrict_uses*/ true) &&
249 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ false)) {
Aart Bik8c4a8542016-10-06 11:36:57 -0700250 for (HInstruction* i : *iset_) {
251 RemoveFromCycle(i);
Aart Bik281c6812016-08-26 11:31:48 -0700252 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800253 simplified_ = true;
Aart Bik482095d2016-10-10 15:39:10 -0700254 }
255 }
256}
257
258void HLoopOptimization::SimplifyBlocks(LoopNode* node) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800259 // Iterate over all basic blocks in the loop-body.
260 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
261 HBasicBlock* block = it.Current();
262 // Remove dead instructions from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800263 RemoveDeadInstructions(block->GetPhis());
264 RemoveDeadInstructions(block->GetInstructions());
Aart Bikdf7822e2016-12-06 10:05:30 -0800265 // Remove trivial control flow blocks from the loop-body.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800266 if (block->GetPredecessors().size() == 1 &&
267 block->GetSuccessors().size() == 1 &&
268 block->GetSingleSuccessor()->GetPredecessors().size() == 1) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800269 simplified_ = true;
Aart Bik6b69e0a2017-01-11 10:20:43 -0800270 block->MergeWith(block->GetSingleSuccessor());
Aart Bikdf7822e2016-12-06 10:05:30 -0800271 } else if (block->GetSuccessors().size() == 2) {
272 // Trivial if block can be bypassed to either branch.
273 HBasicBlock* succ0 = block->GetSuccessors()[0];
274 HBasicBlock* succ1 = block->GetSuccessors()[1];
275 HBasicBlock* meet0 = nullptr;
276 HBasicBlock* meet1 = nullptr;
277 if (succ0 != succ1 &&
278 IsGotoBlock(succ0, &meet0) &&
279 IsGotoBlock(succ1, &meet1) &&
280 meet0 == meet1 && // meets again
281 meet0 != block && // no self-loop
282 meet0->GetPhis().IsEmpty()) { // not used for merging
283 simplified_ = true;
284 succ0->DisconnectAndDelete();
285 if (block->Dominates(meet0)) {
286 block->RemoveDominatedBlock(meet0);
287 succ1->AddDominatedBlock(meet0);
288 meet0->SetDominator(succ1);
Aart Bike3dedc52016-11-02 17:50:27 -0700289 }
Aart Bik482095d2016-10-10 15:39:10 -0700290 }
Aart Bik281c6812016-08-26 11:31:48 -0700291 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800292 }
Aart Bik281c6812016-08-26 11:31:48 -0700293}
294
Aart Bikf8f5a162017-02-06 15:35:29 -0800295void HLoopOptimization::OptimizeInnerLoop(LoopNode* node) {
Aart Bik281c6812016-08-26 11:31:48 -0700296 HBasicBlock* header = node->loop_info->GetHeader();
297 HBasicBlock* preheader = node->loop_info->GetPreHeader();
Aart Bik9abf8942016-10-14 09:49:42 -0700298 // Ensure loop header logic is finite.
Aart Bikf8f5a162017-02-06 15:35:29 -0800299 int64_t trip_count = 0;
300 if (!induction_range_.IsFinite(node->loop_info, &trip_count)) {
301 return;
Aart Bik9abf8942016-10-14 09:49:42 -0700302 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800303
Aart Bik281c6812016-08-26 11:31:48 -0700304 // Ensure there is only a single loop-body (besides the header).
305 HBasicBlock* body = nullptr;
306 for (HBlocksInLoopIterator it(*node->loop_info); !it.Done(); it.Advance()) {
307 if (it.Current() != header) {
308 if (body != nullptr) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800309 return;
Aart Bik281c6812016-08-26 11:31:48 -0700310 }
311 body = it.Current();
312 }
313 }
314 // Ensure there is only a single exit point.
315 if (header->GetSuccessors().size() != 2) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800316 return;
Aart Bik281c6812016-08-26 11:31:48 -0700317 }
318 HBasicBlock* exit = (header->GetSuccessors()[0] == body)
319 ? header->GetSuccessors()[1]
320 : header->GetSuccessors()[0];
Aart Bik8c4a8542016-10-06 11:36:57 -0700321 // Ensure exit can only be reached by exiting loop.
Aart Bik281c6812016-08-26 11:31:48 -0700322 if (exit->GetPredecessors().size() != 1) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800323 return;
Aart Bik281c6812016-08-26 11:31:48 -0700324 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800325 // Detect either an empty loop (no side effects other than plain iteration) or
326 // a trivial loop (just iterating once). Replace subsequent index uses, if any,
327 // with the last value and remove the loop, possibly after unrolling its body.
328 HInstruction* phi = header->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -0800329 iset_->clear(); // prepare phi induction
330 if (TrySetSimpleLoopHeader(header)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800331 bool is_empty = IsEmptyBody(body);
Aart Bikf8f5a162017-02-06 15:35:29 -0800332 if ((is_empty || trip_count == 1) &&
333 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -0800334 if (!is_empty) {
Aart Bikf8f5a162017-02-06 15:35:29 -0800335 // Unroll the loop-body, which sees initial value of the index.
Aart Bik6b69e0a2017-01-11 10:20:43 -0800336 phi->ReplaceWith(phi->InputAt(0));
337 preheader->MergeInstructionsWith(body);
338 }
339 body->DisconnectAndDelete();
340 exit->RemovePredecessor(header);
341 header->RemoveSuccessor(exit);
342 header->RemoveDominatedBlock(exit);
343 header->DisconnectAndDelete();
344 preheader->AddSuccessor(exit);
Aart Bikf8f5a162017-02-06 15:35:29 -0800345 preheader->AddInstruction(new (global_allocator_) HGoto());
Aart Bik6b69e0a2017-01-11 10:20:43 -0800346 preheader->AddDominatedBlock(exit);
347 exit->SetDominator(preheader);
348 RemoveLoop(node); // update hierarchy
Aart Bikf8f5a162017-02-06 15:35:29 -0800349 return;
350 }
351 }
352
353 // Vectorize loop, if possible and valid.
354 if (kEnableVectorization) {
355 iset_->clear(); // prepare phi induction
356 if (TrySetSimpleLoopHeader(header) &&
357 CanVectorize(node, body, trip_count) &&
358 TryAssignLastValue(node->loop_info, phi, preheader, /*collect_loop_uses*/ true)) {
359 Vectorize(node, body, exit, trip_count);
360 graph_->SetHasSIMD(true); // flag SIMD usage
361 return;
362 }
363 }
364}
365
366//
367// Loop vectorization. The implementation is based on the book by Aart J.C. Bik:
368// "The Software Vectorization Handbook. Applying Multimedia Extensions for Maximum Performance."
369// Intel Press, June, 2004 (http://www.aartbik.com/).
370//
371
372bool HLoopOptimization::CanVectorize(LoopNode* node, HBasicBlock* block, int64_t trip_count) {
373 // Reset vector bookkeeping.
374 vector_length_ = 0;
375 vector_refs_->clear();
376 vector_runtime_test_a_ =
377 vector_runtime_test_b_= nullptr;
378
379 // Phis in the loop-body prevent vectorization.
380 if (!block->GetPhis().IsEmpty()) {
381 return false;
382 }
383
384 // Scan the loop-body, starting a right-hand-side tree traversal at each left-hand-side
385 // occurrence, which allows passing down attributes down the use tree.
386 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
387 if (!VectorizeDef(node, it.Current(), /*generate_code*/ false)) {
388 return false; // failure to vectorize a left-hand-side
389 }
390 }
391
392 // Heuristics. Does vectorization seem profitable?
393 // TODO: refine
394 if (vector_length_ == 0) {
395 return false; // nothing found
396 } else if (0 < trip_count && trip_count < vector_length_) {
397 return false; // insufficient iterations
398 }
399
400 // Data dependence analysis. Find each pair of references with same type, where
401 // at least one is a write. Each such pair denotes a possible data dependence.
402 // This analysis exploits the property that differently typed arrays cannot be
403 // aliased, as well as the property that references either point to the same
404 // array or to two completely disjoint arrays, i.e., no partial aliasing.
405 // Other than a few simply heuristics, no detailed subscript analysis is done.
406 for (auto i = vector_refs_->begin(); i != vector_refs_->end(); ++i) {
407 for (auto j = i; ++j != vector_refs_->end(); ) {
408 if (i->type == j->type && (i->lhs || j->lhs)) {
409 // Found same-typed a[i+x] vs. b[i+y], where at least one is a write.
410 HInstruction* a = i->base;
411 HInstruction* b = j->base;
412 HInstruction* x = i->offset;
413 HInstruction* y = j->offset;
414 if (a == b) {
415 // Found a[i+x] vs. a[i+y]. Accept if x == y (loop-independent data dependence).
416 // Conservatively assume a loop-carried data dependence otherwise, and reject.
417 if (x != y) {
418 return false;
419 }
420 } else {
421 // Found a[i+x] vs. b[i+y]. Accept if x == y (at worst loop-independent data dependence).
422 // Conservatively assume a potential loop-carried data dependence otherwise, avoided by
423 // generating an explicit a != b disambiguation runtime test on the two references.
424 if (x != y) {
425 // For now, we reject after one test to avoid excessive overhead.
426 if (vector_runtime_test_a_ != nullptr) {
427 return false;
428 }
429 vector_runtime_test_a_ = a;
430 vector_runtime_test_b_ = b;
431 }
432 }
433 }
434 }
435 }
436
437 // Success!
438 return true;
439}
440
441void HLoopOptimization::Vectorize(LoopNode* node,
442 HBasicBlock* block,
443 HBasicBlock* exit,
444 int64_t trip_count) {
445 Primitive::Type induc_type = Primitive::kPrimInt;
446 HBasicBlock* header = node->loop_info->GetHeader();
447 HBasicBlock* preheader = node->loop_info->GetPreHeader();
448
449 // A cleanup is needed for any unknown trip count or for a known trip count
450 // with remainder iterations after vectorization.
451 bool needs_cleanup = trip_count == 0 || (trip_count % vector_length_) != 0;
452
453 // Adjust vector bookkeeping.
454 iset_->clear(); // prepare phi induction
455 bool is_simple_loop_header = TrySetSimpleLoopHeader(header); // fills iset_
456 DCHECK(is_simple_loop_header);
457
458 // Generate preheader:
459 // stc = <trip-count>;
460 // vtc = stc - stc % VL;
461 HInstruction* stc = induction_range_.GenerateTripCount(node->loop_info, graph_, preheader);
462 HInstruction* vtc = stc;
463 if (needs_cleanup) {
464 DCHECK(IsPowerOfTwo(vector_length_));
465 HInstruction* rem = Insert(
466 preheader, new (global_allocator_) HAnd(induc_type,
467 stc,
468 graph_->GetIntConstant(vector_length_ - 1)));
469 vtc = Insert(preheader, new (global_allocator_) HSub(induc_type, stc, rem));
470 }
471
472 // Generate runtime disambiguation test:
473 // vtc = a != b ? vtc : 0;
474 if (vector_runtime_test_a_ != nullptr) {
475 HInstruction* rt = Insert(
476 preheader,
477 new (global_allocator_) HNotEqual(vector_runtime_test_a_, vector_runtime_test_b_));
478 vtc = Insert(preheader,
479 new (global_allocator_) HSelect(rt, vtc, graph_->GetIntConstant(0), kNoDexPc));
480 needs_cleanup = true;
481 }
482
483 // Generate vector loop:
484 // for (i = 0; i < vtc; i += VL)
485 // <vectorized-loop-body>
486 vector_mode_ = kVector;
487 GenerateNewLoop(node,
488 block,
489 graph_->TransformLoopForVectorization(header, block, exit),
490 graph_->GetIntConstant(0),
491 vtc,
492 graph_->GetIntConstant(vector_length_));
493 HLoopInformation* vloop = vector_header_->GetLoopInformation();
494
495 // Generate cleanup loop, if needed:
496 // for ( ; i < stc; i += 1)
497 // <loop-body>
498 if (needs_cleanup) {
499 vector_mode_ = kSequential;
500 GenerateNewLoop(node,
501 block,
502 graph_->TransformLoopForVectorization(vector_header_, vector_body_, exit),
503 vector_phi_,
504 stc,
505 graph_->GetIntConstant(1));
506 }
507
508 // Remove the original loop by disconnecting the body block
509 // and removing all instructions from the header.
510 block->DisconnectAndDelete();
511 while (!header->GetFirstInstruction()->IsGoto()) {
512 header->RemoveInstruction(header->GetFirstInstruction());
513 }
514 // Update loop hierarchy: the old header now resides in the
515 // same outer loop as the old preheader.
516 header->SetLoopInformation(preheader->GetLoopInformation()); // outward
517 node->loop_info = vloop;
518}
519
520void HLoopOptimization::GenerateNewLoop(LoopNode* node,
521 HBasicBlock* block,
522 HBasicBlock* new_preheader,
523 HInstruction* lo,
524 HInstruction* hi,
525 HInstruction* step) {
526 Primitive::Type induc_type = Primitive::kPrimInt;
527 // Prepare new loop.
528 vector_map_->clear();
529 vector_preheader_ = new_preheader,
530 vector_header_ = vector_preheader_->GetSingleSuccessor();
531 vector_body_ = vector_header_->GetSuccessors()[1];
532 vector_phi_ = new (global_allocator_) HPhi(global_allocator_,
533 kNoRegNumber,
534 0,
535 HPhi::ToPhiType(induc_type));
Aart Bikb07d1bc2017-04-05 10:03:15 -0700536 // Generate header and prepare body.
Aart Bikf8f5a162017-02-06 15:35:29 -0800537 // for (i = lo; i < hi; i += step)
538 // <loop-body>
539 HInstruction* cond = new (global_allocator_) HAboveOrEqual(vector_phi_, hi);
540 vector_header_->AddPhi(vector_phi_);
541 vector_header_->AddInstruction(cond);
542 vector_header_->AddInstruction(new (global_allocator_) HIf(cond));
Aart Bikf8f5a162017-02-06 15:35:29 -0800543 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
544 bool vectorized_def = VectorizeDef(node, it.Current(), /*generate_code*/ true);
545 DCHECK(vectorized_def);
546 }
Aart Bikb07d1bc2017-04-05 10:03:15 -0700547 // Generate body.
548 HEnvironment* env = vector_header_->GetFirstInstruction()->GetEnvironment();
Aart Bikf8f5a162017-02-06 15:35:29 -0800549 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
550 auto i = vector_map_->find(it.Current());
551 if (i != vector_map_->end() && !i->second->IsInBlock()) {
552 Insert(vector_body_, i->second); // lays out in original order
553 if (i->second->NeedsEnvironment()) {
Aart Bikb07d1bc2017-04-05 10:03:15 -0700554 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800555 }
556 }
557 }
558 // Finalize increment and phi.
559 HInstruction* inc = new (global_allocator_) HAdd(induc_type, vector_phi_, step);
560 vector_phi_->AddInput(lo);
561 vector_phi_->AddInput(Insert(vector_body_, inc));
562}
563
564// TODO: accept reductions at left-hand-side, mixed-type store idioms, etc.
565bool HLoopOptimization::VectorizeDef(LoopNode* node,
566 HInstruction* instruction,
567 bool generate_code) {
568 // Accept a left-hand-side array base[index] for
569 // (1) supported vector type,
570 // (2) loop-invariant base,
571 // (3) unit stride index,
572 // (4) vectorizable right-hand-side value.
573 uint64_t restrictions = kNone;
574 if (instruction->IsArraySet()) {
575 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
576 HInstruction* base = instruction->InputAt(0);
577 HInstruction* index = instruction->InputAt(1);
578 HInstruction* value = instruction->InputAt(2);
579 HInstruction* offset = nullptr;
580 if (TrySetVectorType(type, &restrictions) &&
581 node->loop_info->IsDefinedOutOfTheLoop(base) &&
582 induction_range_.IsUnitStride(index, &offset) &&
583 VectorizeUse(node, value, generate_code, type, restrictions)) {
584 if (generate_code) {
585 GenerateVecSub(index, offset);
586 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), type);
587 } else {
588 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
589 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800590 return true;
591 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800592 return false;
593 }
594 // Branch back okay.
595 if (instruction->IsGoto()) {
596 return true;
597 }
598 // Otherwise accept only expressions with no effects outside the immediate loop-body.
599 // Note that actual uses are inspected during right-hand-side tree traversal.
600 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
601}
602
603// TODO: more operations and intrinsics, detect saturation arithmetic, etc.
604bool HLoopOptimization::VectorizeUse(LoopNode* node,
605 HInstruction* instruction,
606 bool generate_code,
607 Primitive::Type type,
608 uint64_t restrictions) {
609 // Accept anything for which code has already been generated.
610 if (generate_code) {
611 if (vector_map_->find(instruction) != vector_map_->end()) {
612 return true;
613 }
614 }
615 // Continue the right-hand-side tree traversal, passing in proper
616 // types and vector restrictions along the way. During code generation,
617 // all new nodes are drawn from the global allocator.
618 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
619 // Accept invariant use, using scalar expansion.
620 if (generate_code) {
621 GenerateVecInv(instruction, type);
622 }
623 return true;
624 } else if (instruction->IsArrayGet()) {
625 // Accept a right-hand-side array base[index] for
626 // (1) exact matching vector type,
627 // (2) loop-invariant base,
628 // (3) unit stride index,
629 // (4) vectorizable right-hand-side value.
630 HInstruction* base = instruction->InputAt(0);
631 HInstruction* index = instruction->InputAt(1);
632 HInstruction* offset = nullptr;
633 if (type == instruction->GetType() &&
634 node->loop_info->IsDefinedOutOfTheLoop(base) &&
635 induction_range_.IsUnitStride(index, &offset)) {
636 if (generate_code) {
637 GenerateVecSub(index, offset);
638 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, type);
639 } else {
640 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
641 }
642 return true;
643 }
644 } else if (instruction->IsTypeConversion()) {
645 // Accept particular type conversions.
646 HTypeConversion* conversion = instruction->AsTypeConversion();
647 HInstruction* opa = conversion->InputAt(0);
648 Primitive::Type from = conversion->GetInputType();
649 Primitive::Type to = conversion->GetResultType();
650 if ((to == Primitive::kPrimByte ||
651 to == Primitive::kPrimChar ||
652 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
653 // Accept a "narrowing" type conversion from a "wider" computation for
654 // (1) conversion into final required type,
655 // (2) vectorizable operand,
656 // (3) "wider" operations cannot bring in higher order bits.
657 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
658 if (generate_code) {
659 if (vector_mode_ == kVector) {
660 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
661 } else {
662 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
663 }
664 }
665 return true;
666 }
667 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
668 DCHECK_EQ(to, type);
669 // Accept int to float conversion for
670 // (1) supported int,
671 // (2) vectorizable operand.
672 if (TrySetVectorType(from, &restrictions) &&
673 VectorizeUse(node, opa, generate_code, from, restrictions)) {
674 if (generate_code) {
675 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
676 }
677 return true;
678 }
679 }
680 return false;
681 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
682 // Accept unary operator for vectorizable operand.
683 HInstruction* opa = instruction->InputAt(0);
684 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
685 if (generate_code) {
686 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
687 }
688 return true;
689 }
690 } else if (instruction->IsAdd() || instruction->IsSub() ||
691 instruction->IsMul() || instruction->IsDiv() ||
692 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
693 // Deal with vector restrictions.
694 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
695 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
696 return false;
697 }
698 // Accept binary operator for vectorizable operands.
699 HInstruction* opa = instruction->InputAt(0);
700 HInstruction* opb = instruction->InputAt(1);
701 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
702 VectorizeUse(node, opb, generate_code, type, restrictions)) {
703 if (generate_code) {
704 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
705 }
706 return true;
707 }
708 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
709 // Deal with vector restrictions.
710 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
711 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
712 return false; // unsupported instruction
713 } else if ((instruction->IsShr() || instruction->IsUShr()) &&
714 HasVectorRestrictions(restrictions, kNoHiBits)) {
715 return false; // hibits may impact lobits; TODO: we can do better!
716 }
717 // Accept shift operator for vectorizable/invariant operands.
718 // TODO: accept symbolic, albeit loop invariant shift factors.
719 HInstruction* opa = instruction->InputAt(0);
720 HInstruction* opb = instruction->InputAt(1);
721 if (VectorizeUse(node, opa, generate_code, type, restrictions) && opb->IsIntConstant()) {
722 if (generate_code) {
723 // Make sure shift factor only looks at lower bits, as defined for sequential shifts.
724 // Note that even the narrower SIMD shifts do the right thing after that.
725 int32_t mask = (instruction->GetType() == Primitive::kPrimLong)
726 ? kMaxLongShiftDistance
727 : kMaxIntShiftDistance;
728 HInstruction* s = graph_->GetIntConstant(opb->AsIntConstant()->GetValue() & mask);
729 GenerateVecOp(instruction, vector_map_->Get(opa), s, type);
730 }
731 return true;
732 }
733 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700734 // Accept particular intrinsics.
735 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
736 switch (invoke->GetIntrinsic()) {
737 case Intrinsics::kMathAbsInt:
738 case Intrinsics::kMathAbsLong:
739 case Intrinsics::kMathAbsFloat:
740 case Intrinsics::kMathAbsDouble: {
741 // Deal with vector restrictions.
742 if (HasVectorRestrictions(restrictions, kNoAbs) ||
743 HasVectorRestrictions(restrictions, kNoHiBits)) {
744 // TODO: we can do better for some hibits cases.
745 return false;
746 }
747 // Accept ABS(x) for vectorizable operand.
748 HInstruction* opa = instruction->InputAt(0);
749 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
750 if (generate_code) {
751 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
752 }
753 return true;
754 }
755 return false;
756 }
757 default:
758 return false;
759 } // switch
Aart Bik281c6812016-08-26 11:31:48 -0700760 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800761 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700762}
763
Aart Bikf8f5a162017-02-06 15:35:29 -0800764bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
765 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
766 switch (compiler_driver_->GetInstructionSet()) {
767 case kArm:
768 case kThumb2:
769 return false;
770 case kArm64:
771 // Allow vectorization for all ARM devices, because Android assumes that
772 // ARMv8 AArch64 always supports advanced SIMD. For now, only D registers
773 // (64-bit vectors) not Q registers (128-bit vectors).
774 switch (type) {
775 case Primitive::kPrimBoolean:
776 case Primitive::kPrimByte:
Aart Bik6daebeb2017-04-03 14:35:41 -0700777 *restrictions |= kNoDiv | kNoAbs;
Aart Bikf8f5a162017-02-06 15:35:29 -0800778 return TrySetVectorLength(8);
779 case Primitive::kPrimChar:
780 case Primitive::kPrimShort:
Aart Bik6daebeb2017-04-03 14:35:41 -0700781 *restrictions |= kNoDiv | kNoAbs;
Aart Bikf8f5a162017-02-06 15:35:29 -0800782 return TrySetVectorLength(4);
783 case Primitive::kPrimInt:
784 *restrictions |= kNoDiv;
785 return TrySetVectorLength(2);
786 case Primitive::kPrimFloat:
787 return TrySetVectorLength(2);
788 default:
789 return false;
790 }
791 case kX86:
792 case kX86_64:
793 // Allow vectorization for SSE4-enabled X86 devices only (128-bit vectors).
794 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
795 switch (type) {
796 case Primitive::kPrimBoolean:
797 case Primitive::kPrimByte:
Aart Bik6daebeb2017-04-03 14:35:41 -0700798 *restrictions |= kNoMul | kNoDiv | kNoShift | kNoAbs;
Aart Bikf8f5a162017-02-06 15:35:29 -0800799 return TrySetVectorLength(16);
800 case Primitive::kPrimChar:
801 case Primitive::kPrimShort:
Aart Bik6daebeb2017-04-03 14:35:41 -0700802 *restrictions |= kNoDiv | kNoAbs;
Aart Bikf8f5a162017-02-06 15:35:29 -0800803 return TrySetVectorLength(8);
804 case Primitive::kPrimInt:
805 *restrictions |= kNoDiv;
806 return TrySetVectorLength(4);
807 case Primitive::kPrimLong:
Aart Bik6daebeb2017-04-03 14:35:41 -0700808 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs;
Aart Bikf8f5a162017-02-06 15:35:29 -0800809 return TrySetVectorLength(2);
810 case Primitive::kPrimFloat:
811 return TrySetVectorLength(4);
812 case Primitive::kPrimDouble:
813 return TrySetVectorLength(2);
814 default:
815 break;
816 } // switch type
817 }
818 return false;
819 case kMips:
820 case kMips64:
821 // TODO: implement MIPS SIMD.
822 return false;
823 default:
824 return false;
825 } // switch instruction set
826}
827
828bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
829 DCHECK(IsPowerOfTwo(length) && length >= 2u);
830 // First time set?
831 if (vector_length_ == 0) {
832 vector_length_ = length;
833 }
834 // Different types are acceptable within a loop-body, as long as all the corresponding vector
835 // lengths match exactly to obtain a uniform traversal through the vector iteration space
836 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
837 return vector_length_ == length;
838}
839
840void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
841 if (vector_map_->find(org) == vector_map_->end()) {
842 // In scalar code, just use a self pass-through for scalar invariants
843 // (viz. expression remains itself).
844 if (vector_mode_ == kSequential) {
845 vector_map_->Put(org, org);
846 return;
847 }
848 // In vector code, explicit scalar expansion is needed.
849 HInstruction* vector = new (global_allocator_) HVecReplicateScalar(
850 global_allocator_, org, type, vector_length_);
851 vector_map_->Put(org, Insert(vector_preheader_, vector));
852 }
853}
854
855void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
856 if (vector_map_->find(org) == vector_map_->end()) {
857 HInstruction* subscript = vector_phi_;
858 if (offset != nullptr) {
859 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
860 if (org->IsPhi()) {
861 Insert(vector_body_, subscript); // lacks layout placeholder
862 }
863 }
864 vector_map_->Put(org, subscript);
865 }
866}
867
868void HLoopOptimization::GenerateVecMem(HInstruction* org,
869 HInstruction* opa,
870 HInstruction* opb,
871 Primitive::Type type) {
872 HInstruction* vector = nullptr;
873 if (vector_mode_ == kVector) {
874 // Vector store or load.
875 if (opb != nullptr) {
876 vector = new (global_allocator_) HVecStore(
877 global_allocator_, org->InputAt(0), opa, opb, type, vector_length_);
878 } else {
879 vector = new (global_allocator_) HVecLoad(
880 global_allocator_, org->InputAt(0), opa, type, vector_length_);
881 }
882 } else {
883 // Scalar store or load.
884 DCHECK(vector_mode_ == kSequential);
885 if (opb != nullptr) {
886 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
887 } else {
888 vector = new (global_allocator_) HArrayGet(org->InputAt(0), opa, type, kNoDexPc);
889 }
890 }
891 vector_map_->Put(org, vector);
892}
893
894#define GENERATE_VEC(x, y) \
895 if (vector_mode_ == kVector) { \
896 vector = (x); \
897 } else { \
898 DCHECK(vector_mode_ == kSequential); \
899 vector = (y); \
900 } \
901 break;
902
903void HLoopOptimization::GenerateVecOp(HInstruction* org,
904 HInstruction* opa,
905 HInstruction* opb,
906 Primitive::Type type) {
907 if (vector_mode_ == kSequential) {
908 // Scalar code follows implicit integral promotion.
909 if (type == Primitive::kPrimBoolean ||
910 type == Primitive::kPrimByte ||
911 type == Primitive::kPrimChar ||
912 type == Primitive::kPrimShort) {
913 type = Primitive::kPrimInt;
914 }
915 }
916 HInstruction* vector = nullptr;
917 switch (org->GetKind()) {
918 case HInstruction::kNeg:
919 DCHECK(opb == nullptr);
920 GENERATE_VEC(
921 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
922 new (global_allocator_) HNeg(type, opa));
923 case HInstruction::kNot:
924 DCHECK(opb == nullptr);
925 GENERATE_VEC(
926 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
927 new (global_allocator_) HNot(type, opa));
928 case HInstruction::kBooleanNot:
929 DCHECK(opb == nullptr);
930 GENERATE_VEC(
931 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
932 new (global_allocator_) HBooleanNot(opa));
933 case HInstruction::kTypeConversion:
934 DCHECK(opb == nullptr);
935 GENERATE_VEC(
936 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
937 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
938 case HInstruction::kAdd:
939 GENERATE_VEC(
940 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
941 new (global_allocator_) HAdd(type, opa, opb));
942 case HInstruction::kSub:
943 GENERATE_VEC(
944 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
945 new (global_allocator_) HSub(type, opa, opb));
946 case HInstruction::kMul:
947 GENERATE_VEC(
948 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
949 new (global_allocator_) HMul(type, opa, opb));
950 case HInstruction::kDiv:
951 GENERATE_VEC(
952 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
953 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
954 case HInstruction::kAnd:
955 GENERATE_VEC(
956 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
957 new (global_allocator_) HAnd(type, opa, opb));
958 case HInstruction::kOr:
959 GENERATE_VEC(
960 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
961 new (global_allocator_) HOr(type, opa, opb));
962 case HInstruction::kXor:
963 GENERATE_VEC(
964 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
965 new (global_allocator_) HXor(type, opa, opb));
966 case HInstruction::kShl:
967 GENERATE_VEC(
968 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
969 new (global_allocator_) HShl(type, opa, opb));
970 case HInstruction::kShr:
971 GENERATE_VEC(
972 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
973 new (global_allocator_) HShr(type, opa, opb));
974 case HInstruction::kUShr:
975 GENERATE_VEC(
976 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
977 new (global_allocator_) HUShr(type, opa, opb));
978 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -0700979 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
980 if (vector_mode_ == kVector) {
981 switch (invoke->GetIntrinsic()) {
982 case Intrinsics::kMathAbsInt:
983 case Intrinsics::kMathAbsLong:
984 case Intrinsics::kMathAbsFloat:
985 case Intrinsics::kMathAbsDouble:
986 DCHECK(opb == nullptr);
987 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
988 break;
989 default:
990 LOG(FATAL) << "Unsupported SIMD intrinsic";
991 UNREACHABLE();
992 } // switch invoke
993 } else {
994 // In scalar code, simply clone the method invoke, and replace its operands
995 // with the corresponding new scalar instructions in the loop.
996 DCHECK(vector_mode_ == kSequential);
997 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
998 global_allocator_,
999 invoke->GetNumberOfArguments(),
1000 invoke->GetType(),
1001 invoke->GetDexPc(),
1002 invoke->GetDexMethodIndex(),
1003 invoke->GetResolvedMethod(),
1004 invoke->GetDispatchInfo(),
1005 invoke->GetInvokeType(),
1006 invoke->GetTargetMethod(),
1007 invoke->GetClinitCheckRequirement());
1008 HInputsRef inputs = invoke->GetInputs();
1009 for (size_t index = 0; index < inputs.size(); ++index) {
1010 new_invoke->SetArgumentAt(index, vector_map_->Get(inputs[index]));
1011 }
1012 vector = new_invoke;
1013 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001014 break;
1015 }
1016 default:
1017 break;
1018 } // switch
1019 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1020 vector_map_->Put(org, vector);
1021}
1022
1023#undef GENERATE_VEC
1024
1025//
1026// Helpers.
1027//
1028
1029bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
1030 DCHECK(iset_->empty());
Aart Bikcc42be02016-10-20 16:14:16 -07001031 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1032 if (set != nullptr) {
1033 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001034 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001035 // each instruction is removable and, when restrict uses are requested, other than for phi,
1036 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001037 if (!i->IsInBlock()) {
1038 continue;
1039 } else if (!i->IsRemovable()) {
1040 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001041 } else if (i != phi && restrict_uses) {
Aart Bikcc42be02016-10-20 16:14:16 -07001042 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1043 if (set->find(use.GetUser()) == set->end()) {
1044 return false;
1045 }
1046 }
1047 }
Aart Bike3dedc52016-11-02 17:50:27 -07001048 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001049 }
Aart Bikcc42be02016-10-20 16:14:16 -07001050 return true;
1051 }
1052 return false;
1053}
1054
1055// Find: phi: Phi(init, addsub)
1056// s: SuspendCheck
1057// c: Condition(phi, bound)
1058// i: If(c)
1059// TODO: Find a less pattern matching approach?
Aart Bikf8f5a162017-02-06 15:35:29 -08001060bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block) {
Aart Bikcc42be02016-10-20 16:14:16 -07001061 DCHECK(iset_->empty());
1062 HInstruction* phi = block->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -08001063 if (phi != nullptr &&
1064 phi->GetNext() == nullptr &&
1065 TrySetPhiInduction(phi->AsPhi(), /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001066 HInstruction* s = block->GetFirstInstruction();
1067 if (s != nullptr && s->IsSuspendCheck()) {
1068 HInstruction* c = s->GetNext();
1069 if (c != nullptr && c->IsCondition() && c->GetUses().HasExactlyOneElement()) {
1070 HInstruction* i = c->GetNext();
1071 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1072 iset_->insert(c);
1073 iset_->insert(s);
1074 return true;
1075 }
1076 }
1077 }
1078 }
1079 return false;
1080}
1081
1082bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001083 if (!block->GetPhis().IsEmpty()) {
1084 return false;
1085 }
1086 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1087 HInstruction* instruction = it.Current();
1088 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1089 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001090 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001091 }
1092 return true;
1093}
1094
1095bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1096 HInstruction* instruction) {
1097 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1098 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1099 return true;
1100 }
Aart Bikcc42be02016-10-20 16:14:16 -07001101 }
1102 return false;
1103}
1104
Aart Bik482095d2016-10-10 15:39:10 -07001105bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001106 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001107 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001108 /*out*/ int32_t* use_count) {
1109 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1110 HInstruction* user = use.GetUser();
1111 if (iset_->find(user) == iset_->end()) { // not excluded?
1112 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001113 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001114 // If collect_loop_uses is set, simply keep adding those uses to the set.
1115 // Otherwise, reject uses inside the loop that were not already in the set.
1116 if (collect_loop_uses) {
1117 iset_->insert(user);
1118 continue;
1119 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001120 return false;
1121 }
1122 ++*use_count;
1123 }
1124 }
1125 return true;
1126}
1127
Aart Bik807868e2016-11-03 17:51:43 -07001128bool HLoopOptimization::TryReplaceWithLastValue(HInstruction* instruction, HBasicBlock* block) {
1129 // Try to replace outside uses with the last value. Environment uses can consume this
1130 // value too, since any first true use is outside the loop (although this may imply
1131 // that de-opting may look "ahead" a bit on the phi value). If there are only environment
1132 // uses, the value is dropped altogether, since the computations have no effect.
1133 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001134 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
1135 const HUseList<HInstruction*>& uses = instruction->GetUses();
1136 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1137 HInstruction* user = it->GetUser();
1138 size_t index = it->GetIndex();
1139 ++it; // increment before replacing
1140 if (iset_->find(user) == iset_->end()) { // not excluded?
1141 user->ReplaceInput(replacement, index);
1142 induction_range_.Replace(user, instruction, replacement); // update induction
1143 }
1144 }
1145 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1146 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1147 HEnvironment* user = it->GetUser();
1148 size_t index = it->GetIndex();
1149 ++it; // increment before replacing
1150 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
1151 user->RemoveAsUserOfInput(index);
1152 user->SetRawEnvAt(index, replacement);
1153 replacement->AddEnvUseAt(user, index);
1154 }
1155 }
1156 induction_simplication_count_++;
Aart Bik807868e2016-11-03 17:51:43 -07001157 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001158 }
Aart Bik807868e2016-11-03 17:51:43 -07001159 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001160}
1161
Aart Bikf8f5a162017-02-06 15:35:29 -08001162bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1163 HInstruction* instruction,
1164 HBasicBlock* block,
1165 bool collect_loop_uses) {
1166 // Assigning the last value is always successful if there are no uses.
1167 // Otherwise, it succeeds in a no early-exit loop by generating the
1168 // proper last value assignment.
1169 int32_t use_count = 0;
1170 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
1171 (use_count == 0 ||
1172 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(instruction, block)));
1173}
1174
Aart Bik6b69e0a2017-01-11 10:20:43 -08001175void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
1176 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
1177 HInstruction* instruction = i.Current();
1178 if (instruction->IsDeadAndRemovable()) {
1179 simplified_ = true;
1180 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
1181 }
1182 }
1183}
1184
Aart Bik281c6812016-08-26 11:31:48 -07001185} // namespace art