blob: dca612e6b720ad7d9871ee236e79fed3974cc429 [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"
Calin Juravleacf735c2015-02-12 15:25:22 +000021#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000022
23namespace art {
24
25void HGraph::AddBlock(HBasicBlock* block) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000026 block->SetBlockId(blocks_.Size());
Nicolas Geoffray818f2102014-02-18 16:43:35 +000027 blocks_.Add(block);
28}
29
Nicolas Geoffray804d0932014-05-02 08:46:00 +010030void HGraph::FindBackEdges(ArenaBitVector* visited) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000031 ArenaBitVector visiting(arena_, blocks_.Size(), false);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000032 VisitBlockForBackEdges(entry_block_, visited, &visiting);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000033}
34
Roland Levillainfc600dc2014-12-02 17:16:31 +000035static void RemoveAsUser(HInstruction* instruction) {
36 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000037 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000038 }
39
40 HEnvironment* environment = instruction->GetEnvironment();
41 if (environment != nullptr) {
42 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000043 if (environment->GetInstructionAt(i) != nullptr) {
44 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000045 }
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)) {
David Brazdil1abb4192015-02-17 18:33:36 +000067 HBasicBlock* block = blocks_.Get(i);
68 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
69 block->GetSuccessors().Get(j)->RemovePredecessor(block);
70 }
71 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
72 block->RemovePhi(it.Current()->AsPhi(), /*ensure_safety=*/ false);
73 }
74 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
75 block->RemoveInstruction(it.Current(), /*ensure_safety=*/ false);
76 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000077 }
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();
David Brazdil46e2a392015-03-16 17:31:52 +0000188 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100189 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
David Brazdil8d5b8b22015-03-24 10:51:52 +0000290void HGraph::InsertConstant(HConstant* constant) {
291 // New constants are inserted before the final control-flow instruction
292 // of the graph, or at its end if called from the graph builder.
293 if (entry_block_->EndsWithControlFlowInstruction()) {
294 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000295 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000296 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000297 }
298}
299
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000300HNullConstant* HGraph::GetNullConstant() {
301 if (cached_null_constant_ == nullptr) {
302 cached_null_constant_ = new (arena_) HNullConstant();
David Brazdil8d5b8b22015-03-24 10:51:52 +0000303 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000304 }
305 return cached_null_constant_;
306}
307
David Brazdil8d5b8b22015-03-24 10:51:52 +0000308template <class InstructionType, typename ValueType>
309InstructionType* HGraph::CreateConstant(ValueType value,
310 ArenaSafeMap<ValueType, InstructionType*>* cache) {
311 // Try to find an existing constant of the given value.
312 InstructionType* constant = nullptr;
313 auto cached_constant = cache->find(value);
314 if (cached_constant != cache->end()) {
315 constant = cached_constant->second;
David Brazdil46e2a392015-03-16 17:31:52 +0000316 }
David Brazdil8d5b8b22015-03-24 10:51:52 +0000317
318 // If not found or previously deleted, create and cache a new instruction.
319 if (constant == nullptr || constant->GetBlock() == nullptr) {
320 constant = new (arena_) InstructionType(value);
321 cache->Overwrite(value, constant);
322 InsertConstant(constant);
323 }
324 return constant;
David Brazdil46e2a392015-03-16 17:31:52 +0000325}
326
David Brazdil8d5b8b22015-03-24 10:51:52 +0000327HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value) {
328 switch (type) {
329 case Primitive::Type::kPrimBoolean:
330 DCHECK(IsUint<1>(value));
331 FALLTHROUGH_INTENDED;
332 case Primitive::Type::kPrimByte:
333 case Primitive::Type::kPrimChar:
334 case Primitive::Type::kPrimShort:
335 case Primitive::Type::kPrimInt:
336 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
337 return GetIntConstant(static_cast<int32_t>(value));
338
339 case Primitive::Type::kPrimLong:
340 return GetLongConstant(value);
341
342 default:
343 LOG(FATAL) << "Unsupported constant type";
344 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000345 }
David Brazdil46e2a392015-03-16 17:31:52 +0000346}
347
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000348void HLoopInformation::Add(HBasicBlock* block) {
349 blocks_.SetBit(block->GetBlockId());
350}
351
David Brazdil46e2a392015-03-16 17:31:52 +0000352void HLoopInformation::Remove(HBasicBlock* block) {
353 blocks_.ClearBit(block->GetBlockId());
354}
355
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100356void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
357 if (blocks_.IsBitSet(block->GetBlockId())) {
358 return;
359 }
360
361 blocks_.SetBit(block->GetBlockId());
362 block->SetInLoop(this);
363 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
364 PopulateRecursive(block->GetPredecessors().Get(i));
365 }
366}
367
368bool HLoopInformation::Populate() {
369 DCHECK_EQ(GetBackEdges().Size(), 1u);
370 HBasicBlock* back_edge = GetBackEdges().Get(0);
371 DCHECK(back_edge->GetDominator() != nullptr);
372 if (!header_->Dominates(back_edge)) {
373 // This loop is not natural. Do not bother going further.
374 return false;
375 }
376
377 // Populate this loop: starting with the back edge, recursively add predecessors
378 // that are not already part of that loop. Set the header as part of the loop
379 // to end the recursion.
380 // This is a recursive implementation of the algorithm described in
381 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
382 blocks_.SetBit(header_->GetBlockId());
383 PopulateRecursive(back_edge);
384 return true;
385}
386
387HBasicBlock* HLoopInformation::GetPreHeader() const {
388 DCHECK_EQ(header_->GetPredecessors().Size(), 2u);
389 return header_->GetDominator();
390}
391
392bool HLoopInformation::Contains(const HBasicBlock& block) const {
393 return blocks_.IsBitSet(block.GetBlockId());
394}
395
396bool HLoopInformation::IsIn(const HLoopInformation& other) const {
397 return other.blocks_.IsBitSet(header_->GetBlockId());
398}
399
400bool HBasicBlock::Dominates(HBasicBlock* other) const {
401 // Walk up the dominator tree from `other`, to find out if `this`
402 // is an ancestor.
403 HBasicBlock* current = other;
404 while (current != nullptr) {
405 if (current == this) {
406 return true;
407 }
408 current = current->GetDominator();
409 }
410 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100411}
412
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100413static void UpdateInputsUsers(HInstruction* instruction) {
414 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
415 instruction->InputAt(i)->AddUseAt(instruction, i);
416 }
417 // Environment should be created later.
418 DCHECK(!instruction->HasEnvironment());
419}
420
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100421void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
Roland Levillain476df552014-10-09 17:51:36 +0100422 DCHECK(!cursor->IsPhi());
423 DCHECK(!instruction->IsPhi());
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100424 DCHECK_EQ(instruction->GetId(), -1);
425 DCHECK_NE(cursor->GetId(), -1);
426 DCHECK_EQ(cursor->GetBlock(), this);
427 DCHECK(!instruction->IsControlFlow());
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100428 instruction->next_ = cursor;
429 instruction->previous_ = cursor->previous_;
430 cursor->previous_ = instruction;
431 if (GetFirstInstruction() == cursor) {
432 instructions_.first_instruction_ = instruction;
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100433 } else {
434 instruction->previous_->next_ = instruction;
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100435 }
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100436 instruction->SetBlock(this);
437 instruction->SetId(GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100438 UpdateInputsUsers(instruction);
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100439}
440
Roland Levillainccc07a92014-09-16 14:48:16 +0100441void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
442 HInstruction* replacement) {
443 DCHECK(initial->GetBlock() == this);
444 InsertInstructionBefore(replacement, initial);
445 initial->ReplaceWith(replacement);
446 RemoveInstruction(initial);
447}
448
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100449static void Add(HInstructionList* instruction_list,
450 HBasicBlock* block,
451 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000452 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000453 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100454 instruction->SetBlock(block);
455 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100456 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100457 instruction_list->AddInstruction(instruction);
458}
459
460void HBasicBlock::AddInstruction(HInstruction* instruction) {
461 Add(&instructions_, this, instruction);
462}
463
464void HBasicBlock::AddPhi(HPhi* phi) {
465 Add(&phis_, this, phi);
466}
467
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100468void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
469 DCHECK_EQ(phi->GetId(), -1);
470 DCHECK_NE(cursor->GetId(), -1);
471 DCHECK_EQ(cursor->GetBlock(), this);
472 if (cursor->next_ == nullptr) {
473 cursor->next_ = phi;
474 phi->previous_ = cursor;
475 DCHECK(phi->next_ == nullptr);
476 } else {
477 phi->next_ = cursor->next_;
478 phi->previous_ = cursor;
479 cursor->next_ = phi;
480 phi->next_->previous_ = phi;
481 }
482 phi->SetBlock(this);
483 phi->SetId(GetGraph()->GetNextInstructionId());
484 UpdateInputsUsers(phi);
485}
486
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100487static void Remove(HInstructionList* instruction_list,
488 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000489 HInstruction* instruction,
490 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100491 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100492 instruction->SetBlock(nullptr);
493 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000494 if (ensure_safety) {
495 DCHECK(instruction->GetUses().IsEmpty());
496 DCHECK(instruction->GetEnvUses().IsEmpty());
497 RemoveAsUser(instruction);
498 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100499}
500
David Brazdil1abb4192015-02-17 18:33:36 +0000501void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
502 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100503}
504
David Brazdil1abb4192015-02-17 18:33:36 +0000505void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
506 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100507}
508
David Brazdiled596192015-01-23 10:39:45 +0000509void HEnvironment::CopyFrom(HEnvironment* env) {
510 for (size_t i = 0; i < env->Size(); i++) {
511 HInstruction* instruction = env->GetInstructionAt(i);
512 SetRawEnvAt(i, instruction);
513 if (instruction != nullptr) {
514 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100515 }
David Brazdiled596192015-01-23 10:39:45 +0000516 }
517}
518
David Brazdil1abb4192015-02-17 18:33:36 +0000519void HEnvironment::RemoveAsUserOfInput(size_t index) const {
520 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
521 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100522}
523
Calin Juravle77520bc2015-01-12 18:45:46 +0000524HInstruction* HInstruction::GetNextDisregardingMoves() const {
525 HInstruction* next = GetNext();
526 while (next != nullptr && next->IsParallelMove()) {
527 next = next->GetNext();
528 }
529 return next;
530}
531
532HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
533 HInstruction* previous = GetPrevious();
534 while (previous != nullptr && previous->IsParallelMove()) {
535 previous = previous->GetPrevious();
536 }
537 return previous;
538}
539
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100540void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000541 if (first_instruction_ == nullptr) {
542 DCHECK(last_instruction_ == nullptr);
543 first_instruction_ = last_instruction_ = instruction;
544 } else {
545 last_instruction_->next_ = instruction;
546 instruction->previous_ = last_instruction_;
547 last_instruction_ = instruction;
548 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000549}
550
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100551void HInstructionList::RemoveInstruction(HInstruction* instruction) {
552 if (instruction->previous_ != nullptr) {
553 instruction->previous_->next_ = instruction->next_;
554 }
555 if (instruction->next_ != nullptr) {
556 instruction->next_->previous_ = instruction->previous_;
557 }
558 if (instruction == first_instruction_) {
559 first_instruction_ = instruction->next_;
560 }
561 if (instruction == last_instruction_) {
562 last_instruction_ = instruction->previous_;
563 }
564}
565
Roland Levillain6b469232014-09-25 10:10:38 +0100566bool HInstructionList::Contains(HInstruction* instruction) const {
567 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
568 if (it.Current() == instruction) {
569 return true;
570 }
571 }
572 return false;
573}
574
Roland Levillainccc07a92014-09-16 14:48:16 +0100575bool HInstructionList::FoundBefore(const HInstruction* instruction1,
576 const HInstruction* instruction2) const {
577 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
578 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
579 if (it.Current() == instruction1) {
580 return true;
581 }
582 if (it.Current() == instruction2) {
583 return false;
584 }
585 }
586 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
587 return true;
588}
589
Roland Levillain6c82d402014-10-13 16:10:27 +0100590bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
591 if (other_instruction == this) {
592 // An instruction does not strictly dominate itself.
593 return false;
594 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100595 HBasicBlock* block = GetBlock();
596 HBasicBlock* other_block = other_instruction->GetBlock();
597 if (block != other_block) {
598 return GetBlock()->Dominates(other_instruction->GetBlock());
599 } else {
600 // If both instructions are in the same block, ensure this
601 // instruction comes before `other_instruction`.
602 if (IsPhi()) {
603 if (!other_instruction->IsPhi()) {
604 // Phis appear before non phi-instructions so this instruction
605 // dominates `other_instruction`.
606 return true;
607 } else {
608 // There is no order among phis.
609 LOG(FATAL) << "There is no dominance between phis of a same block.";
610 return false;
611 }
612 } else {
613 // `this` is not a phi.
614 if (other_instruction->IsPhi()) {
615 // Phis appear before non phi-instructions so this instruction
616 // does not dominate `other_instruction`.
617 return false;
618 } else {
619 // Check whether this instruction comes before
620 // `other_instruction` in the instruction list.
621 return block->GetInstructions().FoundBefore(this, other_instruction);
622 }
623 }
624 }
625}
626
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100627void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100628 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000629 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
630 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100631 HInstruction* user = current->GetUser();
632 size_t input_index = current->GetIndex();
633 user->SetRawInputAt(input_index, other);
634 other->AddUseAt(user, input_index);
635 }
636
David Brazdiled596192015-01-23 10:39:45 +0000637 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
638 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100639 HEnvironment* user = current->GetUser();
640 size_t input_index = current->GetIndex();
641 user->SetRawEnvAt(input_index, other);
642 other->AddEnvUseAt(user, input_index);
643 }
644
David Brazdiled596192015-01-23 10:39:45 +0000645 uses_.Clear();
646 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100647}
648
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100649void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000650 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100651 SetRawInputAt(index, replacement);
652 replacement->AddUseAt(this, index);
653}
654
Nicolas Geoffray39468442014-09-02 15:17:15 +0100655size_t HInstruction::EnvironmentSize() const {
656 return HasEnvironment() ? environment_->Size() : 0;
657}
658
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100659void HPhi::AddInput(HInstruction* input) {
660 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000661 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100662 input->AddUseAt(this, inputs_.Size() - 1);
663}
664
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100665#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000666void H##name::Accept(HGraphVisitor* visitor) { \
667 visitor->Visit##name(this); \
668}
669
670FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
671
672#undef DEFINE_ACCEPT
673
674void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100675 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
676 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000677 HBasicBlock* block = blocks.Get(i);
678 if (block != nullptr) {
679 VisitBasicBlock(block);
680 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000681 }
682}
683
Roland Levillain633021e2014-10-01 14:12:25 +0100684void HGraphVisitor::VisitReversePostOrder() {
685 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
686 VisitBasicBlock(it.Current());
687 }
688}
689
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000690void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100691 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100692 it.Current()->Accept(this);
693 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100694 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000695 it.Current()->Accept(this);
696 }
697}
698
Roland Levillain9240d6a2014-10-20 16:47:04 +0100699HConstant* HUnaryOperation::TryStaticEvaluation() const {
700 if (GetInput()->IsIntConstant()) {
701 int32_t value = Evaluate(GetInput()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000702 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain9240d6a2014-10-20 16:47:04 +0100703 } else if (GetInput()->IsLongConstant()) {
Roland Levillainb762d2e2014-10-22 10:11:06 +0100704 // TODO: Implement static evaluation of long unary operations.
705 //
706 // Do not exit with a fatal condition here. Instead, simply
707 // return `nullptr' to notify the caller that this instruction
708 // cannot (yet) be statically evaluated.
Roland Levillain9240d6a2014-10-20 16:47:04 +0100709 return nullptr;
710 }
711 return nullptr;
712}
713
714HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain556c3d12014-09-18 15:25:07 +0100715 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
716 int32_t value = Evaluate(GetLeft()->AsIntConstant()->GetValue(),
717 GetRight()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000718 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain556c3d12014-09-18 15:25:07 +0100719 } else if (GetLeft()->IsLongConstant() && GetRight()->IsLongConstant()) {
720 int64_t value = Evaluate(GetLeft()->AsLongConstant()->GetValue(),
721 GetRight()->AsLongConstant()->GetValue());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000722 if (GetResultType() == Primitive::kPrimLong) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000723 return GetBlock()->GetGraph()->GetLongConstant(value);
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000724 } else {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000725 DCHECK_EQ(GetResultType(), Primitive::kPrimInt);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000726 return GetBlock()->GetGraph()->GetIntConstant(static_cast<int32_t>(value));
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000727 }
Roland Levillain556c3d12014-09-18 15:25:07 +0100728 }
729 return nullptr;
730}
Dave Allison20dfc792014-06-16 20:44:29 -0700731
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000732HConstant* HBinaryOperation::GetConstantRight() const {
733 if (GetRight()->IsConstant()) {
734 return GetRight()->AsConstant();
735 } else if (IsCommutative() && GetLeft()->IsConstant()) {
736 return GetLeft()->AsConstant();
737 } else {
738 return nullptr;
739 }
740}
741
742// If `GetConstantRight()` returns one of the input, this returns the other
743// one. Otherwise it returns nullptr.
744HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
745 HInstruction* most_constant_right = GetConstantRight();
746 if (most_constant_right == nullptr) {
747 return nullptr;
748 } else if (most_constant_right == GetLeft()) {
749 return GetRight();
750 } else {
751 return GetLeft();
752 }
753}
754
Andreas Gampe0ba62732015-03-24 02:39:46 +0000755bool HCondition::IsBeforeWhenDisregardMoves(HIf* if_) const {
756 return this == if_->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100757}
758
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100759bool HInstruction::Equals(HInstruction* other) const {
760 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100761 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100762 if (!InstructionDataEquals(other)) return false;
763 if (GetType() != other->GetType()) return false;
764 if (InputCount() != other->InputCount()) return false;
765
766 for (size_t i = 0, e = InputCount(); i < e; ++i) {
767 if (InputAt(i) != other->InputAt(i)) return false;
768 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100769 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100770 return true;
771}
772
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700773std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
774#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
775 switch (rhs) {
776 FOR_EACH_INSTRUCTION(DECLARE_CASE)
777 default:
778 os << "Unknown instruction kind " << static_cast<int>(rhs);
779 break;
780 }
781#undef DECLARE_CASE
782 return os;
783}
784
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000785void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000786 next_->previous_ = previous_;
787 if (previous_ != nullptr) {
788 previous_->next_ = next_;
789 }
790 if (block_->instructions_.first_instruction_ == this) {
791 block_->instructions_.first_instruction_ = next_;
792 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000793 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000794
795 previous_ = cursor->previous_;
796 if (previous_ != nullptr) {
797 previous_->next_ = this;
798 }
799 next_ = cursor;
800 cursor->previous_ = this;
801 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000802
803 if (block_->instructions_.first_instruction_ == cursor) {
804 block_->instructions_.first_instruction_ = this;
805 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000806}
807
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000808HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
809 DCHECK(!cursor->IsControlFlow());
810 DCHECK_NE(instructions_.last_instruction_, cursor);
811 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000812
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000813 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
814 new_block->instructions_.first_instruction_ = cursor->GetNext();
815 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
816 cursor->next_->previous_ = nullptr;
817 cursor->next_ = nullptr;
818 instructions_.last_instruction_ = cursor;
819
820 new_block->instructions_.SetBlockOfInstructions(new_block);
821 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
822 HBasicBlock* successor = GetSuccessors().Get(i);
823 new_block->successors_.Add(successor);
824 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
825 }
826 successors_.Reset();
827
828 for (size_t i = 0, e = GetDominatedBlocks().Size(); i < e; ++i) {
829 HBasicBlock* dominated = GetDominatedBlocks().Get(i);
830 dominated->dominator_ = new_block;
831 new_block->dominated_blocks_.Add(dominated);
832 }
833 dominated_blocks_.Reset();
834 return new_block;
835}
836
David Brazdil46e2a392015-03-16 17:31:52 +0000837bool HBasicBlock::IsSingleGoto() const {
838 HLoopInformation* loop_info = GetLoopInformation();
839 // TODO: Remove the null check b/19084197.
840 return GetFirstInstruction() != nullptr
841 && GetPhis().IsEmpty()
842 && GetFirstInstruction() == GetLastInstruction()
843 && GetLastInstruction()->IsGoto()
844 // Back edges generate the suspend check.
845 && (loop_info == nullptr || !loop_info->IsBackEdge(*this));
846}
847
David Brazdil8d5b8b22015-03-24 10:51:52 +0000848bool HBasicBlock::EndsWithControlFlowInstruction() const {
849 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
850}
851
David Brazdilb2bd1c52015-03-25 11:17:37 +0000852bool HBasicBlock::EndsWithIf() const {
853 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
854}
855
856bool HBasicBlock::HasSinglePhi() const {
857 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
858}
859
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000860void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
861 for (HInstruction* current = first_instruction_;
862 current != nullptr;
863 current = current->GetNext()) {
864 current->SetBlock(block);
865 }
866}
867
868void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
869 DCHECK(Contains(cursor));
870 if (!instruction_list.IsEmpty()) {
871 if (cursor == last_instruction_) {
872 last_instruction_ = instruction_list.last_instruction_;
873 } else {
874 cursor->next_->previous_ = instruction_list.last_instruction_;
875 }
876 instruction_list.last_instruction_->next_ = cursor->next_;
877 cursor->next_ = instruction_list.first_instruction_;
878 instruction_list.first_instruction_->previous_ = cursor;
879 }
880}
881
882void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +0000883 if (IsEmpty()) {
884 first_instruction_ = instruction_list.first_instruction_;
885 last_instruction_ = instruction_list.last_instruction_;
886 } else {
887 AddAfter(last_instruction_, instruction_list);
888 }
889}
890
891void HBasicBlock::DisconnectFromAll() {
892 DCHECK(dominated_blocks_.IsEmpty()) << "Unimplemented scenario";
893
894 for (size_t i = 0, e = predecessors_.Size(); i < e; ++i) {
895 predecessors_.Get(i)->successors_.Delete(this);
896 }
897 for (size_t i = 0, e = successors_.Size(); i < e; ++i) {
898 successors_.Get(i)->predecessors_.Delete(this);
899 }
900 dominator_->dominated_blocks_.Delete(this);
901
902 predecessors_.Reset();
903 successors_.Reset();
904 dominator_ = nullptr;
905 graph_ = nullptr;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000906}
907
908void HBasicBlock::MergeWith(HBasicBlock* other) {
909 DCHECK(successors_.IsEmpty()) << "Unimplemented block merge scenario";
David Brazdil46e2a392015-03-16 17:31:52 +0000910 DCHECK(dominated_blocks_.IsEmpty()
911 || (dominated_blocks_.Size() == 1 && dominated_blocks_.Get(0) == other))
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000912 << "Unimplemented block merge scenario";
913 DCHECK(other->GetPhis().IsEmpty());
914
915 successors_.Reset();
916 dominated_blocks_.Reset();
917 instructions_.Add(other->GetInstructions());
918 other->GetInstructions().SetBlockOfInstructions(this);
919
920 while (!other->GetSuccessors().IsEmpty()) {
921 HBasicBlock* successor = other->GetSuccessors().Get(0);
922 successor->ReplacePredecessor(other, this);
923 }
924
925 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
926 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
927 dominated_blocks_.Add(dominated);
928 dominated->SetDominator(this);
929 }
930 other->dominated_blocks_.Reset();
931 other->dominator_ = nullptr;
932 other->graph_ = nullptr;
933}
934
935void HBasicBlock::ReplaceWith(HBasicBlock* other) {
936 while (!GetPredecessors().IsEmpty()) {
937 HBasicBlock* predecessor = GetPredecessors().Get(0);
938 predecessor->ReplaceSuccessor(this, other);
939 }
940 while (!GetSuccessors().IsEmpty()) {
941 HBasicBlock* successor = GetSuccessors().Get(0);
942 successor->ReplacePredecessor(this, other);
943 }
944 for (size_t i = 0; i < dominated_blocks_.Size(); ++i) {
945 other->AddDominatedBlock(dominated_blocks_.Get(i));
946 }
947 GetDominator()->ReplaceDominatedBlock(this, other);
948 other->SetDominator(GetDominator());
949 dominator_ = nullptr;
950 graph_ = nullptr;
951}
952
953// Create space in `blocks` for adding `number_of_new_blocks` entries
954// starting at location `at`. Blocks after `at` are moved accordingly.
955static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
956 size_t number_of_new_blocks,
957 size_t at) {
958 size_t old_size = blocks->Size();
959 size_t new_size = old_size + number_of_new_blocks;
960 blocks->SetSize(new_size);
961 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
962 blocks->Put(j, blocks->Get(i));
963 }
964}
965
966void HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000967 // Walk over the entry block and:
968 // - Move constants from the entry block to the outer_graph's entry block,
969 // - Replace HParameterValue instructions with their real value.
970 // - Remove suspend checks, that hold an environment.
971 int parameter_index = 0;
972 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
973 HInstruction* current = it.Current();
974 if (current->IsConstant()) {
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000975 current->MoveBefore(outer_graph->GetEntryBlock()->GetLastInstruction());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000976 } else if (current->IsParameterValue()) {
977 current->ReplaceWith(invoke->InputAt(parameter_index++));
978 } else {
979 DCHECK(current->IsGoto() || current->IsSuspendCheck());
980 entry_block_->RemoveInstruction(current);
981 }
982 }
983
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000984 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +0000985 // Simple case of an entry block, a body block, and an exit block.
986 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000987 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +0000988 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
989 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000990 DCHECK(!body->IsExitBlock());
991 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000992
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000993 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
994 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000995
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000996 // Replace the invoke with the return value of the inlined graph.
997 if (last->IsReturn()) {
998 invoke->ReplaceWith(last->InputAt(0));
999 } else {
1000 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001001 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001002
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001003 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001004 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001005 // Need to inline multiple blocks. We split `invoke`'s block
1006 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001007 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001008 // with the second half.
1009 ArenaAllocator* allocator = outer_graph->GetArena();
1010 HBasicBlock* at = invoke->GetBlock();
1011 HBasicBlock* to = at->SplitAfter(invoke);
1012
1013 HBasicBlock* first = entry_block_->GetSuccessors().Get(0);
1014 DCHECK(!first->IsInLoop());
1015 at->MergeWith(first);
1016 exit_block_->ReplaceWith(to);
1017
1018 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001019 // to not `HReturn` but `HGoto` instead.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001020 HInstruction* return_value = nullptr;
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001021 bool returns_void = to->GetPredecessors().Get(0)->GetLastInstruction()->IsReturnVoid();
1022 if (to->GetPredecessors().Size() == 1) {
1023 HBasicBlock* predecessor = to->GetPredecessors().Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001024 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001025 if (!returns_void) {
1026 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001027 }
1028 predecessor->AddInstruction(new (allocator) HGoto());
1029 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001030 } else {
1031 if (!returns_void) {
1032 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001033 return_value = new (allocator) HPhi(
1034 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001035 to->AddPhi(return_value->AsPhi());
1036 }
1037 for (size_t i = 0, e = to->GetPredecessors().Size(); i < e; ++i) {
1038 HBasicBlock* predecessor = to->GetPredecessors().Get(i);
1039 HInstruction* last = predecessor->GetLastInstruction();
1040 if (!returns_void) {
1041 return_value->AsPhi()->AddInput(last->InputAt(0));
1042 }
1043 predecessor->AddInstruction(new (allocator) HGoto());
1044 predecessor->RemoveInstruction(last);
1045 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001046 }
1047
1048 if (return_value != nullptr) {
1049 invoke->ReplaceWith(return_value);
1050 }
1051
1052 // Update the meta information surrounding blocks:
1053 // (1) the graph they are now in,
1054 // (2) the reverse post order of that graph,
1055 // (3) the potential loop information they are now in.
1056
1057 // We don't add the entry block, the exit block, and the first block, which
1058 // has been merged with `at`.
1059 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1060
1061 // We add the `to` block.
1062 static constexpr int kNumberOfNewBlocksInCaller = 1;
1063 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1064 + kNumberOfNewBlocksInCaller;
1065
1066 // Find the location of `at` in the outer graph's reverse post order. The new
1067 // blocks will be added after it.
1068 size_t index_of_at = 0;
1069 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1070 index_of_at++;
1071 }
1072 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1073
1074 // Do a reverse post order of the blocks in the callee and do (1), (2),
1075 // and (3) to the blocks that apply.
1076 HLoopInformation* info = at->GetLoopInformation();
1077 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1078 HBasicBlock* current = it.Current();
1079 if (current != exit_block_ && current != entry_block_ && current != first) {
1080 DCHECK(!current->IsInLoop());
1081 DCHECK(current->GetGraph() == this);
1082 current->SetGraph(outer_graph);
1083 outer_graph->AddBlock(current);
1084 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1085 if (info != nullptr) {
1086 info->Add(current);
1087 current->SetLoopInformation(info);
1088 }
1089 }
1090 }
1091
1092 // Do (1), (2), and (3) to `to`.
1093 to->SetGraph(outer_graph);
1094 outer_graph->AddBlock(to);
1095 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1096 if (info != nullptr) {
1097 info->Add(to);
1098 to->SetLoopInformation(info);
David Brazdil46e2a392015-03-16 17:31:52 +00001099 if (info->IsBackEdge(*at)) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001100 // Only `at` can become a back edge, as the inlined blocks
1101 // are predecessors of `at`.
1102 DCHECK_EQ(1u, info->NumberOfBackEdges());
1103 info->ClearBackEdges();
1104 info->AddBackEdge(to);
1105 }
1106 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001107 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001108
1109 // Finally remove the invoke from the caller.
1110 invoke->GetBlock()->RemoveInstruction(invoke);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001111}
1112
David Brazdil46e2a392015-03-16 17:31:52 +00001113void HGraph::MergeEmptyBranches(HBasicBlock* start_block, HBasicBlock* end_block) {
David Brazdilb2bd1c52015-03-25 11:17:37 +00001114 // Find the two branches of an If.
David Brazdil46e2a392015-03-16 17:31:52 +00001115 DCHECK_EQ(start_block->GetSuccessors().Size(), 2u);
David Brazdil46e2a392015-03-16 17:31:52 +00001116 HBasicBlock* left_branch = start_block->GetSuccessors().Get(0);
1117 HBasicBlock* right_branch = start_block->GetSuccessors().Get(1);
David Brazdilb2bd1c52015-03-25 11:17:37 +00001118
1119 // Make sure this is a diamond control-flow path.
David Brazdil46e2a392015-03-16 17:31:52 +00001120 DCHECK_EQ(left_branch->GetSuccessors().Get(0), end_block);
1121 DCHECK_EQ(right_branch->GetSuccessors().Get(0), end_block);
David Brazdilb2bd1c52015-03-25 11:17:37 +00001122 DCHECK_EQ(end_block->GetPredecessors().Size(), 2u);
David Brazdil46e2a392015-03-16 17:31:52 +00001123 DCHECK_EQ(start_block, end_block->GetDominator());
1124
1125 // Disconnect the branches and merge the two blocks. This will move
1126 // all instructions from 'end_block' to 'start_block'.
1127 DCHECK(left_branch->IsSingleGoto());
1128 DCHECK(right_branch->IsSingleGoto());
1129 left_branch->DisconnectFromAll();
1130 right_branch->DisconnectFromAll();
1131 start_block->RemoveInstruction(start_block->GetLastInstruction());
1132 start_block->MergeWith(end_block);
1133
1134 // Delete the now redundant blocks from the graph.
1135 blocks_.Put(left_branch->GetBlockId(), nullptr);
1136 blocks_.Put(right_branch->GetBlockId(), nullptr);
1137 blocks_.Put(end_block->GetBlockId(), nullptr);
1138
1139 // Update reverse post order.
1140 reverse_post_order_.Delete(left_branch);
1141 reverse_post_order_.Delete(right_branch);
1142 reverse_post_order_.Delete(end_block);
1143
David Brazdilb2bd1c52015-03-25 11:17:37 +00001144 // Update loops which contain the code.
1145 for (HLoopInformationOutwardIterator it(*start_block); !it.Done(); it.Advance()) {
1146 HLoopInformation* loop_info = it.Current();
1147 DCHECK(loop_info->Contains(*left_branch));
1148 DCHECK(loop_info->Contains(*right_branch));
1149 DCHECK(loop_info->Contains(*end_block));
David Brazdil46e2a392015-03-16 17:31:52 +00001150 loop_info->Remove(left_branch);
1151 loop_info->Remove(right_branch);
1152 loop_info->Remove(end_block);
1153 if (loop_info->IsBackEdge(*end_block)) {
1154 loop_info->RemoveBackEdge(end_block);
1155 loop_info->AddBackEdge(start_block);
1156 }
David Brazdil46e2a392015-03-16 17:31:52 +00001157 }
1158}
1159
Calin Juravleacf735c2015-02-12 15:25:22 +00001160std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1161 ScopedObjectAccess soa(Thread::Current());
1162 os << "["
1163 << " is_top=" << rhs.IsTop()
1164 << " type=" << (rhs.IsTop() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
1165 << " is_exact=" << rhs.IsExact()
1166 << " ]";
1167 return os;
1168}
1169
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001170} // namespace art