blob: 39ec22bea1c937722c9ac213478eab4d1fcec149 [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
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000064void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010065 for (size_t i = 0; i < blocks_.Size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000066 if (!visited.IsBitSet(i)) {
67 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010068 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +010069 block->GetSuccessors().Get(j)->RemovePredecessor(block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010070 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010071 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010072 block->RemovePhi(it.Current()->AsPhi());
73 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +010074 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010075 block->RemoveInstruction(it.Current());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000076 }
77 }
78 }
79}
80
81void HGraph::VisitBlockForBackEdges(HBasicBlock* block,
82 ArenaBitVector* visited,
Nicolas Geoffray804d0932014-05-02 08:46:00 +010083 ArenaBitVector* visiting) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000084 int id = block->GetBlockId();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000085 if (visited->IsBitSet(id)) return;
86
87 visited->SetBit(id);
88 visiting->SetBit(id);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010089 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
90 HBasicBlock* successor = block->GetSuccessors().Get(i);
Nicolas Geoffray787c3072014-03-17 10:20:19 +000091 if (visiting->IsBitSet(successor->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000092 successor->AddBackEdge(block);
93 } else {
94 VisitBlockForBackEdges(successor, visited, visiting);
95 }
96 }
97 visiting->ClearBit(id);
98}
99
100void HGraph::BuildDominatorTree() {
101 ArenaBitVector visited(arena_, blocks_.Size(), false);
102
103 // (1) Find the back edges in the graph doing a DFS traversal.
104 FindBackEdges(&visited);
105
Roland Levillainfc600dc2014-12-02 17:16:31 +0000106 // (2) Remove instructions and phis from blocks not visited during
107 // the initial DFS as users from other instructions, so that
108 // users can be safely removed before uses later.
109 RemoveInstructionsAsUsersFromDeadBlocks(visited);
110
111 // (3) Remove blocks not visited during the initial DFS.
112 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000113 // predecessors list of live blocks.
114 RemoveDeadBlocks(visited);
115
Roland Levillainfc600dc2014-12-02 17:16:31 +0000116 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100117 // dominators and the reverse post order.
118 SimplifyCFG();
119
Roland Levillainfc600dc2014-12-02 17:16:31 +0000120 // (5) Compute the immediate dominator of each block. We visit
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000121 // the successors of a block only when all its forward branches
122 // have been processed.
123 GrowableArray<size_t> visits(arena_, blocks_.Size());
124 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100125 reverse_post_order_.Add(entry_block_);
126 for (size_t i = 0; i < entry_block_->GetSuccessors().Size(); i++) {
127 VisitBlockForDominatorTree(entry_block_->GetSuccessors().Get(i), entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000128 }
129}
130
131HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
132 ArenaBitVector visited(arena_, blocks_.Size(), false);
133 // Walk the dominator tree of the first block and mark the visited blocks.
134 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000135 visited.SetBit(first->GetBlockId());
136 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000137 }
138 // Walk the dominator tree of the second block until a marked block is found.
139 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000140 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000141 return second;
142 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000143 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000144 }
145 LOG(ERROR) << "Could not find common dominator";
146 return nullptr;
147}
148
149void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
150 HBasicBlock* predecessor,
151 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000152 if (block->GetDominator() == nullptr) {
153 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000154 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000155 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000156 }
157
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000158 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000159 // Once all the forward edges have been visited, we know the immediate
160 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000161 if (visits->Get(block->GetBlockId()) ==
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100162 block->GetPredecessors().Size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100163 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100164 reverse_post_order_.Add(block);
165 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
166 VisitBlockForDominatorTree(block->GetSuccessors().Get(i), block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000167 }
168 }
169}
170
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000171void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100172 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100173 SsaBuilder ssa_builder(this);
174 ssa_builder.BuildSsa();
175}
176
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100177void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
178 // Insert a new node between `block` and `successor` to split the
179 // critical edge.
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100180 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100181 AddBlock(new_block);
182 new_block->AddInstruction(new (arena_) HGoto());
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100183 block->ReplaceSuccessor(successor, new_block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100184 new_block->AddSuccessor(successor);
185 if (successor->IsLoopHeader()) {
186 // If we split at a back edge boundary, make the new block the back edge.
187 HLoopInformation* info = successor->GetLoopInformation();
188 if (info->IsBackEdge(block)) {
189 info->RemoveBackEdge(block);
190 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100191 }
192 }
193}
194
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100195void HGraph::SimplifyLoop(HBasicBlock* header) {
196 HLoopInformation* info = header->GetLoopInformation();
197
198 // If there are more than one back edge, make them branch to the same block that
199 // will become the only back edge. This simplifies finding natural loops in the
200 // graph.
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100201 // Also, if the loop is a do/while (that is the back edge is an if), change the
202 // back edge to be a goto. This simplifies code generation of suspend cheks.
203 if (info->NumberOfBackEdges() > 1 || info->GetBackEdges().Get(0)->GetLastInstruction()->IsIf()) {
204 HBasicBlock* new_back_edge = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100205 AddBlock(new_back_edge);
206 new_back_edge->AddInstruction(new (arena_) HGoto());
207 for (size_t pred = 0, e = info->GetBackEdges().Size(); pred < e; ++pred) {
208 HBasicBlock* back_edge = info->GetBackEdges().Get(pred);
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100209 back_edge->ReplaceSuccessor(header, new_back_edge);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100210 }
211 info->ClearBackEdges();
212 info->AddBackEdge(new_back_edge);
213 new_back_edge->AddSuccessor(header);
214 }
215
216 // Make sure the loop has only one pre header. This simplifies SSA building by having
217 // to just look at the pre header to know which locals are initialized at entry of the
218 // loop.
219 size_t number_of_incomings = header->GetPredecessors().Size() - info->NumberOfBackEdges();
220 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100221 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100222 AddBlock(pre_header);
223 pre_header->AddInstruction(new (arena_) HGoto());
224
225 ArenaBitVector back_edges(arena_, GetBlocks().Size(), false);
226 HBasicBlock* back_edge = info->GetBackEdges().Get(0);
227 for (size_t pred = 0; pred < header->GetPredecessors().Size(); ++pred) {
228 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
229 if (predecessor != back_edge) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100230 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100231 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100232 }
233 }
234 pre_header->AddSuccessor(header);
235 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100236
237 // Make sure the second predecessor of a loop header is the back edge.
238 if (header->GetPredecessors().Get(1) != info->GetBackEdges().Get(0)) {
239 header->SwapPredecessors();
240 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100241
242 // Place the suspend check at the beginning of the header, so that live registers
243 // will be known when allocating registers. Note that code generation can still
244 // generate the suspend check at the back edge, but needs to be careful with
245 // loop phi spill slots (which are not written to at back edge).
246 HInstruction* first_instruction = header->GetFirstInstruction();
247 if (!first_instruction->IsSuspendCheck()) {
248 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
249 header->InsertInstructionBefore(check, first_instruction);
250 first_instruction = check;
251 }
252 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100253}
254
255void HGraph::SimplifyCFG() {
256 // Simplify the CFG for future analysis, and code generation:
257 // (1): Split critical edges.
258 // (2): Simplify loops by having only one back edge, and one preheader.
259 for (size_t i = 0; i < blocks_.Size(); ++i) {
260 HBasicBlock* block = blocks_.Get(i);
261 if (block->GetSuccessors().Size() > 1) {
262 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
263 HBasicBlock* successor = block->GetSuccessors().Get(j);
264 if (successor->GetPredecessors().Size() > 1) {
265 SplitCriticalEdge(block, successor);
266 --j;
267 }
268 }
269 }
270 if (block->IsLoopHeader()) {
271 SimplifyLoop(block);
272 }
273 }
274}
275
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000276bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100277 for (size_t i = 0; i < blocks_.Size(); ++i) {
278 HBasicBlock* block = blocks_.Get(i);
279 if (block->IsLoopHeader()) {
280 HLoopInformation* info = block->GetLoopInformation();
281 if (!info->Populate()) {
282 // Abort if the loop is non natural. We currently bailout in such cases.
283 return false;
284 }
285 }
286 }
287 return true;
288}
289
290void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
291 if (blocks_.IsBitSet(block->GetBlockId())) {
292 return;
293 }
294
295 blocks_.SetBit(block->GetBlockId());
296 block->SetInLoop(this);
297 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
298 PopulateRecursive(block->GetPredecessors().Get(i));
299 }
300}
301
302bool HLoopInformation::Populate() {
303 DCHECK_EQ(GetBackEdges().Size(), 1u);
304 HBasicBlock* back_edge = GetBackEdges().Get(0);
305 DCHECK(back_edge->GetDominator() != nullptr);
306 if (!header_->Dominates(back_edge)) {
307 // This loop is not natural. Do not bother going further.
308 return false;
309 }
310
311 // Populate this loop: starting with the back edge, recursively add predecessors
312 // that are not already part of that loop. Set the header as part of the loop
313 // to end the recursion.
314 // This is a recursive implementation of the algorithm described in
315 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
316 blocks_.SetBit(header_->GetBlockId());
317 PopulateRecursive(back_edge);
318 return true;
319}
320
321HBasicBlock* HLoopInformation::GetPreHeader() const {
322 DCHECK_EQ(header_->GetPredecessors().Size(), 2u);
323 return header_->GetDominator();
324}
325
326bool HLoopInformation::Contains(const HBasicBlock& block) const {
327 return blocks_.IsBitSet(block.GetBlockId());
328}
329
330bool HLoopInformation::IsIn(const HLoopInformation& other) const {
331 return other.blocks_.IsBitSet(header_->GetBlockId());
332}
333
334bool HBasicBlock::Dominates(HBasicBlock* other) const {
335 // Walk up the dominator tree from `other`, to find out if `this`
336 // is an ancestor.
337 HBasicBlock* current = other;
338 while (current != nullptr) {
339 if (current == this) {
340 return true;
341 }
342 current = current->GetDominator();
343 }
344 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100345}
346
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100347static void UpdateInputsUsers(HInstruction* instruction) {
348 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
349 instruction->InputAt(i)->AddUseAt(instruction, i);
350 }
351 // Environment should be created later.
352 DCHECK(!instruction->HasEnvironment());
353}
354
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100355void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
Roland Levillain476df552014-10-09 17:51:36 +0100356 DCHECK(!cursor->IsPhi());
357 DCHECK(!instruction->IsPhi());
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100358 DCHECK_EQ(instruction->GetId(), -1);
359 DCHECK_NE(cursor->GetId(), -1);
360 DCHECK_EQ(cursor->GetBlock(), this);
361 DCHECK(!instruction->IsControlFlow());
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100362 instruction->next_ = cursor;
363 instruction->previous_ = cursor->previous_;
364 cursor->previous_ = instruction;
365 if (GetFirstInstruction() == cursor) {
366 instructions_.first_instruction_ = instruction;
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100367 } else {
368 instruction->previous_->next_ = instruction;
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100369 }
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100370 instruction->SetBlock(this);
371 instruction->SetId(GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100372 UpdateInputsUsers(instruction);
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100373}
374
Roland Levillainccc07a92014-09-16 14:48:16 +0100375void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
376 HInstruction* replacement) {
377 DCHECK(initial->GetBlock() == this);
378 InsertInstructionBefore(replacement, initial);
379 initial->ReplaceWith(replacement);
380 RemoveInstruction(initial);
381}
382
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100383static void Add(HInstructionList* instruction_list,
384 HBasicBlock* block,
385 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000386 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000387 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100388 instruction->SetBlock(block);
389 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100390 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100391 instruction_list->AddInstruction(instruction);
392}
393
394void HBasicBlock::AddInstruction(HInstruction* instruction) {
395 Add(&instructions_, this, instruction);
396}
397
398void HBasicBlock::AddPhi(HPhi* phi) {
399 Add(&phis_, this, phi);
400}
401
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100402void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
403 DCHECK_EQ(phi->GetId(), -1);
404 DCHECK_NE(cursor->GetId(), -1);
405 DCHECK_EQ(cursor->GetBlock(), this);
406 if (cursor->next_ == nullptr) {
407 cursor->next_ = phi;
408 phi->previous_ = cursor;
409 DCHECK(phi->next_ == nullptr);
410 } else {
411 phi->next_ = cursor->next_;
412 phi->previous_ = cursor;
413 cursor->next_ = phi;
414 phi->next_->previous_ = phi;
415 }
416 phi->SetBlock(this);
417 phi->SetId(GetGraph()->GetNextInstructionId());
418 UpdateInputsUsers(phi);
419}
420
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100421static void Remove(HInstructionList* instruction_list,
422 HBasicBlock* block,
423 HInstruction* instruction) {
424 DCHECK_EQ(block, instruction->GetBlock());
425 DCHECK(instruction->GetUses() == nullptr);
426 DCHECK(instruction->GetEnvUses() == nullptr);
427 instruction->SetBlock(nullptr);
428 instruction_list->RemoveInstruction(instruction);
429
Roland Levillainfc600dc2014-12-02 17:16:31 +0000430 RemoveAsUser(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100431}
432
433void HBasicBlock::RemoveInstruction(HInstruction* instruction) {
434 Remove(&instructions_, this, instruction);
435}
436
437void HBasicBlock::RemovePhi(HPhi* phi) {
438 Remove(&phis_, this, phi);
439}
440
Nicolas Geoffray724c9632014-09-22 12:27:27 +0100441template <typename T>
442static void RemoveFromUseList(T* user,
443 size_t input_index,
444 HUseListNode<T>** list) {
445 HUseListNode<T>* previous = nullptr;
446 HUseListNode<T>* current = *list;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100447 while (current != nullptr) {
448 if (current->GetUser() == user && current->GetIndex() == input_index) {
449 if (previous == NULL) {
Nicolas Geoffray724c9632014-09-22 12:27:27 +0100450 *list = current->GetTail();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100451 } else {
452 previous->SetTail(current->GetTail());
453 }
454 }
455 previous = current;
456 current = current->GetTail();
457 }
458}
459
Calin Juravle77520bc2015-01-12 18:45:46 +0000460HInstruction* HInstruction::GetNextDisregardingMoves() const {
461 HInstruction* next = GetNext();
462 while (next != nullptr && next->IsParallelMove()) {
463 next = next->GetNext();
464 }
465 return next;
466}
467
468HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
469 HInstruction* previous = GetPrevious();
470 while (previous != nullptr && previous->IsParallelMove()) {
471 previous = previous->GetPrevious();
472 }
473 return previous;
474}
475
Nicolas Geoffray724c9632014-09-22 12:27:27 +0100476void HInstruction::RemoveUser(HInstruction* user, size_t input_index) {
477 RemoveFromUseList(user, input_index, &uses_);
478}
479
480void HInstruction::RemoveEnvironmentUser(HEnvironment* user, size_t input_index) {
481 RemoveFromUseList(user, input_index, &env_uses_);
482}
483
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100484void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000485 if (first_instruction_ == nullptr) {
486 DCHECK(last_instruction_ == nullptr);
487 first_instruction_ = last_instruction_ = instruction;
488 } else {
489 last_instruction_->next_ = instruction;
490 instruction->previous_ = last_instruction_;
491 last_instruction_ = instruction;
492 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000493}
494
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100495void HInstructionList::RemoveInstruction(HInstruction* instruction) {
496 if (instruction->previous_ != nullptr) {
497 instruction->previous_->next_ = instruction->next_;
498 }
499 if (instruction->next_ != nullptr) {
500 instruction->next_->previous_ = instruction->previous_;
501 }
502 if (instruction == first_instruction_) {
503 first_instruction_ = instruction->next_;
504 }
505 if (instruction == last_instruction_) {
506 last_instruction_ = instruction->previous_;
507 }
508}
509
Roland Levillain6b469232014-09-25 10:10:38 +0100510bool HInstructionList::Contains(HInstruction* instruction) const {
511 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
512 if (it.Current() == instruction) {
513 return true;
514 }
515 }
516 return false;
517}
518
Roland Levillainccc07a92014-09-16 14:48:16 +0100519bool HInstructionList::FoundBefore(const HInstruction* instruction1,
520 const HInstruction* instruction2) const {
521 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
522 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
523 if (it.Current() == instruction1) {
524 return true;
525 }
526 if (it.Current() == instruction2) {
527 return false;
528 }
529 }
530 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
531 return true;
532}
533
Roland Levillain6c82d402014-10-13 16:10:27 +0100534bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
535 if (other_instruction == this) {
536 // An instruction does not strictly dominate itself.
537 return false;
538 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100539 HBasicBlock* block = GetBlock();
540 HBasicBlock* other_block = other_instruction->GetBlock();
541 if (block != other_block) {
542 return GetBlock()->Dominates(other_instruction->GetBlock());
543 } else {
544 // If both instructions are in the same block, ensure this
545 // instruction comes before `other_instruction`.
546 if (IsPhi()) {
547 if (!other_instruction->IsPhi()) {
548 // Phis appear before non phi-instructions so this instruction
549 // dominates `other_instruction`.
550 return true;
551 } else {
552 // There is no order among phis.
553 LOG(FATAL) << "There is no dominance between phis of a same block.";
554 return false;
555 }
556 } else {
557 // `this` is not a phi.
558 if (other_instruction->IsPhi()) {
559 // Phis appear before non phi-instructions so this instruction
560 // does not dominate `other_instruction`.
561 return false;
562 } else {
563 // Check whether this instruction comes before
564 // `other_instruction` in the instruction list.
565 return block->GetInstructions().FoundBefore(this, other_instruction);
566 }
567 }
568 }
569}
570
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100571void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100572 DCHECK(other != nullptr);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100573 for (HUseIterator<HInstruction> it(GetUses()); !it.Done(); it.Advance()) {
574 HUseListNode<HInstruction>* current = it.Current();
575 HInstruction* user = current->GetUser();
576 size_t input_index = current->GetIndex();
577 user->SetRawInputAt(input_index, other);
578 other->AddUseAt(user, input_index);
579 }
580
581 for (HUseIterator<HEnvironment> it(GetEnvUses()); !it.Done(); it.Advance()) {
582 HUseListNode<HEnvironment>* current = it.Current();
583 HEnvironment* user = current->GetUser();
584 size_t input_index = current->GetIndex();
585 user->SetRawEnvAt(input_index, other);
586 other->AddEnvUseAt(user, input_index);
587 }
588
589 uses_ = nullptr;
590 env_uses_ = nullptr;
591}
592
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100593void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
594 InputAt(index)->RemoveUser(this, index);
595 SetRawInputAt(index, replacement);
596 replacement->AddUseAt(this, index);
597}
598
Nicolas Geoffray39468442014-09-02 15:17:15 +0100599size_t HInstruction::EnvironmentSize() const {
600 return HasEnvironment() ? environment_->Size() : 0;
601}
602
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100603void HPhi::AddInput(HInstruction* input) {
604 DCHECK(input->GetBlock() != nullptr);
605 inputs_.Add(input);
606 input->AddUseAt(this, inputs_.Size() - 1);
607}
608
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100609#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000610void H##name::Accept(HGraphVisitor* visitor) { \
611 visitor->Visit##name(this); \
612}
613
614FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
615
616#undef DEFINE_ACCEPT
617
618void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100619 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
620 for (size_t i = 0 ; i < blocks.Size(); i++) {
621 VisitBasicBlock(blocks.Get(i));
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000622 }
623}
624
Roland Levillain633021e2014-10-01 14:12:25 +0100625void HGraphVisitor::VisitReversePostOrder() {
626 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
627 VisitBasicBlock(it.Current());
628 }
629}
630
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000631void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100632 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100633 it.Current()->Accept(this);
634 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100635 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000636 it.Current()->Accept(this);
637 }
638}
639
Roland Levillain9240d6a2014-10-20 16:47:04 +0100640HConstant* HUnaryOperation::TryStaticEvaluation() const {
641 if (GetInput()->IsIntConstant()) {
642 int32_t value = Evaluate(GetInput()->AsIntConstant()->GetValue());
643 return new(GetBlock()->GetGraph()->GetArena()) HIntConstant(value);
644 } else if (GetInput()->IsLongConstant()) {
Roland Levillainb762d2e2014-10-22 10:11:06 +0100645 // TODO: Implement static evaluation of long unary operations.
646 //
647 // Do not exit with a fatal condition here. Instead, simply
648 // return `nullptr' to notify the caller that this instruction
649 // cannot (yet) be statically evaluated.
Roland Levillain9240d6a2014-10-20 16:47:04 +0100650 return nullptr;
651 }
652 return nullptr;
653}
654
655HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain556c3d12014-09-18 15:25:07 +0100656 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
657 int32_t value = Evaluate(GetLeft()->AsIntConstant()->GetValue(),
658 GetRight()->AsIntConstant()->GetValue());
Roland Levillain9240d6a2014-10-20 16:47:04 +0100659 return new(GetBlock()->GetGraph()->GetArena()) HIntConstant(value);
Roland Levillain556c3d12014-09-18 15:25:07 +0100660 } else if (GetLeft()->IsLongConstant() && GetRight()->IsLongConstant()) {
661 int64_t value = Evaluate(GetLeft()->AsLongConstant()->GetValue(),
662 GetRight()->AsLongConstant()->GetValue());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000663 if (GetResultType() == Primitive::kPrimLong) {
664 return new(GetBlock()->GetGraph()->GetArena()) HLongConstant(value);
665 } else {
Nicolas Geoffrayc399fdc2015-01-21 12:42:57 +0000666 DCHECK(GetResultType() == Primitive::kPrimInt);
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000667 return new(GetBlock()->GetGraph()->GetArena()) HIntConstant(value);
668 }
Roland Levillain556c3d12014-09-18 15:25:07 +0100669 }
670 return nullptr;
671}
Dave Allison20dfc792014-06-16 20:44:29 -0700672
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100673bool HCondition::IsBeforeWhenDisregardMoves(HIf* if_) const {
Calin Juravle77520bc2015-01-12 18:45:46 +0000674 return this == if_->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100675}
676
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100677bool HInstruction::Equals(HInstruction* other) const {
678 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100679 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100680 if (!InstructionDataEquals(other)) return false;
681 if (GetType() != other->GetType()) return false;
682 if (InputCount() != other->InputCount()) return false;
683
684 for (size_t i = 0, e = InputCount(); i < e; ++i) {
685 if (InputAt(i) != other->InputAt(i)) return false;
686 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100687 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100688 return true;
689}
690
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700691std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
692#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
693 switch (rhs) {
694 FOR_EACH_INSTRUCTION(DECLARE_CASE)
695 default:
696 os << "Unknown instruction kind " << static_cast<int>(rhs);
697 break;
698 }
699#undef DECLARE_CASE
700 return os;
701}
702
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000703void HInstruction::InsertBefore(HInstruction* cursor) {
704 next_->previous_ = previous_;
705 if (previous_ != nullptr) {
706 previous_->next_ = next_;
707 }
708 if (block_->instructions_.first_instruction_ == this) {
709 block_->instructions_.first_instruction_ = next_;
710 }
711
712 previous_ = cursor->previous_;
713 if (previous_ != nullptr) {
714 previous_->next_ = this;
715 }
716 next_ = cursor;
717 cursor->previous_ = this;
718 block_ = cursor->block_;
719}
720
721void HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
722 // We currently only support graphs with one entry block, one body block, and one exit block.
723 DCHECK_EQ(GetBlocks().Size(), 3u);
724
725 // Walk over the entry block and:
726 // - Move constants from the entry block to the outer_graph's entry block,
727 // - Replace HParameterValue instructions with their real value.
728 // - Remove suspend checks, that hold an environment.
729 int parameter_index = 0;
730 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
731 HInstruction* current = it.Current();
732 if (current->IsConstant()) {
733 current->InsertBefore(outer_graph->GetEntryBlock()->GetLastInstruction());
734 } else if (current->IsParameterValue()) {
735 current->ReplaceWith(invoke->InputAt(parameter_index++));
736 } else {
737 DCHECK(current->IsGoto() || current->IsSuspendCheck());
738 entry_block_->RemoveInstruction(current);
739 }
740 }
741
742 // Insert the body's instructions except the last, just after the `invoke`
743 // instruction.
744 HBasicBlock* body = GetBlocks().Get(1);
745 DCHECK(!body->IsExitBlock());
746 HInstruction* last = body->GetLastInstruction();
747 HInstruction* first = body->GetFirstInstruction();
748
749 if (first != last) {
750 HInstruction* antelast = last->GetPrevious();
751
752 // Update the instruction list of the body to only contain the last
753 // instruction.
754 last->previous_ = nullptr;
755 body->instructions_.first_instruction_ = last;
756 body->instructions_.last_instruction_ = last;
757
758 // Update the instruction list of the `invoke`'s block to now contain the
759 // body's instructions.
760 antelast->next_ = invoke->GetNext();
761 antelast->next_->previous_ = antelast;
762 first->previous_ = invoke;
763 invoke->next_ = first;
764
765 // Update the block pointer of all instructions.
766 for (HInstruction* current = antelast; current != invoke; current = current->GetPrevious()) {
767 current->SetBlock(invoke->GetBlock());
768 }
769 }
770
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +0000771 // Replace the invoke with the return value of the inlined graph.
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000772 if (last->IsReturn()) {
773 invoke->ReplaceWith(last->InputAt(0));
774 body->RemoveInstruction(last);
775 } else {
776 DCHECK(last->IsReturnVoid());
777 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +0000778
779 // Finally remove the invoke from the caller.
780 invoke->GetBlock()->RemoveInstruction(invoke);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000781}
782
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000783} // namespace art