blob: 1a79601a934e5b7fb318bc260eb8cbca40427d36 [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 Bik24b905f2017-04-06 09:59:06 -0700547 // Generate body from the instruction map, but in original program order.
Aart Bikb07d1bc2017-04-05 10:03:15 -0700548 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()) {
Aart Bik24b905f2017-04-06 09:59:06 -0700552 Insert(vector_body_, i->second);
553 // Deal with instructions that need an environment, such as the scalar intrinsics.
Aart Bikf8f5a162017-02-06 15:35:29 -0800554 if (i->second->NeedsEnvironment()) {
Aart Bikb07d1bc2017-04-05 10:03:15 -0700555 i->second->CopyEnvironmentFromWithLoopPhiAdjustment(env, vector_header_);
Aart Bikf8f5a162017-02-06 15:35:29 -0800556 }
557 }
558 }
559 // Finalize increment and phi.
560 HInstruction* inc = new (global_allocator_) HAdd(induc_type, vector_phi_, step);
561 vector_phi_->AddInput(lo);
562 vector_phi_->AddInput(Insert(vector_body_, inc));
563}
564
565// TODO: accept reductions at left-hand-side, mixed-type store idioms, etc.
566bool HLoopOptimization::VectorizeDef(LoopNode* node,
567 HInstruction* instruction,
568 bool generate_code) {
569 // Accept a left-hand-side array base[index] for
570 // (1) supported vector type,
571 // (2) loop-invariant base,
572 // (3) unit stride index,
573 // (4) vectorizable right-hand-side value.
574 uint64_t restrictions = kNone;
575 if (instruction->IsArraySet()) {
576 Primitive::Type type = instruction->AsArraySet()->GetComponentType();
577 HInstruction* base = instruction->InputAt(0);
578 HInstruction* index = instruction->InputAt(1);
579 HInstruction* value = instruction->InputAt(2);
580 HInstruction* offset = nullptr;
581 if (TrySetVectorType(type, &restrictions) &&
582 node->loop_info->IsDefinedOutOfTheLoop(base) &&
583 induction_range_.IsUnitStride(index, &offset) &&
584 VectorizeUse(node, value, generate_code, type, restrictions)) {
585 if (generate_code) {
586 GenerateVecSub(index, offset);
587 GenerateVecMem(instruction, vector_map_->Get(index), vector_map_->Get(value), type);
588 } else {
589 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ true));
590 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800591 return true;
592 }
Aart Bikf8f5a162017-02-06 15:35:29 -0800593 return false;
594 }
595 // Branch back okay.
596 if (instruction->IsGoto()) {
597 return true;
598 }
599 // Otherwise accept only expressions with no effects outside the immediate loop-body.
600 // Note that actual uses are inspected during right-hand-side tree traversal.
601 return !IsUsedOutsideLoop(node->loop_info, instruction) && !instruction->DoesAnyWrite();
602}
603
604// TODO: more operations and intrinsics, detect saturation arithmetic, etc.
605bool HLoopOptimization::VectorizeUse(LoopNode* node,
606 HInstruction* instruction,
607 bool generate_code,
608 Primitive::Type type,
609 uint64_t restrictions) {
610 // Accept anything for which code has already been generated.
611 if (generate_code) {
612 if (vector_map_->find(instruction) != vector_map_->end()) {
613 return true;
614 }
615 }
616 // Continue the right-hand-side tree traversal, passing in proper
617 // types and vector restrictions along the way. During code generation,
618 // all new nodes are drawn from the global allocator.
619 if (node->loop_info->IsDefinedOutOfTheLoop(instruction)) {
620 // Accept invariant use, using scalar expansion.
621 if (generate_code) {
622 GenerateVecInv(instruction, type);
623 }
624 return true;
625 } else if (instruction->IsArrayGet()) {
626 // Accept a right-hand-side array base[index] for
627 // (1) exact matching vector type,
628 // (2) loop-invariant base,
629 // (3) unit stride index,
630 // (4) vectorizable right-hand-side value.
631 HInstruction* base = instruction->InputAt(0);
632 HInstruction* index = instruction->InputAt(1);
633 HInstruction* offset = nullptr;
634 if (type == instruction->GetType() &&
635 node->loop_info->IsDefinedOutOfTheLoop(base) &&
636 induction_range_.IsUnitStride(index, &offset)) {
637 if (generate_code) {
638 GenerateVecSub(index, offset);
639 GenerateVecMem(instruction, vector_map_->Get(index), nullptr, type);
640 } else {
641 vector_refs_->insert(ArrayReference(base, offset, type, /*lhs*/ false));
642 }
643 return true;
644 }
645 } else if (instruction->IsTypeConversion()) {
646 // Accept particular type conversions.
647 HTypeConversion* conversion = instruction->AsTypeConversion();
648 HInstruction* opa = conversion->InputAt(0);
649 Primitive::Type from = conversion->GetInputType();
650 Primitive::Type to = conversion->GetResultType();
651 if ((to == Primitive::kPrimByte ||
652 to == Primitive::kPrimChar ||
653 to == Primitive::kPrimShort) && from == Primitive::kPrimInt) {
654 // Accept a "narrowing" type conversion from a "wider" computation for
655 // (1) conversion into final required type,
656 // (2) vectorizable operand,
657 // (3) "wider" operations cannot bring in higher order bits.
658 if (to == type && VectorizeUse(node, opa, generate_code, type, restrictions | kNoHiBits)) {
659 if (generate_code) {
660 if (vector_mode_ == kVector) {
661 vector_map_->Put(instruction, vector_map_->Get(opa)); // operand pass-through
662 } else {
663 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
664 }
665 }
666 return true;
667 }
668 } else if (to == Primitive::kPrimFloat && from == Primitive::kPrimInt) {
669 DCHECK_EQ(to, type);
670 // Accept int to float conversion for
671 // (1) supported int,
672 // (2) vectorizable operand.
673 if (TrySetVectorType(from, &restrictions) &&
674 VectorizeUse(node, opa, generate_code, from, restrictions)) {
675 if (generate_code) {
676 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
677 }
678 return true;
679 }
680 }
681 return false;
682 } else if (instruction->IsNeg() || instruction->IsNot() || instruction->IsBooleanNot()) {
683 // Accept unary operator for vectorizable operand.
684 HInstruction* opa = instruction->InputAt(0);
685 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
686 if (generate_code) {
687 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
688 }
689 return true;
690 }
691 } else if (instruction->IsAdd() || instruction->IsSub() ||
692 instruction->IsMul() || instruction->IsDiv() ||
693 instruction->IsAnd() || instruction->IsOr() || instruction->IsXor()) {
694 // Deal with vector restrictions.
695 if ((instruction->IsMul() && HasVectorRestrictions(restrictions, kNoMul)) ||
696 (instruction->IsDiv() && HasVectorRestrictions(restrictions, kNoDiv))) {
697 return false;
698 }
699 // Accept binary operator for vectorizable operands.
700 HInstruction* opa = instruction->InputAt(0);
701 HInstruction* opb = instruction->InputAt(1);
702 if (VectorizeUse(node, opa, generate_code, type, restrictions) &&
703 VectorizeUse(node, opb, generate_code, type, restrictions)) {
704 if (generate_code) {
705 GenerateVecOp(instruction, vector_map_->Get(opa), vector_map_->Get(opb), type);
706 }
707 return true;
708 }
709 } else if (instruction->IsShl() || instruction->IsShr() || instruction->IsUShr()) {
710 // Deal with vector restrictions.
711 if ((HasVectorRestrictions(restrictions, kNoShift)) ||
712 (instruction->IsShr() && HasVectorRestrictions(restrictions, kNoShr))) {
713 return false; // unsupported instruction
714 } else if ((instruction->IsShr() || instruction->IsUShr()) &&
715 HasVectorRestrictions(restrictions, kNoHiBits)) {
716 return false; // hibits may impact lobits; TODO: we can do better!
717 }
718 // Accept shift operator for vectorizable/invariant operands.
719 // TODO: accept symbolic, albeit loop invariant shift factors.
720 HInstruction* opa = instruction->InputAt(0);
721 HInstruction* opb = instruction->InputAt(1);
722 if (VectorizeUse(node, opa, generate_code, type, restrictions) && opb->IsIntConstant()) {
723 if (generate_code) {
724 // Make sure shift factor only looks at lower bits, as defined for sequential shifts.
725 // Note that even the narrower SIMD shifts do the right thing after that.
726 int32_t mask = (instruction->GetType() == Primitive::kPrimLong)
727 ? kMaxLongShiftDistance
728 : kMaxIntShiftDistance;
729 HInstruction* s = graph_->GetIntConstant(opb->AsIntConstant()->GetValue() & mask);
730 GenerateVecOp(instruction, vector_map_->Get(opa), s, type);
731 }
732 return true;
733 }
734 } else if (instruction->IsInvokeStaticOrDirect()) {
Aart Bik6daebeb2017-04-03 14:35:41 -0700735 // Accept particular intrinsics.
736 HInvokeStaticOrDirect* invoke = instruction->AsInvokeStaticOrDirect();
737 switch (invoke->GetIntrinsic()) {
738 case Intrinsics::kMathAbsInt:
739 case Intrinsics::kMathAbsLong:
740 case Intrinsics::kMathAbsFloat:
741 case Intrinsics::kMathAbsDouble: {
742 // Deal with vector restrictions.
743 if (HasVectorRestrictions(restrictions, kNoAbs) ||
744 HasVectorRestrictions(restrictions, kNoHiBits)) {
745 // TODO: we can do better for some hibits cases.
746 return false;
747 }
748 // Accept ABS(x) for vectorizable operand.
749 HInstruction* opa = instruction->InputAt(0);
750 if (VectorizeUse(node, opa, generate_code, type, restrictions)) {
751 if (generate_code) {
752 GenerateVecOp(instruction, vector_map_->Get(opa), nullptr, type);
753 }
754 return true;
755 }
756 return false;
757 }
758 default:
759 return false;
760 } // switch
Aart Bik281c6812016-08-26 11:31:48 -0700761 }
Aart Bik6b69e0a2017-01-11 10:20:43 -0800762 return false;
Aart Bik281c6812016-08-26 11:31:48 -0700763}
764
Aart Bikf8f5a162017-02-06 15:35:29 -0800765bool HLoopOptimization::TrySetVectorType(Primitive::Type type, uint64_t* restrictions) {
766 const InstructionSetFeatures* features = compiler_driver_->GetInstructionSetFeatures();
767 switch (compiler_driver_->GetInstructionSet()) {
768 case kArm:
769 case kThumb2:
770 return false;
771 case kArm64:
772 // Allow vectorization for all ARM devices, because Android assumes that
773 // ARMv8 AArch64 always supports advanced SIMD. For now, only D registers
774 // (64-bit vectors) not Q registers (128-bit vectors).
775 switch (type) {
776 case Primitive::kPrimBoolean:
777 case Primitive::kPrimByte:
Aart Bik6daebeb2017-04-03 14:35:41 -0700778 *restrictions |= kNoDiv | kNoAbs;
Aart Bikf8f5a162017-02-06 15:35:29 -0800779 return TrySetVectorLength(8);
780 case Primitive::kPrimChar:
781 case Primitive::kPrimShort:
Aart Bik6daebeb2017-04-03 14:35:41 -0700782 *restrictions |= kNoDiv | kNoAbs;
Aart Bikf8f5a162017-02-06 15:35:29 -0800783 return TrySetVectorLength(4);
784 case Primitive::kPrimInt:
785 *restrictions |= kNoDiv;
786 return TrySetVectorLength(2);
787 case Primitive::kPrimFloat:
788 return TrySetVectorLength(2);
789 default:
790 return false;
791 }
792 case kX86:
793 case kX86_64:
794 // Allow vectorization for SSE4-enabled X86 devices only (128-bit vectors).
795 if (features->AsX86InstructionSetFeatures()->HasSSE4_1()) {
796 switch (type) {
797 case Primitive::kPrimBoolean:
798 case Primitive::kPrimByte:
Aart Bik6daebeb2017-04-03 14:35:41 -0700799 *restrictions |= kNoMul | kNoDiv | kNoShift | kNoAbs;
Aart Bikf8f5a162017-02-06 15:35:29 -0800800 return TrySetVectorLength(16);
801 case Primitive::kPrimChar:
802 case Primitive::kPrimShort:
Aart Bik6daebeb2017-04-03 14:35:41 -0700803 *restrictions |= kNoDiv | kNoAbs;
Aart Bikf8f5a162017-02-06 15:35:29 -0800804 return TrySetVectorLength(8);
805 case Primitive::kPrimInt:
806 *restrictions |= kNoDiv;
807 return TrySetVectorLength(4);
808 case Primitive::kPrimLong:
Aart Bik6daebeb2017-04-03 14:35:41 -0700809 *restrictions |= kNoMul | kNoDiv | kNoShr | kNoAbs;
Aart Bikf8f5a162017-02-06 15:35:29 -0800810 return TrySetVectorLength(2);
811 case Primitive::kPrimFloat:
812 return TrySetVectorLength(4);
813 case Primitive::kPrimDouble:
814 return TrySetVectorLength(2);
815 default:
816 break;
817 } // switch type
818 }
819 return false;
820 case kMips:
821 case kMips64:
822 // TODO: implement MIPS SIMD.
823 return false;
824 default:
825 return false;
826 } // switch instruction set
827}
828
829bool HLoopOptimization::TrySetVectorLength(uint32_t length) {
830 DCHECK(IsPowerOfTwo(length) && length >= 2u);
831 // First time set?
832 if (vector_length_ == 0) {
833 vector_length_ = length;
834 }
835 // Different types are acceptable within a loop-body, as long as all the corresponding vector
836 // lengths match exactly to obtain a uniform traversal through the vector iteration space
837 // (idiomatic exceptions to this rule can be handled by further unrolling sub-expressions).
838 return vector_length_ == length;
839}
840
841void HLoopOptimization::GenerateVecInv(HInstruction* org, Primitive::Type type) {
842 if (vector_map_->find(org) == vector_map_->end()) {
843 // In scalar code, just use a self pass-through for scalar invariants
844 // (viz. expression remains itself).
845 if (vector_mode_ == kSequential) {
846 vector_map_->Put(org, org);
847 return;
848 }
849 // In vector code, explicit scalar expansion is needed.
850 HInstruction* vector = new (global_allocator_) HVecReplicateScalar(
851 global_allocator_, org, type, vector_length_);
852 vector_map_->Put(org, Insert(vector_preheader_, vector));
853 }
854}
855
856void HLoopOptimization::GenerateVecSub(HInstruction* org, HInstruction* offset) {
857 if (vector_map_->find(org) == vector_map_->end()) {
858 HInstruction* subscript = vector_phi_;
859 if (offset != nullptr) {
860 subscript = new (global_allocator_) HAdd(Primitive::kPrimInt, subscript, offset);
861 if (org->IsPhi()) {
862 Insert(vector_body_, subscript); // lacks layout placeholder
863 }
864 }
865 vector_map_->Put(org, subscript);
866 }
867}
868
869void HLoopOptimization::GenerateVecMem(HInstruction* org,
870 HInstruction* opa,
871 HInstruction* opb,
872 Primitive::Type type) {
873 HInstruction* vector = nullptr;
874 if (vector_mode_ == kVector) {
875 // Vector store or load.
876 if (opb != nullptr) {
877 vector = new (global_allocator_) HVecStore(
878 global_allocator_, org->InputAt(0), opa, opb, type, vector_length_);
879 } else {
880 vector = new (global_allocator_) HVecLoad(
881 global_allocator_, org->InputAt(0), opa, type, vector_length_);
882 }
883 } else {
884 // Scalar store or load.
885 DCHECK(vector_mode_ == kSequential);
886 if (opb != nullptr) {
887 vector = new (global_allocator_) HArraySet(org->InputAt(0), opa, opb, type, kNoDexPc);
888 } else {
889 vector = new (global_allocator_) HArrayGet(org->InputAt(0), opa, type, kNoDexPc);
890 }
891 }
892 vector_map_->Put(org, vector);
893}
894
895#define GENERATE_VEC(x, y) \
896 if (vector_mode_ == kVector) { \
897 vector = (x); \
898 } else { \
899 DCHECK(vector_mode_ == kSequential); \
900 vector = (y); \
901 } \
902 break;
903
904void HLoopOptimization::GenerateVecOp(HInstruction* org,
905 HInstruction* opa,
906 HInstruction* opb,
907 Primitive::Type type) {
908 if (vector_mode_ == kSequential) {
909 // Scalar code follows implicit integral promotion.
910 if (type == Primitive::kPrimBoolean ||
911 type == Primitive::kPrimByte ||
912 type == Primitive::kPrimChar ||
913 type == Primitive::kPrimShort) {
914 type = Primitive::kPrimInt;
915 }
916 }
917 HInstruction* vector = nullptr;
918 switch (org->GetKind()) {
919 case HInstruction::kNeg:
920 DCHECK(opb == nullptr);
921 GENERATE_VEC(
922 new (global_allocator_) HVecNeg(global_allocator_, opa, type, vector_length_),
923 new (global_allocator_) HNeg(type, opa));
924 case HInstruction::kNot:
925 DCHECK(opb == nullptr);
926 GENERATE_VEC(
927 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
928 new (global_allocator_) HNot(type, opa));
929 case HInstruction::kBooleanNot:
930 DCHECK(opb == nullptr);
931 GENERATE_VEC(
932 new (global_allocator_) HVecNot(global_allocator_, opa, type, vector_length_),
933 new (global_allocator_) HBooleanNot(opa));
934 case HInstruction::kTypeConversion:
935 DCHECK(opb == nullptr);
936 GENERATE_VEC(
937 new (global_allocator_) HVecCnv(global_allocator_, opa, type, vector_length_),
938 new (global_allocator_) HTypeConversion(type, opa, kNoDexPc));
939 case HInstruction::kAdd:
940 GENERATE_VEC(
941 new (global_allocator_) HVecAdd(global_allocator_, opa, opb, type, vector_length_),
942 new (global_allocator_) HAdd(type, opa, opb));
943 case HInstruction::kSub:
944 GENERATE_VEC(
945 new (global_allocator_) HVecSub(global_allocator_, opa, opb, type, vector_length_),
946 new (global_allocator_) HSub(type, opa, opb));
947 case HInstruction::kMul:
948 GENERATE_VEC(
949 new (global_allocator_) HVecMul(global_allocator_, opa, opb, type, vector_length_),
950 new (global_allocator_) HMul(type, opa, opb));
951 case HInstruction::kDiv:
952 GENERATE_VEC(
953 new (global_allocator_) HVecDiv(global_allocator_, opa, opb, type, vector_length_),
954 new (global_allocator_) HDiv(type, opa, opb, kNoDexPc));
955 case HInstruction::kAnd:
956 GENERATE_VEC(
957 new (global_allocator_) HVecAnd(global_allocator_, opa, opb, type, vector_length_),
958 new (global_allocator_) HAnd(type, opa, opb));
959 case HInstruction::kOr:
960 GENERATE_VEC(
961 new (global_allocator_) HVecOr(global_allocator_, opa, opb, type, vector_length_),
962 new (global_allocator_) HOr(type, opa, opb));
963 case HInstruction::kXor:
964 GENERATE_VEC(
965 new (global_allocator_) HVecXor(global_allocator_, opa, opb, type, vector_length_),
966 new (global_allocator_) HXor(type, opa, opb));
967 case HInstruction::kShl:
968 GENERATE_VEC(
969 new (global_allocator_) HVecShl(global_allocator_, opa, opb, type, vector_length_),
970 new (global_allocator_) HShl(type, opa, opb));
971 case HInstruction::kShr:
972 GENERATE_VEC(
973 new (global_allocator_) HVecShr(global_allocator_, opa, opb, type, vector_length_),
974 new (global_allocator_) HShr(type, opa, opb));
975 case HInstruction::kUShr:
976 GENERATE_VEC(
977 new (global_allocator_) HVecUShr(global_allocator_, opa, opb, type, vector_length_),
978 new (global_allocator_) HUShr(type, opa, opb));
979 case HInstruction::kInvokeStaticOrDirect: {
Aart Bik6daebeb2017-04-03 14:35:41 -0700980 HInvokeStaticOrDirect* invoke = org->AsInvokeStaticOrDirect();
981 if (vector_mode_ == kVector) {
982 switch (invoke->GetIntrinsic()) {
983 case Intrinsics::kMathAbsInt:
984 case Intrinsics::kMathAbsLong:
985 case Intrinsics::kMathAbsFloat:
986 case Intrinsics::kMathAbsDouble:
987 DCHECK(opb == nullptr);
988 vector = new (global_allocator_) HVecAbs(global_allocator_, opa, type, vector_length_);
989 break;
990 default:
991 LOG(FATAL) << "Unsupported SIMD intrinsic";
992 UNREACHABLE();
993 } // switch invoke
994 } else {
Aart Bik24b905f2017-04-06 09:59:06 -0700995 // In scalar code, simply clone the method invoke, and replace its operands with the
996 // corresponding new scalar instructions in the loop. The instruction will get an
997 // environment while being inserted from the instruction map in original program order.
Aart Bik6daebeb2017-04-03 14:35:41 -0700998 DCHECK(vector_mode_ == kSequential);
999 HInvokeStaticOrDirect* new_invoke = new (global_allocator_) HInvokeStaticOrDirect(
1000 global_allocator_,
1001 invoke->GetNumberOfArguments(),
1002 invoke->GetType(),
1003 invoke->GetDexPc(),
1004 invoke->GetDexMethodIndex(),
1005 invoke->GetResolvedMethod(),
1006 invoke->GetDispatchInfo(),
1007 invoke->GetInvokeType(),
1008 invoke->GetTargetMethod(),
1009 invoke->GetClinitCheckRequirement());
1010 HInputsRef inputs = invoke->GetInputs();
1011 for (size_t index = 0; index < inputs.size(); ++index) {
1012 new_invoke->SetArgumentAt(index, vector_map_->Get(inputs[index]));
1013 }
1014 vector = new_invoke;
1015 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001016 break;
1017 }
1018 default:
1019 break;
1020 } // switch
1021 CHECK(vector != nullptr) << "Unsupported SIMD operator";
1022 vector_map_->Put(org, vector);
1023}
1024
1025#undef GENERATE_VEC
1026
1027//
1028// Helpers.
1029//
1030
1031bool HLoopOptimization::TrySetPhiInduction(HPhi* phi, bool restrict_uses) {
1032 DCHECK(iset_->empty());
Aart Bikcc42be02016-10-20 16:14:16 -07001033 ArenaSet<HInstruction*>* set = induction_range_.LookupCycle(phi);
1034 if (set != nullptr) {
1035 for (HInstruction* i : *set) {
Aart Bike3dedc52016-11-02 17:50:27 -07001036 // Check that, other than instructions that are no longer in the graph (removed earlier)
Aart Bikf8f5a162017-02-06 15:35:29 -08001037 // each instruction is removable and, when restrict uses are requested, other than for phi,
1038 // all uses are contained within the cycle.
Aart Bike3dedc52016-11-02 17:50:27 -07001039 if (!i->IsInBlock()) {
1040 continue;
1041 } else if (!i->IsRemovable()) {
1042 return false;
Aart Bikf8f5a162017-02-06 15:35:29 -08001043 } else if (i != phi && restrict_uses) {
Aart Bikcc42be02016-10-20 16:14:16 -07001044 for (const HUseListNode<HInstruction*>& use : i->GetUses()) {
1045 if (set->find(use.GetUser()) == set->end()) {
1046 return false;
1047 }
1048 }
1049 }
Aart Bike3dedc52016-11-02 17:50:27 -07001050 iset_->insert(i); // copy
Aart Bikcc42be02016-10-20 16:14:16 -07001051 }
Aart Bikcc42be02016-10-20 16:14:16 -07001052 return true;
1053 }
1054 return false;
1055}
1056
1057// Find: phi: Phi(init, addsub)
1058// s: SuspendCheck
1059// c: Condition(phi, bound)
1060// i: If(c)
1061// TODO: Find a less pattern matching approach?
Aart Bikf8f5a162017-02-06 15:35:29 -08001062bool HLoopOptimization::TrySetSimpleLoopHeader(HBasicBlock* block) {
Aart Bikcc42be02016-10-20 16:14:16 -07001063 DCHECK(iset_->empty());
1064 HInstruction* phi = block->GetFirstPhi();
Aart Bikf8f5a162017-02-06 15:35:29 -08001065 if (phi != nullptr &&
1066 phi->GetNext() == nullptr &&
1067 TrySetPhiInduction(phi->AsPhi(), /*restrict_uses*/ false)) {
Aart Bikcc42be02016-10-20 16:14:16 -07001068 HInstruction* s = block->GetFirstInstruction();
1069 if (s != nullptr && s->IsSuspendCheck()) {
1070 HInstruction* c = s->GetNext();
1071 if (c != nullptr && c->IsCondition() && c->GetUses().HasExactlyOneElement()) {
1072 HInstruction* i = c->GetNext();
1073 if (i != nullptr && i->IsIf() && i->InputAt(0) == c) {
1074 iset_->insert(c);
1075 iset_->insert(s);
1076 return true;
1077 }
1078 }
1079 }
1080 }
1081 return false;
1082}
1083
1084bool HLoopOptimization::IsEmptyBody(HBasicBlock* block) {
Aart Bikf8f5a162017-02-06 15:35:29 -08001085 if (!block->GetPhis().IsEmpty()) {
1086 return false;
1087 }
1088 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1089 HInstruction* instruction = it.Current();
1090 if (!instruction->IsGoto() && iset_->find(instruction) == iset_->end()) {
1091 return false;
Aart Bikcc42be02016-10-20 16:14:16 -07001092 }
Aart Bikf8f5a162017-02-06 15:35:29 -08001093 }
1094 return true;
1095}
1096
1097bool HLoopOptimization::IsUsedOutsideLoop(HLoopInformation* loop_info,
1098 HInstruction* instruction) {
1099 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1100 if (use.GetUser()->GetBlock()->GetLoopInformation() != loop_info) {
1101 return true;
1102 }
Aart Bikcc42be02016-10-20 16:14:16 -07001103 }
1104 return false;
1105}
1106
Aart Bik482095d2016-10-10 15:39:10 -07001107bool HLoopOptimization::IsOnlyUsedAfterLoop(HLoopInformation* loop_info,
Aart Bik8c4a8542016-10-06 11:36:57 -07001108 HInstruction* instruction,
Aart Bik6b69e0a2017-01-11 10:20:43 -08001109 bool collect_loop_uses,
Aart Bik8c4a8542016-10-06 11:36:57 -07001110 /*out*/ int32_t* use_count) {
1111 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
1112 HInstruction* user = use.GetUser();
1113 if (iset_->find(user) == iset_->end()) { // not excluded?
1114 HLoopInformation* other_loop_info = user->GetBlock()->GetLoopInformation();
Aart Bik482095d2016-10-10 15:39:10 -07001115 if (other_loop_info != nullptr && other_loop_info->IsIn(*loop_info)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001116 // If collect_loop_uses is set, simply keep adding those uses to the set.
1117 // Otherwise, reject uses inside the loop that were not already in the set.
1118 if (collect_loop_uses) {
1119 iset_->insert(user);
1120 continue;
1121 }
Aart Bik8c4a8542016-10-06 11:36:57 -07001122 return false;
1123 }
1124 ++*use_count;
1125 }
1126 }
1127 return true;
1128}
1129
Aart Bik807868e2016-11-03 17:51:43 -07001130bool HLoopOptimization::TryReplaceWithLastValue(HInstruction* instruction, HBasicBlock* block) {
1131 // Try to replace outside uses with the last value. Environment uses can consume this
1132 // value too, since any first true use is outside the loop (although this may imply
1133 // that de-opting may look "ahead" a bit on the phi value). If there are only environment
1134 // uses, the value is dropped altogether, since the computations have no effect.
1135 if (induction_range_.CanGenerateLastValue(instruction)) {
Aart Bik6b69e0a2017-01-11 10:20:43 -08001136 HInstruction* replacement = induction_range_.GenerateLastValue(instruction, graph_, block);
1137 const HUseList<HInstruction*>& uses = instruction->GetUses();
1138 for (auto it = uses.begin(), end = uses.end(); it != end;) {
1139 HInstruction* user = it->GetUser();
1140 size_t index = it->GetIndex();
1141 ++it; // increment before replacing
1142 if (iset_->find(user) == iset_->end()) { // not excluded?
1143 user->ReplaceInput(replacement, index);
1144 induction_range_.Replace(user, instruction, replacement); // update induction
1145 }
1146 }
1147 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1148 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
1149 HEnvironment* user = it->GetUser();
1150 size_t index = it->GetIndex();
1151 ++it; // increment before replacing
1152 if (iset_->find(user->GetHolder()) == iset_->end()) { // not excluded?
1153 user->RemoveAsUserOfInput(index);
1154 user->SetRawEnvAt(index, replacement);
1155 replacement->AddEnvUseAt(user, index);
1156 }
1157 }
1158 induction_simplication_count_++;
Aart Bik807868e2016-11-03 17:51:43 -07001159 return true;
Aart Bik8c4a8542016-10-06 11:36:57 -07001160 }
Aart Bik807868e2016-11-03 17:51:43 -07001161 return false;
Aart Bik8c4a8542016-10-06 11:36:57 -07001162}
1163
Aart Bikf8f5a162017-02-06 15:35:29 -08001164bool HLoopOptimization::TryAssignLastValue(HLoopInformation* loop_info,
1165 HInstruction* instruction,
1166 HBasicBlock* block,
1167 bool collect_loop_uses) {
1168 // Assigning the last value is always successful if there are no uses.
1169 // Otherwise, it succeeds in a no early-exit loop by generating the
1170 // proper last value assignment.
1171 int32_t use_count = 0;
1172 return IsOnlyUsedAfterLoop(loop_info, instruction, collect_loop_uses, &use_count) &&
1173 (use_count == 0 ||
1174 (!IsEarlyExit(loop_info) && TryReplaceWithLastValue(instruction, block)));
1175}
1176
Aart Bik6b69e0a2017-01-11 10:20:43 -08001177void HLoopOptimization::RemoveDeadInstructions(const HInstructionList& list) {
1178 for (HBackwardInstructionIterator i(list); !i.Done(); i.Advance()) {
1179 HInstruction* instruction = i.Current();
1180 if (instruction->IsDeadAndRemovable()) {
1181 simplified_ = true;
1182 instruction->GetBlock()->RemoveInstructionOrPhi(instruction);
1183 }
1184 }
1185}
1186
Aart Bik281c6812016-08-26 11:31:48 -07001187} // namespace art