blob: ec53366e198ad2d793de437a42aa1bfa9f48d34b [file] [log] [blame]
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001/*
2 * Copyright (C) 2014 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 "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000018
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010019#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000020#include "utils/growable_array.h"
21
22namespace art {
23
24void HGraph::AddBlock(HBasicBlock* block) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000025 block->SetBlockId(blocks_.Size());
Nicolas Geoffray818f2102014-02-18 16:43:35 +000026 blocks_.Add(block);
27}
28
Nicolas Geoffray804d0932014-05-02 08:46:00 +010029void HGraph::FindBackEdges(ArenaBitVector* visited) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000030 ArenaBitVector visiting(arena_, blocks_.Size(), false);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000031 VisitBlockForBackEdges(entry_block_, visited, &visiting);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000032}
33
Roland Levillainfc600dc2014-12-02 17:16:31 +000034static void RemoveAsUser(HInstruction* instruction) {
35 for (size_t i = 0; i < instruction->InputCount(); i++) {
36 instruction->InputAt(i)->RemoveUser(instruction, i);
37 }
38
39 HEnvironment* environment = instruction->GetEnvironment();
40 if (environment != nullptr) {
41 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
42 HInstruction* vreg = environment->GetInstructionAt(i);
43 if (vreg != nullptr) {
44 vreg->RemoveEnvironmentUser(environment, i);
45 }
46 }
47 }
48}
49
50void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
51 for (size_t i = 0; i < blocks_.Size(); ++i) {
52 if (!visited.IsBitSet(i)) {
53 HBasicBlock* block = blocks_.Get(i);
54 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
55 RemoveAsUser(it.Current());
56 }
57 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
58 RemoveAsUser(it.Current());
59 }
60 }
61 }
62}
63
Jean Christophe Beyler53d9da82014-12-04 13:28:25 -080064void HGraph::RemoveBlock(HBasicBlock* block) const {
65 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
66 block->GetSuccessors().Get(j)->RemovePredecessor(block);
67 }
68 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
69 block->RemovePhi(it.Current()->AsPhi());
70 }
71 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
72 block->RemoveInstruction(it.Current());
73 }
74}
75
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000076void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010077 for (size_t i = 0; i < blocks_.Size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000078 if (!visited.IsBitSet(i)) {
Jean Christophe Beyler53d9da82014-12-04 13:28:25 -080079 RemoveBlock(blocks_.Get(i));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000080 }
81 }
82}
83
84void HGraph::VisitBlockForBackEdges(HBasicBlock* block,
85 ArenaBitVector* visited,
Nicolas Geoffray804d0932014-05-02 08:46:00 +010086 ArenaBitVector* visiting) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000087 int id = block->GetBlockId();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000088 if (visited->IsBitSet(id)) return;
89
90 visited->SetBit(id);
91 visiting->SetBit(id);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010092 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
93 HBasicBlock* successor = block->GetSuccessors().Get(i);
Nicolas Geoffray787c3072014-03-17 10:20:19 +000094 if (visiting->IsBitSet(successor->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000095 successor->AddBackEdge(block);
96 } else {
97 VisitBlockForBackEdges(successor, visited, visiting);
98 }
99 }
100 visiting->ClearBit(id);
101}
102
103void HGraph::BuildDominatorTree() {
104 ArenaBitVector visited(arena_, blocks_.Size(), false);
105
106 // (1) Find the back edges in the graph doing a DFS traversal.
107 FindBackEdges(&visited);
108
Roland Levillainfc600dc2014-12-02 17:16:31 +0000109 // (2) Remove instructions and phis from blocks not visited during
110 // the initial DFS as users from other instructions, so that
111 // users can be safely removed before uses later.
112 RemoveInstructionsAsUsersFromDeadBlocks(visited);
113
114 // (3) Remove blocks not visited during the initial DFS.
115 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000116 // predecessors list of live blocks.
117 RemoveDeadBlocks(visited);
118
Roland Levillainfc600dc2014-12-02 17:16:31 +0000119 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100120 // dominators and the reverse post order.
121 SimplifyCFG();
122
Roland Levillainfc600dc2014-12-02 17:16:31 +0000123 // (5) Compute the immediate dominator of each block. We visit
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000124 // the successors of a block only when all its forward branches
125 // have been processed.
126 GrowableArray<size_t> visits(arena_, blocks_.Size());
127 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100128 reverse_post_order_.Add(entry_block_);
129 for (size_t i = 0; i < entry_block_->GetSuccessors().Size(); i++) {
130 VisitBlockForDominatorTree(entry_block_->GetSuccessors().Get(i), entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000131 }
132}
133
134HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
135 ArenaBitVector visited(arena_, blocks_.Size(), false);
136 // Walk the dominator tree of the first block and mark the visited blocks.
137 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000138 visited.SetBit(first->GetBlockId());
139 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000140 }
141 // Walk the dominator tree of the second block until a marked block is found.
142 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000143 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000144 return second;
145 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000146 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000147 }
148 LOG(ERROR) << "Could not find common dominator";
149 return nullptr;
150}
151
152void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
153 HBasicBlock* predecessor,
154 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000155 if (block->GetDominator() == nullptr) {
156 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000157 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000158 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000159 }
160
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000161 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000162 // Once all the forward edges have been visited, we know the immediate
163 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000164 if (visits->Get(block->GetBlockId()) ==
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100165 block->GetPredecessors().Size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100166 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100167 reverse_post_order_.Add(block);
168 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
169 VisitBlockForDominatorTree(block->GetSuccessors().Get(i), block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000170 }
171 }
172}
173
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000174void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100175 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100176 SsaBuilder ssa_builder(this);
177 ssa_builder.BuildSsa();
178}
179
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100180void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
181 // Insert a new node between `block` and `successor` to split the
182 // critical edge.
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100183 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100184 AddBlock(new_block);
185 new_block->AddInstruction(new (arena_) HGoto());
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100186 block->ReplaceSuccessor(successor, new_block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100187 new_block->AddSuccessor(successor);
188 if (successor->IsLoopHeader()) {
189 // If we split at a back edge boundary, make the new block the back edge.
190 HLoopInformation* info = successor->GetLoopInformation();
191 if (info->IsBackEdge(block)) {
192 info->RemoveBackEdge(block);
193 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100194 }
195 }
196}
197
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100198void HGraph::SimplifyLoop(HBasicBlock* header) {
199 HLoopInformation* info = header->GetLoopInformation();
200
201 // If there are more than one back edge, make them branch to the same block that
202 // will become the only back edge. This simplifies finding natural loops in the
203 // graph.
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100204 // Also, if the loop is a do/while (that is the back edge is an if), change the
205 // back edge to be a goto. This simplifies code generation of suspend cheks.
206 if (info->NumberOfBackEdges() > 1 || info->GetBackEdges().Get(0)->GetLastInstruction()->IsIf()) {
207 HBasicBlock* new_back_edge = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100208 AddBlock(new_back_edge);
209 new_back_edge->AddInstruction(new (arena_) HGoto());
210 for (size_t pred = 0, e = info->GetBackEdges().Size(); pred < e; ++pred) {
211 HBasicBlock* back_edge = info->GetBackEdges().Get(pred);
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100212 back_edge->ReplaceSuccessor(header, new_back_edge);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100213 }
214 info->ClearBackEdges();
215 info->AddBackEdge(new_back_edge);
216 new_back_edge->AddSuccessor(header);
217 }
218
219 // Make sure the loop has only one pre header. This simplifies SSA building by having
220 // to just look at the pre header to know which locals are initialized at entry of the
221 // loop.
222 size_t number_of_incomings = header->GetPredecessors().Size() - info->NumberOfBackEdges();
223 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100224 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100225 AddBlock(pre_header);
226 pre_header->AddInstruction(new (arena_) HGoto());
227
228 ArenaBitVector back_edges(arena_, GetBlocks().Size(), false);
229 HBasicBlock* back_edge = info->GetBackEdges().Get(0);
230 for (size_t pred = 0; pred < header->GetPredecessors().Size(); ++pred) {
231 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
232 if (predecessor != back_edge) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100233 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100234 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100235 }
236 }
237 pre_header->AddSuccessor(header);
238 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100239
240 // Make sure the second predecessor of a loop header is the back edge.
241 if (header->GetPredecessors().Get(1) != info->GetBackEdges().Get(0)) {
242 header->SwapPredecessors();
243 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100244
245 // Place the suspend check at the beginning of the header, so that live registers
246 // will be known when allocating registers. Note that code generation can still
247 // generate the suspend check at the back edge, but needs to be careful with
248 // loop phi spill slots (which are not written to at back edge).
249 HInstruction* first_instruction = header->GetFirstInstruction();
250 if (!first_instruction->IsSuspendCheck()) {
251 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
252 header->InsertInstructionBefore(check, first_instruction);
253 first_instruction = check;
254 }
255 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100256}
257
258void HGraph::SimplifyCFG() {
259 // Simplify the CFG for future analysis, and code generation:
260 // (1): Split critical edges.
261 // (2): Simplify loops by having only one back edge, and one preheader.
262 for (size_t i = 0; i < blocks_.Size(); ++i) {
263 HBasicBlock* block = blocks_.Get(i);
264 if (block->GetSuccessors().Size() > 1) {
265 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
266 HBasicBlock* successor = block->GetSuccessors().Get(j);
267 if (successor->GetPredecessors().Size() > 1) {
268 SplitCriticalEdge(block, successor);
269 --j;
270 }
271 }
272 }
273 if (block->IsLoopHeader()) {
274 SimplifyLoop(block);
275 }
276 }
277}
278
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000279bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100280 for (size_t i = 0; i < blocks_.Size(); ++i) {
281 HBasicBlock* block = blocks_.Get(i);
282 if (block->IsLoopHeader()) {
283 HLoopInformation* info = block->GetLoopInformation();
284 if (!info->Populate()) {
285 // Abort if the loop is non natural. We currently bailout in such cases.
286 return false;
287 }
288 }
289 }
290 return true;
291}
292
293void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
294 if (blocks_.IsBitSet(block->GetBlockId())) {
295 return;
296 }
297
298 blocks_.SetBit(block->GetBlockId());
299 block->SetInLoop(this);
300 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
301 PopulateRecursive(block->GetPredecessors().Get(i));
302 }
303}
304
305bool HLoopInformation::Populate() {
306 DCHECK_EQ(GetBackEdges().Size(), 1u);
307 HBasicBlock* back_edge = GetBackEdges().Get(0);
308 DCHECK(back_edge->GetDominator() != nullptr);
309 if (!header_->Dominates(back_edge)) {
310 // This loop is not natural. Do not bother going further.
311 return false;
312 }
313
314 // Populate this loop: starting with the back edge, recursively add predecessors
315 // that are not already part of that loop. Set the header as part of the loop
316 // to end the recursion.
317 // This is a recursive implementation of the algorithm described in
318 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
319 blocks_.SetBit(header_->GetBlockId());
320 PopulateRecursive(back_edge);
321 return true;
322}
323
324HBasicBlock* HLoopInformation::GetPreHeader() const {
325 DCHECK_EQ(header_->GetPredecessors().Size(), 2u);
326 return header_->GetDominator();
327}
328
329bool HLoopInformation::Contains(const HBasicBlock& block) const {
330 return blocks_.IsBitSet(block.GetBlockId());
331}
332
333bool HLoopInformation::IsIn(const HLoopInformation& other) const {
334 return other.blocks_.IsBitSet(header_->GetBlockId());
335}
336
337bool HBasicBlock::Dominates(HBasicBlock* other) const {
338 // Walk up the dominator tree from `other`, to find out if `this`
339 // is an ancestor.
340 HBasicBlock* current = other;
341 while (current != nullptr) {
342 if (current == this) {
343 return true;
344 }
345 current = current->GetDominator();
346 }
347 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100348}
349
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100350static void UpdateInputsUsers(HInstruction* instruction) {
351 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
352 instruction->InputAt(i)->AddUseAt(instruction, i);
353 }
354 // Environment should be created later.
355 DCHECK(!instruction->HasEnvironment());
356}
357
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100358void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
Roland Levillain476df552014-10-09 17:51:36 +0100359 DCHECK(!cursor->IsPhi());
360 DCHECK(!instruction->IsPhi());
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100361 DCHECK_EQ(instruction->GetId(), -1);
362 DCHECK_NE(cursor->GetId(), -1);
363 DCHECK_EQ(cursor->GetBlock(), this);
364 DCHECK(!instruction->IsControlFlow());
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100365 instruction->next_ = cursor;
366 instruction->previous_ = cursor->previous_;
367 cursor->previous_ = instruction;
368 if (GetFirstInstruction() == cursor) {
369 instructions_.first_instruction_ = instruction;
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100370 } else {
371 instruction->previous_->next_ = instruction;
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100372 }
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100373 instruction->SetBlock(this);
374 instruction->SetId(GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100375 UpdateInputsUsers(instruction);
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100376}
377
Roland Levillainccc07a92014-09-16 14:48:16 +0100378void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
379 HInstruction* replacement) {
380 DCHECK(initial->GetBlock() == this);
381 InsertInstructionBefore(replacement, initial);
382 initial->ReplaceWith(replacement);
383 RemoveInstruction(initial);
384}
385
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100386static void Add(HInstructionList* instruction_list,
387 HBasicBlock* block,
388 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000389 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000390 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100391 instruction->SetBlock(block);
392 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100393 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100394 instruction_list->AddInstruction(instruction);
395}
396
397void HBasicBlock::AddInstruction(HInstruction* instruction) {
398 Add(&instructions_, this, instruction);
399}
400
401void HBasicBlock::AddPhi(HPhi* phi) {
402 Add(&phis_, this, phi);
403}
404
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100405void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
406 DCHECK_EQ(phi->GetId(), -1);
407 DCHECK_NE(cursor->GetId(), -1);
408 DCHECK_EQ(cursor->GetBlock(), this);
409 if (cursor->next_ == nullptr) {
410 cursor->next_ = phi;
411 phi->previous_ = cursor;
412 DCHECK(phi->next_ == nullptr);
413 } else {
414 phi->next_ = cursor->next_;
415 phi->previous_ = cursor;
416 cursor->next_ = phi;
417 phi->next_->previous_ = phi;
418 }
419 phi->SetBlock(this);
420 phi->SetId(GetGraph()->GetNextInstructionId());
421 UpdateInputsUsers(phi);
422}
423
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100424static void Remove(HInstructionList* instruction_list,
425 HBasicBlock* block,
426 HInstruction* instruction) {
427 DCHECK_EQ(block, instruction->GetBlock());
428 DCHECK(instruction->GetUses() == nullptr);
429 DCHECK(instruction->GetEnvUses() == nullptr);
430 instruction->SetBlock(nullptr);
431 instruction_list->RemoveInstruction(instruction);
432
Roland Levillainfc600dc2014-12-02 17:16:31 +0000433 RemoveAsUser(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100434}
435
436void HBasicBlock::RemoveInstruction(HInstruction* instruction) {
437 Remove(&instructions_, this, instruction);
438}
439
440void HBasicBlock::RemovePhi(HPhi* phi) {
441 Remove(&phis_, this, phi);
442}
443
Nicolas Geoffray724c9632014-09-22 12:27:27 +0100444template <typename T>
445static void RemoveFromUseList(T* user,
446 size_t input_index,
447 HUseListNode<T>** list) {
448 HUseListNode<T>* previous = nullptr;
449 HUseListNode<T>* current = *list;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100450 while (current != nullptr) {
451 if (current->GetUser() == user && current->GetIndex() == input_index) {
Jean Christophe Beyler0ada95d2014-12-04 11:20:20 -0800452 if (previous == nullptr) {
Nicolas Geoffray724c9632014-09-22 12:27:27 +0100453 *list = current->GetTail();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100454 } else {
455 previous->SetTail(current->GetTail());
456 }
457 }
458 previous = current;
459 current = current->GetTail();
460 }
461}
462
Calin Juravle77520bc2015-01-12 18:45:46 +0000463HInstruction* HInstruction::GetNextDisregardingMoves() const {
464 HInstruction* next = GetNext();
465 while (next != nullptr && next->IsParallelMove()) {
466 next = next->GetNext();
467 }
468 return next;
469}
470
471HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
472 HInstruction* previous = GetPrevious();
473 while (previous != nullptr && previous->IsParallelMove()) {
474 previous = previous->GetPrevious();
475 }
476 return previous;
477}
478
Nicolas Geoffray724c9632014-09-22 12:27:27 +0100479void HInstruction::RemoveUser(HInstruction* user, size_t input_index) {
480 RemoveFromUseList(user, input_index, &uses_);
481}
482
483void HInstruction::RemoveEnvironmentUser(HEnvironment* user, size_t input_index) {
484 RemoveFromUseList(user, input_index, &env_uses_);
485}
486
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100487void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000488 if (first_instruction_ == nullptr) {
489 DCHECK(last_instruction_ == nullptr);
490 first_instruction_ = last_instruction_ = instruction;
491 } else {
492 last_instruction_->next_ = instruction;
493 instruction->previous_ = last_instruction_;
494 last_instruction_ = instruction;
495 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000496}
497
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100498void HInstructionList::RemoveInstruction(HInstruction* instruction) {
499 if (instruction->previous_ != nullptr) {
500 instruction->previous_->next_ = instruction->next_;
501 }
502 if (instruction->next_ != nullptr) {
503 instruction->next_->previous_ = instruction->previous_;
504 }
505 if (instruction == first_instruction_) {
506 first_instruction_ = instruction->next_;
507 }
508 if (instruction == last_instruction_) {
509 last_instruction_ = instruction->previous_;
510 }
511}
512
Roland Levillain6b469232014-09-25 10:10:38 +0100513bool HInstructionList::Contains(HInstruction* instruction) const {
514 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
515 if (it.Current() == instruction) {
516 return true;
517 }
518 }
519 return false;
520}
521
Roland Levillainccc07a92014-09-16 14:48:16 +0100522bool HInstructionList::FoundBefore(const HInstruction* instruction1,
523 const HInstruction* instruction2) const {
524 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
525 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
526 if (it.Current() == instruction1) {
527 return true;
528 }
529 if (it.Current() == instruction2) {
530 return false;
531 }
532 }
533 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
534 return true;
535}
536
Roland Levillain6c82d402014-10-13 16:10:27 +0100537bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
538 if (other_instruction == this) {
539 // An instruction does not strictly dominate itself.
540 return false;
541 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100542 HBasicBlock* block = GetBlock();
543 HBasicBlock* other_block = other_instruction->GetBlock();
544 if (block != other_block) {
545 return GetBlock()->Dominates(other_instruction->GetBlock());
546 } else {
547 // If both instructions are in the same block, ensure this
548 // instruction comes before `other_instruction`.
549 if (IsPhi()) {
550 if (!other_instruction->IsPhi()) {
551 // Phis appear before non phi-instructions so this instruction
552 // dominates `other_instruction`.
553 return true;
554 } else {
555 // There is no order among phis.
556 LOG(FATAL) << "There is no dominance between phis of a same block.";
557 return false;
558 }
559 } else {
560 // `this` is not a phi.
561 if (other_instruction->IsPhi()) {
562 // Phis appear before non phi-instructions so this instruction
563 // does not dominate `other_instruction`.
564 return false;
565 } else {
566 // Check whether this instruction comes before
567 // `other_instruction` in the instruction list.
568 return block->GetInstructions().FoundBefore(this, other_instruction);
569 }
570 }
571 }
572}
573
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100574void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100575 DCHECK(other != nullptr);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100576 for (HUseIterator<HInstruction> it(GetUses()); !it.Done(); it.Advance()) {
577 HUseListNode<HInstruction>* current = it.Current();
578 HInstruction* user = current->GetUser();
579 size_t input_index = current->GetIndex();
580 user->SetRawInputAt(input_index, other);
581 other->AddUseAt(user, input_index);
582 }
583
584 for (HUseIterator<HEnvironment> it(GetEnvUses()); !it.Done(); it.Advance()) {
585 HUseListNode<HEnvironment>* current = it.Current();
586 HEnvironment* user = current->GetUser();
587 size_t input_index = current->GetIndex();
588 user->SetRawEnvAt(input_index, other);
589 other->AddEnvUseAt(user, input_index);
590 }
591
592 uses_ = nullptr;
593 env_uses_ = nullptr;
594}
595
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100596void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
597 InputAt(index)->RemoveUser(this, index);
598 SetRawInputAt(index, replacement);
599 replacement->AddUseAt(this, index);
600}
601
Nicolas Geoffray39468442014-09-02 15:17:15 +0100602size_t HInstruction::EnvironmentSize() const {
603 return HasEnvironment() ? environment_->Size() : 0;
604}
605
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100606void HPhi::AddInput(HInstruction* input) {
607 DCHECK(input->GetBlock() != nullptr);
608 inputs_.Add(input);
609 input->AddUseAt(this, inputs_.Size() - 1);
610}
611
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100612#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000613void H##name::Accept(HGraphVisitor* visitor) { \
614 visitor->Visit##name(this); \
615}
616
617FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
618
619#undef DEFINE_ACCEPT
620
621void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100622 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
623 for (size_t i = 0 ; i < blocks.Size(); i++) {
624 VisitBasicBlock(blocks.Get(i));
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000625 }
626}
627
Roland Levillain633021e2014-10-01 14:12:25 +0100628void HGraphVisitor::VisitReversePostOrder() {
629 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
630 VisitBasicBlock(it.Current());
631 }
632}
633
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000634void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100635 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100636 it.Current()->Accept(this);
637 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100638 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000639 it.Current()->Accept(this);
640 }
641}
642
Roland Levillain9240d6a2014-10-20 16:47:04 +0100643HConstant* HUnaryOperation::TryStaticEvaluation() const {
644 if (GetInput()->IsIntConstant()) {
645 int32_t value = Evaluate(GetInput()->AsIntConstant()->GetValue());
646 return new(GetBlock()->GetGraph()->GetArena()) HIntConstant(value);
647 } else if (GetInput()->IsLongConstant()) {
Roland Levillainb762d2e2014-10-22 10:11:06 +0100648 // TODO: Implement static evaluation of long unary operations.
649 //
650 // Do not exit with a fatal condition here. Instead, simply
651 // return `nullptr' to notify the caller that this instruction
652 // cannot (yet) be statically evaluated.
Roland Levillain9240d6a2014-10-20 16:47:04 +0100653 return nullptr;
654 }
655 return nullptr;
656}
657
658HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain556c3d12014-09-18 15:25:07 +0100659 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
660 int32_t value = Evaluate(GetLeft()->AsIntConstant()->GetValue(),
661 GetRight()->AsIntConstant()->GetValue());
Roland Levillain9240d6a2014-10-20 16:47:04 +0100662 return new(GetBlock()->GetGraph()->GetArena()) HIntConstant(value);
Roland Levillain556c3d12014-09-18 15:25:07 +0100663 } else if (GetLeft()->IsLongConstant() && GetRight()->IsLongConstant()) {
664 int64_t value = Evaluate(GetLeft()->AsLongConstant()->GetValue(),
665 GetRight()->AsLongConstant()->GetValue());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000666 if (GetResultType() == Primitive::kPrimLong) {
667 return new(GetBlock()->GetGraph()->GetArena()) HLongConstant(value);
668 } else {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000669 DCHECK_EQ(GetResultType(), Primitive::kPrimInt);
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000670 return new(GetBlock()->GetGraph()->GetArena()) HIntConstant(value);
671 }
Roland Levillain556c3d12014-09-18 15:25:07 +0100672 }
673 return nullptr;
674}
Dave Allison20dfc792014-06-16 20:44:29 -0700675
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100676bool HCondition::IsBeforeWhenDisregardMoves(HIf* if_) const {
Calin Juravle77520bc2015-01-12 18:45:46 +0000677 return this == if_->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100678}
679
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100680bool HInstruction::Equals(HInstruction* other) const {
681 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100682 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100683 if (!InstructionDataEquals(other)) return false;
684 if (GetType() != other->GetType()) return false;
685 if (InputCount() != other->InputCount()) return false;
686
687 for (size_t i = 0, e = InputCount(); i < e; ++i) {
688 if (InputAt(i) != other->InputAt(i)) return false;
689 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100690 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100691 return true;
692}
693
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700694std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
695#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
696 switch (rhs) {
697 FOR_EACH_INSTRUCTION(DECLARE_CASE)
698 default:
699 os << "Unknown instruction kind " << static_cast<int>(rhs);
700 break;
701 }
702#undef DECLARE_CASE
703 return os;
704}
705
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000706void HInstruction::InsertBefore(HInstruction* cursor) {
707 next_->previous_ = previous_;
708 if (previous_ != nullptr) {
709 previous_->next_ = next_;
710 }
711 if (block_->instructions_.first_instruction_ == this) {
712 block_->instructions_.first_instruction_ = next_;
713 }
714
715 previous_ = cursor->previous_;
716 if (previous_ != nullptr) {
717 previous_->next_ = this;
718 }
719 next_ = cursor;
720 cursor->previous_ = this;
721 block_ = cursor->block_;
722}
723
724void HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
725 // We currently only support graphs with one entry block, one body block, and one exit block.
726 DCHECK_EQ(GetBlocks().Size(), 3u);
727
728 // Walk over the entry block and:
729 // - Move constants from the entry block to the outer_graph's entry block,
730 // - Replace HParameterValue instructions with their real value.
731 // - Remove suspend checks, that hold an environment.
732 int parameter_index = 0;
733 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
734 HInstruction* current = it.Current();
735 if (current->IsConstant()) {
736 current->InsertBefore(outer_graph->GetEntryBlock()->GetLastInstruction());
737 } else if (current->IsParameterValue()) {
738 current->ReplaceWith(invoke->InputAt(parameter_index++));
739 } else {
740 DCHECK(current->IsGoto() || current->IsSuspendCheck());
741 entry_block_->RemoveInstruction(current);
742 }
743 }
744
745 // Insert the body's instructions except the last, just after the `invoke`
746 // instruction.
747 HBasicBlock* body = GetBlocks().Get(1);
748 DCHECK(!body->IsExitBlock());
749 HInstruction* last = body->GetLastInstruction();
750 HInstruction* first = body->GetFirstInstruction();
751
752 if (first != last) {
753 HInstruction* antelast = last->GetPrevious();
754
755 // Update the instruction list of the body to only contain the last
756 // instruction.
757 last->previous_ = nullptr;
758 body->instructions_.first_instruction_ = last;
759 body->instructions_.last_instruction_ = last;
760
761 // Update the instruction list of the `invoke`'s block to now contain the
762 // body's instructions.
763 antelast->next_ = invoke->GetNext();
764 antelast->next_->previous_ = antelast;
765 first->previous_ = invoke;
766 invoke->next_ = first;
767
768 // Update the block pointer of all instructions.
769 for (HInstruction* current = antelast; current != invoke; current = current->GetPrevious()) {
770 current->SetBlock(invoke->GetBlock());
771 }
772 }
773
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +0000774 // Replace the invoke with the return value of the inlined graph.
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000775 if (last->IsReturn()) {
776 invoke->ReplaceWith(last->InputAt(0));
777 body->RemoveInstruction(last);
778 } else {
779 DCHECK(last->IsReturnVoid());
780 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +0000781
782 // Finally remove the invoke from the caller.
783 invoke->GetBlock()->RemoveInstruction(invoke);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000784}
785
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000786} // namespace art