blob: 5fca4fab22bcd5c5aa8850e7a8ec4b8be0a1881f [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);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010054 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000055 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
56 RemoveAsUser(it.Current());
57 }
58 }
59 }
60}
61
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010062void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010063 for (size_t i = 0; i < blocks_.Size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000064 if (!visited.IsBitSet(i)) {
David Brazdil1abb4192015-02-17 18:33:36 +000065 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010066 // We only need to update the successor, which might be live.
David Brazdil1abb4192015-02-17 18:33:36 +000067 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
68 block->GetSuccessors().Get(j)->RemovePredecessor(block);
69 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010070 // Remove the block from the list of blocks, so that further analyses
71 // never see it.
72 blocks_.Put(i, nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000073 }
74 }
75}
76
77void HGraph::VisitBlockForBackEdges(HBasicBlock* block,
78 ArenaBitVector* visited,
Nicolas Geoffray804d0932014-05-02 08:46:00 +010079 ArenaBitVector* visiting) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000080 int id = block->GetBlockId();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000081 if (visited->IsBitSet(id)) return;
82
83 visited->SetBit(id);
84 visiting->SetBit(id);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010085 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
86 HBasicBlock* successor = block->GetSuccessors().Get(i);
Nicolas Geoffray787c3072014-03-17 10:20:19 +000087 if (visiting->IsBitSet(successor->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000088 successor->AddBackEdge(block);
89 } else {
90 VisitBlockForBackEdges(successor, visited, visiting);
91 }
92 }
93 visiting->ClearBit(id);
94}
95
96void HGraph::BuildDominatorTree() {
97 ArenaBitVector visited(arena_, blocks_.Size(), false);
98
99 // (1) Find the back edges in the graph doing a DFS traversal.
100 FindBackEdges(&visited);
101
Roland Levillainfc600dc2014-12-02 17:16:31 +0000102 // (2) Remove instructions and phis from blocks not visited during
103 // the initial DFS as users from other instructions, so that
104 // users can be safely removed before uses later.
105 RemoveInstructionsAsUsersFromDeadBlocks(visited);
106
107 // (3) Remove blocks not visited during the initial DFS.
108 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000109 // predecessors list of live blocks.
110 RemoveDeadBlocks(visited);
111
Roland Levillainfc600dc2014-12-02 17:16:31 +0000112 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100113 // dominators and the reverse post order.
114 SimplifyCFG();
115
Roland Levillainfc600dc2014-12-02 17:16:31 +0000116 // (5) Compute the immediate dominator of each block. We visit
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000117 // the successors of a block only when all its forward branches
118 // have been processed.
119 GrowableArray<size_t> visits(arena_, blocks_.Size());
120 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100121 reverse_post_order_.Add(entry_block_);
122 for (size_t i = 0; i < entry_block_->GetSuccessors().Size(); i++) {
123 VisitBlockForDominatorTree(entry_block_->GetSuccessors().Get(i), entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000124 }
125}
126
127HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
128 ArenaBitVector visited(arena_, blocks_.Size(), false);
129 // Walk the dominator tree of the first block and mark the visited blocks.
130 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000131 visited.SetBit(first->GetBlockId());
132 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000133 }
134 // Walk the dominator tree of the second block until a marked block is found.
135 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000136 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000137 return second;
138 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000139 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000140 }
141 LOG(ERROR) << "Could not find common dominator";
142 return nullptr;
143}
144
145void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
146 HBasicBlock* predecessor,
147 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000148 if (block->GetDominator() == nullptr) {
149 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000150 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000151 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000152 }
153
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000154 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000155 // Once all the forward edges have been visited, we know the immediate
156 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000157 if (visits->Get(block->GetBlockId()) ==
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100158 block->GetPredecessors().Size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100159 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100160 reverse_post_order_.Add(block);
161 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
162 VisitBlockForDominatorTree(block->GetSuccessors().Get(i), block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000163 }
164 }
165}
166
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000167void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100168 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100169 SsaBuilder ssa_builder(this);
170 ssa_builder.BuildSsa();
171}
172
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100173void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
174 // Insert a new node between `block` and `successor` to split the
175 // critical edge.
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100176 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100177 AddBlock(new_block);
178 new_block->AddInstruction(new (arena_) HGoto());
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100179 block->ReplaceSuccessor(successor, new_block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100180 new_block->AddSuccessor(successor);
181 if (successor->IsLoopHeader()) {
182 // If we split at a back edge boundary, make the new block the back edge.
183 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000184 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100185 info->RemoveBackEdge(block);
186 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100187 }
188 }
189}
190
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100191void HGraph::SimplifyLoop(HBasicBlock* header) {
192 HLoopInformation* info = header->GetLoopInformation();
193
194 // If there are more than one back edge, make them branch to the same block that
195 // will become the only back edge. This simplifies finding natural loops in the
196 // graph.
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100197 // Also, if the loop is a do/while (that is the back edge is an if), change the
198 // back edge to be a goto. This simplifies code generation of suspend cheks.
199 if (info->NumberOfBackEdges() > 1 || info->GetBackEdges().Get(0)->GetLastInstruction()->IsIf()) {
200 HBasicBlock* new_back_edge = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100201 AddBlock(new_back_edge);
202 new_back_edge->AddInstruction(new (arena_) HGoto());
203 for (size_t pred = 0, e = info->GetBackEdges().Size(); pred < e; ++pred) {
204 HBasicBlock* back_edge = info->GetBackEdges().Get(pred);
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100205 back_edge->ReplaceSuccessor(header, new_back_edge);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100206 }
207 info->ClearBackEdges();
208 info->AddBackEdge(new_back_edge);
209 new_back_edge->AddSuccessor(header);
210 }
211
212 // Make sure the loop has only one pre header. This simplifies SSA building by having
213 // to just look at the pre header to know which locals are initialized at entry of the
214 // loop.
215 size_t number_of_incomings = header->GetPredecessors().Size() - info->NumberOfBackEdges();
216 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100217 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100218 AddBlock(pre_header);
219 pre_header->AddInstruction(new (arena_) HGoto());
220
221 ArenaBitVector back_edges(arena_, GetBlocks().Size(), false);
222 HBasicBlock* back_edge = info->GetBackEdges().Get(0);
223 for (size_t pred = 0; pred < header->GetPredecessors().Size(); ++pred) {
224 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
225 if (predecessor != back_edge) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100226 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100227 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100228 }
229 }
230 pre_header->AddSuccessor(header);
231 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100232
233 // Make sure the second predecessor of a loop header is the back edge.
234 if (header->GetPredecessors().Get(1) != info->GetBackEdges().Get(0)) {
235 header->SwapPredecessors();
236 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100237
238 // Place the suspend check at the beginning of the header, so that live registers
239 // will be known when allocating registers. Note that code generation can still
240 // generate the suspend check at the back edge, but needs to be careful with
241 // loop phi spill slots (which are not written to at back edge).
242 HInstruction* first_instruction = header->GetFirstInstruction();
243 if (!first_instruction->IsSuspendCheck()) {
244 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
245 header->InsertInstructionBefore(check, first_instruction);
246 first_instruction = check;
247 }
248 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100249}
250
251void HGraph::SimplifyCFG() {
252 // Simplify the CFG for future analysis, and code generation:
253 // (1): Split critical edges.
254 // (2): Simplify loops by having only one back edge, and one preheader.
255 for (size_t i = 0; i < blocks_.Size(); ++i) {
256 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100257 if (block == nullptr) continue;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100258 if (block->GetSuccessors().Size() > 1) {
259 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
260 HBasicBlock* successor = block->GetSuccessors().Get(j);
261 if (successor->GetPredecessors().Size() > 1) {
262 SplitCriticalEdge(block, successor);
263 --j;
264 }
265 }
266 }
267 if (block->IsLoopHeader()) {
268 SimplifyLoop(block);
269 }
270 }
271}
272
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000273bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100274 // Order does not matter.
275 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
276 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100277 if (block->IsLoopHeader()) {
278 HLoopInformation* info = block->GetLoopInformation();
279 if (!info->Populate()) {
280 // Abort if the loop is non natural. We currently bailout in such cases.
281 return false;
282 }
283 }
284 }
285 return true;
286}
287
David Brazdil8d5b8b22015-03-24 10:51:52 +0000288void HGraph::InsertConstant(HConstant* constant) {
289 // New constants are inserted before the final control-flow instruction
290 // of the graph, or at its end if called from the graph builder.
291 if (entry_block_->EndsWithControlFlowInstruction()) {
292 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000293 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000294 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000295 }
296}
297
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000298HNullConstant* HGraph::GetNullConstant() {
299 if (cached_null_constant_ == nullptr) {
300 cached_null_constant_ = new (arena_) HNullConstant();
David Brazdil8d5b8b22015-03-24 10:51:52 +0000301 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000302 }
303 return cached_null_constant_;
304}
305
David Brazdil8d5b8b22015-03-24 10:51:52 +0000306template <class InstructionType, typename ValueType>
307InstructionType* HGraph::CreateConstant(ValueType value,
308 ArenaSafeMap<ValueType, InstructionType*>* cache) {
309 // Try to find an existing constant of the given value.
310 InstructionType* constant = nullptr;
311 auto cached_constant = cache->find(value);
312 if (cached_constant != cache->end()) {
313 constant = cached_constant->second;
David Brazdil46e2a392015-03-16 17:31:52 +0000314 }
David Brazdil8d5b8b22015-03-24 10:51:52 +0000315
316 // If not found or previously deleted, create and cache a new instruction.
317 if (constant == nullptr || constant->GetBlock() == nullptr) {
318 constant = new (arena_) InstructionType(value);
319 cache->Overwrite(value, constant);
320 InsertConstant(constant);
321 }
322 return constant;
David Brazdil46e2a392015-03-16 17:31:52 +0000323}
324
David Brazdil8d5b8b22015-03-24 10:51:52 +0000325HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value) {
326 switch (type) {
327 case Primitive::Type::kPrimBoolean:
328 DCHECK(IsUint<1>(value));
329 FALLTHROUGH_INTENDED;
330 case Primitive::Type::kPrimByte:
331 case Primitive::Type::kPrimChar:
332 case Primitive::Type::kPrimShort:
333 case Primitive::Type::kPrimInt:
334 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
335 return GetIntConstant(static_cast<int32_t>(value));
336
337 case Primitive::Type::kPrimLong:
338 return GetLongConstant(value);
339
340 default:
341 LOG(FATAL) << "Unsupported constant type";
342 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000343 }
David Brazdil46e2a392015-03-16 17:31:52 +0000344}
345
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000346void HLoopInformation::Add(HBasicBlock* block) {
347 blocks_.SetBit(block->GetBlockId());
348}
349
David Brazdil46e2a392015-03-16 17:31:52 +0000350void HLoopInformation::Remove(HBasicBlock* block) {
351 blocks_.ClearBit(block->GetBlockId());
352}
353
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100354void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
355 if (blocks_.IsBitSet(block->GetBlockId())) {
356 return;
357 }
358
359 blocks_.SetBit(block->GetBlockId());
360 block->SetInLoop(this);
361 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
362 PopulateRecursive(block->GetPredecessors().Get(i));
363 }
364}
365
366bool HLoopInformation::Populate() {
367 DCHECK_EQ(GetBackEdges().Size(), 1u);
368 HBasicBlock* back_edge = GetBackEdges().Get(0);
369 DCHECK(back_edge->GetDominator() != nullptr);
370 if (!header_->Dominates(back_edge)) {
371 // This loop is not natural. Do not bother going further.
372 return false;
373 }
374
375 // Populate this loop: starting with the back edge, recursively add predecessors
376 // that are not already part of that loop. Set the header as part of the loop
377 // to end the recursion.
378 // This is a recursive implementation of the algorithm described in
379 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
380 blocks_.SetBit(header_->GetBlockId());
381 PopulateRecursive(back_edge);
382 return true;
383}
384
385HBasicBlock* HLoopInformation::GetPreHeader() const {
386 DCHECK_EQ(header_->GetPredecessors().Size(), 2u);
387 return header_->GetDominator();
388}
389
390bool HLoopInformation::Contains(const HBasicBlock& block) const {
391 return blocks_.IsBitSet(block.GetBlockId());
392}
393
394bool HLoopInformation::IsIn(const HLoopInformation& other) const {
395 return other.blocks_.IsBitSet(header_->GetBlockId());
396}
397
398bool HBasicBlock::Dominates(HBasicBlock* other) const {
399 // Walk up the dominator tree from `other`, to find out if `this`
400 // is an ancestor.
401 HBasicBlock* current = other;
402 while (current != nullptr) {
403 if (current == this) {
404 return true;
405 }
406 current = current->GetDominator();
407 }
408 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100409}
410
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100411static void UpdateInputsUsers(HInstruction* instruction) {
412 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
413 instruction->InputAt(i)->AddUseAt(instruction, i);
414 }
415 // Environment should be created later.
416 DCHECK(!instruction->HasEnvironment());
417}
418
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100419void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
Roland Levillain476df552014-10-09 17:51:36 +0100420 DCHECK(!cursor->IsPhi());
421 DCHECK(!instruction->IsPhi());
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100422 DCHECK_EQ(instruction->GetId(), -1);
423 DCHECK_NE(cursor->GetId(), -1);
424 DCHECK_EQ(cursor->GetBlock(), this);
425 DCHECK(!instruction->IsControlFlow());
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100426 instruction->next_ = cursor;
427 instruction->previous_ = cursor->previous_;
428 cursor->previous_ = instruction;
429 if (GetFirstInstruction() == cursor) {
430 instructions_.first_instruction_ = instruction;
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100431 } else {
432 instruction->previous_->next_ = instruction;
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100433 }
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100434 instruction->SetBlock(this);
435 instruction->SetId(GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100436 UpdateInputsUsers(instruction);
Nicolas Geoffray4e3d23a2014-05-22 18:32:45 +0100437}
438
Roland Levillainccc07a92014-09-16 14:48:16 +0100439void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
440 HInstruction* replacement) {
441 DCHECK(initial->GetBlock() == this);
442 InsertInstructionBefore(replacement, initial);
443 initial->ReplaceWith(replacement);
444 RemoveInstruction(initial);
445}
446
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100447static void Add(HInstructionList* instruction_list,
448 HBasicBlock* block,
449 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000450 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000451 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100452 instruction->SetBlock(block);
453 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100454 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100455 instruction_list->AddInstruction(instruction);
456}
457
458void HBasicBlock::AddInstruction(HInstruction* instruction) {
459 Add(&instructions_, this, instruction);
460}
461
462void HBasicBlock::AddPhi(HPhi* phi) {
463 Add(&phis_, this, phi);
464}
465
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100466void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
467 DCHECK_EQ(phi->GetId(), -1);
468 DCHECK_NE(cursor->GetId(), -1);
469 DCHECK_EQ(cursor->GetBlock(), this);
470 if (cursor->next_ == nullptr) {
471 cursor->next_ = phi;
472 phi->previous_ = cursor;
473 DCHECK(phi->next_ == nullptr);
474 } else {
475 phi->next_ = cursor->next_;
476 phi->previous_ = cursor;
477 cursor->next_ = phi;
478 phi->next_->previous_ = phi;
479 }
480 phi->SetBlock(this);
481 phi->SetId(GetGraph()->GetNextInstructionId());
482 UpdateInputsUsers(phi);
483}
484
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100485static void Remove(HInstructionList* instruction_list,
486 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000487 HInstruction* instruction,
488 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100489 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100490 instruction->SetBlock(nullptr);
491 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000492 if (ensure_safety) {
493 DCHECK(instruction->GetUses().IsEmpty());
494 DCHECK(instruction->GetEnvUses().IsEmpty());
495 RemoveAsUser(instruction);
496 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100497}
498
David Brazdil1abb4192015-02-17 18:33:36 +0000499void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
500 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100501}
502
David Brazdil1abb4192015-02-17 18:33:36 +0000503void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
504 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100505}
506
David Brazdiled596192015-01-23 10:39:45 +0000507void HEnvironment::CopyFrom(HEnvironment* env) {
508 for (size_t i = 0; i < env->Size(); i++) {
509 HInstruction* instruction = env->GetInstructionAt(i);
510 SetRawEnvAt(i, instruction);
511 if (instruction != nullptr) {
512 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100513 }
David Brazdiled596192015-01-23 10:39:45 +0000514 }
515}
516
David Brazdil1abb4192015-02-17 18:33:36 +0000517void HEnvironment::RemoveAsUserOfInput(size_t index) const {
518 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
519 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100520}
521
Calin Juravle77520bc2015-01-12 18:45:46 +0000522HInstruction* HInstruction::GetNextDisregardingMoves() const {
523 HInstruction* next = GetNext();
524 while (next != nullptr && next->IsParallelMove()) {
525 next = next->GetNext();
526 }
527 return next;
528}
529
530HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
531 HInstruction* previous = GetPrevious();
532 while (previous != nullptr && previous->IsParallelMove()) {
533 previous = previous->GetPrevious();
534 }
535 return previous;
536}
537
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100538void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000539 if (first_instruction_ == nullptr) {
540 DCHECK(last_instruction_ == nullptr);
541 first_instruction_ = last_instruction_ = instruction;
542 } else {
543 last_instruction_->next_ = instruction;
544 instruction->previous_ = last_instruction_;
545 last_instruction_ = instruction;
546 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000547}
548
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100549void HInstructionList::RemoveInstruction(HInstruction* instruction) {
550 if (instruction->previous_ != nullptr) {
551 instruction->previous_->next_ = instruction->next_;
552 }
553 if (instruction->next_ != nullptr) {
554 instruction->next_->previous_ = instruction->previous_;
555 }
556 if (instruction == first_instruction_) {
557 first_instruction_ = instruction->next_;
558 }
559 if (instruction == last_instruction_) {
560 last_instruction_ = instruction->previous_;
561 }
562}
563
Roland Levillain6b469232014-09-25 10:10:38 +0100564bool HInstructionList::Contains(HInstruction* instruction) const {
565 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
566 if (it.Current() == instruction) {
567 return true;
568 }
569 }
570 return false;
571}
572
Roland Levillainccc07a92014-09-16 14:48:16 +0100573bool HInstructionList::FoundBefore(const HInstruction* instruction1,
574 const HInstruction* instruction2) const {
575 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
576 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
577 if (it.Current() == instruction1) {
578 return true;
579 }
580 if (it.Current() == instruction2) {
581 return false;
582 }
583 }
584 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
585 return true;
586}
587
Roland Levillain6c82d402014-10-13 16:10:27 +0100588bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
589 if (other_instruction == this) {
590 // An instruction does not strictly dominate itself.
591 return false;
592 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100593 HBasicBlock* block = GetBlock();
594 HBasicBlock* other_block = other_instruction->GetBlock();
595 if (block != other_block) {
596 return GetBlock()->Dominates(other_instruction->GetBlock());
597 } else {
598 // If both instructions are in the same block, ensure this
599 // instruction comes before `other_instruction`.
600 if (IsPhi()) {
601 if (!other_instruction->IsPhi()) {
602 // Phis appear before non phi-instructions so this instruction
603 // dominates `other_instruction`.
604 return true;
605 } else {
606 // There is no order among phis.
607 LOG(FATAL) << "There is no dominance between phis of a same block.";
608 return false;
609 }
610 } else {
611 // `this` is not a phi.
612 if (other_instruction->IsPhi()) {
613 // Phis appear before non phi-instructions so this instruction
614 // does not dominate `other_instruction`.
615 return false;
616 } else {
617 // Check whether this instruction comes before
618 // `other_instruction` in the instruction list.
619 return block->GetInstructions().FoundBefore(this, other_instruction);
620 }
621 }
622 }
623}
624
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100625void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100626 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000627 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
628 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100629 HInstruction* user = current->GetUser();
630 size_t input_index = current->GetIndex();
631 user->SetRawInputAt(input_index, other);
632 other->AddUseAt(user, input_index);
633 }
634
David Brazdiled596192015-01-23 10:39:45 +0000635 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
636 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100637 HEnvironment* user = current->GetUser();
638 size_t input_index = current->GetIndex();
639 user->SetRawEnvAt(input_index, other);
640 other->AddEnvUseAt(user, input_index);
641 }
642
David Brazdiled596192015-01-23 10:39:45 +0000643 uses_.Clear();
644 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100645}
646
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100647void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000648 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100649 SetRawInputAt(index, replacement);
650 replacement->AddUseAt(this, index);
651}
652
Nicolas Geoffray39468442014-09-02 15:17:15 +0100653size_t HInstruction::EnvironmentSize() const {
654 return HasEnvironment() ? environment_->Size() : 0;
655}
656
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100657void HPhi::AddInput(HInstruction* input) {
658 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000659 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100660 input->AddUseAt(this, inputs_.Size() - 1);
661}
662
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100663#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000664void H##name::Accept(HGraphVisitor* visitor) { \
665 visitor->Visit##name(this); \
666}
667
668FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
669
670#undef DEFINE_ACCEPT
671
672void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100673 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
674 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000675 HBasicBlock* block = blocks.Get(i);
676 if (block != nullptr) {
677 VisitBasicBlock(block);
678 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000679 }
680}
681
Roland Levillain633021e2014-10-01 14:12:25 +0100682void HGraphVisitor::VisitReversePostOrder() {
683 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
684 VisitBasicBlock(it.Current());
685 }
686}
687
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000688void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100689 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100690 it.Current()->Accept(this);
691 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100692 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000693 it.Current()->Accept(this);
694 }
695}
696
Roland Levillain9240d6a2014-10-20 16:47:04 +0100697HConstant* HUnaryOperation::TryStaticEvaluation() const {
698 if (GetInput()->IsIntConstant()) {
699 int32_t value = Evaluate(GetInput()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000700 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain9240d6a2014-10-20 16:47:04 +0100701 } else if (GetInput()->IsLongConstant()) {
Roland Levillainb762d2e2014-10-22 10:11:06 +0100702 // TODO: Implement static evaluation of long unary operations.
703 //
704 // Do not exit with a fatal condition here. Instead, simply
705 // return `nullptr' to notify the caller that this instruction
706 // cannot (yet) be statically evaluated.
Roland Levillain9240d6a2014-10-20 16:47:04 +0100707 return nullptr;
708 }
709 return nullptr;
710}
711
712HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain556c3d12014-09-18 15:25:07 +0100713 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
714 int32_t value = Evaluate(GetLeft()->AsIntConstant()->GetValue(),
715 GetRight()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000716 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain556c3d12014-09-18 15:25:07 +0100717 } else if (GetLeft()->IsLongConstant() && GetRight()->IsLongConstant()) {
718 int64_t value = Evaluate(GetLeft()->AsLongConstant()->GetValue(),
719 GetRight()->AsLongConstant()->GetValue());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000720 if (GetResultType() == Primitive::kPrimLong) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000721 return GetBlock()->GetGraph()->GetLongConstant(value);
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000722 } else {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000723 DCHECK_EQ(GetResultType(), Primitive::kPrimInt);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000724 return GetBlock()->GetGraph()->GetIntConstant(static_cast<int32_t>(value));
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000725 }
Roland Levillain556c3d12014-09-18 15:25:07 +0100726 }
727 return nullptr;
728}
Dave Allison20dfc792014-06-16 20:44:29 -0700729
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000730HConstant* HBinaryOperation::GetConstantRight() const {
731 if (GetRight()->IsConstant()) {
732 return GetRight()->AsConstant();
733 } else if (IsCommutative() && GetLeft()->IsConstant()) {
734 return GetLeft()->AsConstant();
735 } else {
736 return nullptr;
737 }
738}
739
740// If `GetConstantRight()` returns one of the input, this returns the other
741// one. Otherwise it returns nullptr.
742HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
743 HInstruction* most_constant_right = GetConstantRight();
744 if (most_constant_right == nullptr) {
745 return nullptr;
746 } else if (most_constant_right == GetLeft()) {
747 return GetRight();
748 } else {
749 return GetLeft();
750 }
751}
752
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700753bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
754 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100755}
756
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100757bool HInstruction::Equals(HInstruction* other) const {
758 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100759 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100760 if (!InstructionDataEquals(other)) return false;
761 if (GetType() != other->GetType()) return false;
762 if (InputCount() != other->InputCount()) return false;
763
764 for (size_t i = 0, e = InputCount(); i < e; ++i) {
765 if (InputAt(i) != other->InputAt(i)) return false;
766 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100767 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100768 return true;
769}
770
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700771std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
772#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
773 switch (rhs) {
774 FOR_EACH_INSTRUCTION(DECLARE_CASE)
775 default:
776 os << "Unknown instruction kind " << static_cast<int>(rhs);
777 break;
778 }
779#undef DECLARE_CASE
780 return os;
781}
782
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000783void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000784 next_->previous_ = previous_;
785 if (previous_ != nullptr) {
786 previous_->next_ = next_;
787 }
788 if (block_->instructions_.first_instruction_ == this) {
789 block_->instructions_.first_instruction_ = next_;
790 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000791 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000792
793 previous_ = cursor->previous_;
794 if (previous_ != nullptr) {
795 previous_->next_ = this;
796 }
797 next_ = cursor;
798 cursor->previous_ = this;
799 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000800
801 if (block_->instructions_.first_instruction_ == cursor) {
802 block_->instructions_.first_instruction_ = this;
803 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000804}
805
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000806HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
807 DCHECK(!cursor->IsControlFlow());
808 DCHECK_NE(instructions_.last_instruction_, cursor);
809 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000810
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000811 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
812 new_block->instructions_.first_instruction_ = cursor->GetNext();
813 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
814 cursor->next_->previous_ = nullptr;
815 cursor->next_ = nullptr;
816 instructions_.last_instruction_ = cursor;
817
818 new_block->instructions_.SetBlockOfInstructions(new_block);
819 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
820 HBasicBlock* successor = GetSuccessors().Get(i);
821 new_block->successors_.Add(successor);
822 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
823 }
824 successors_.Reset();
825
826 for (size_t i = 0, e = GetDominatedBlocks().Size(); i < e; ++i) {
827 HBasicBlock* dominated = GetDominatedBlocks().Get(i);
828 dominated->dominator_ = new_block;
829 new_block->dominated_blocks_.Add(dominated);
830 }
831 dominated_blocks_.Reset();
832 return new_block;
833}
834
David Brazdil46e2a392015-03-16 17:31:52 +0000835bool HBasicBlock::IsSingleGoto() const {
836 HLoopInformation* loop_info = GetLoopInformation();
837 // TODO: Remove the null check b/19084197.
838 return GetFirstInstruction() != nullptr
839 && GetPhis().IsEmpty()
840 && GetFirstInstruction() == GetLastInstruction()
841 && GetLastInstruction()->IsGoto()
842 // Back edges generate the suspend check.
843 && (loop_info == nullptr || !loop_info->IsBackEdge(*this));
844}
845
David Brazdil8d5b8b22015-03-24 10:51:52 +0000846bool HBasicBlock::EndsWithControlFlowInstruction() const {
847 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
848}
849
David Brazdilb2bd1c52015-03-25 11:17:37 +0000850bool HBasicBlock::EndsWithIf() const {
851 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
852}
853
854bool HBasicBlock::HasSinglePhi() const {
855 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
856}
857
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000858void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
859 for (HInstruction* current = first_instruction_;
860 current != nullptr;
861 current = current->GetNext()) {
862 current->SetBlock(block);
863 }
864}
865
866void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
867 DCHECK(Contains(cursor));
868 if (!instruction_list.IsEmpty()) {
869 if (cursor == last_instruction_) {
870 last_instruction_ = instruction_list.last_instruction_;
871 } else {
872 cursor->next_->previous_ = instruction_list.last_instruction_;
873 }
874 instruction_list.last_instruction_->next_ = cursor->next_;
875 cursor->next_ = instruction_list.first_instruction_;
876 instruction_list.first_instruction_->previous_ = cursor;
877 }
878}
879
880void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +0000881 if (IsEmpty()) {
882 first_instruction_ = instruction_list.first_instruction_;
883 last_instruction_ = instruction_list.last_instruction_;
884 } else {
885 AddAfter(last_instruction_, instruction_list);
886 }
887}
888
889void HBasicBlock::DisconnectFromAll() {
890 DCHECK(dominated_blocks_.IsEmpty()) << "Unimplemented scenario";
891
892 for (size_t i = 0, e = predecessors_.Size(); i < e; ++i) {
893 predecessors_.Get(i)->successors_.Delete(this);
894 }
895 for (size_t i = 0, e = successors_.Size(); i < e; ++i) {
896 successors_.Get(i)->predecessors_.Delete(this);
897 }
898 dominator_->dominated_blocks_.Delete(this);
899
900 predecessors_.Reset();
901 successors_.Reset();
902 dominator_ = nullptr;
903 graph_ = nullptr;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000904}
905
906void HBasicBlock::MergeWith(HBasicBlock* other) {
907 DCHECK(successors_.IsEmpty()) << "Unimplemented block merge scenario";
David Brazdil46e2a392015-03-16 17:31:52 +0000908 DCHECK(dominated_blocks_.IsEmpty()
909 || (dominated_blocks_.Size() == 1 && dominated_blocks_.Get(0) == other))
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000910 << "Unimplemented block merge scenario";
911 DCHECK(other->GetPhis().IsEmpty());
912
913 successors_.Reset();
914 dominated_blocks_.Reset();
915 instructions_.Add(other->GetInstructions());
916 other->GetInstructions().SetBlockOfInstructions(this);
917
918 while (!other->GetSuccessors().IsEmpty()) {
919 HBasicBlock* successor = other->GetSuccessors().Get(0);
920 successor->ReplacePredecessor(other, this);
921 }
922
923 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
924 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
925 dominated_blocks_.Add(dominated);
926 dominated->SetDominator(this);
927 }
928 other->dominated_blocks_.Reset();
929 other->dominator_ = nullptr;
930 other->graph_ = nullptr;
931}
932
933void HBasicBlock::ReplaceWith(HBasicBlock* other) {
934 while (!GetPredecessors().IsEmpty()) {
935 HBasicBlock* predecessor = GetPredecessors().Get(0);
936 predecessor->ReplaceSuccessor(this, other);
937 }
938 while (!GetSuccessors().IsEmpty()) {
939 HBasicBlock* successor = GetSuccessors().Get(0);
940 successor->ReplacePredecessor(this, other);
941 }
942 for (size_t i = 0; i < dominated_blocks_.Size(); ++i) {
943 other->AddDominatedBlock(dominated_blocks_.Get(i));
944 }
945 GetDominator()->ReplaceDominatedBlock(this, other);
946 other->SetDominator(GetDominator());
947 dominator_ = nullptr;
948 graph_ = nullptr;
949}
950
951// Create space in `blocks` for adding `number_of_new_blocks` entries
952// starting at location `at`. Blocks after `at` are moved accordingly.
953static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
954 size_t number_of_new_blocks,
955 size_t at) {
956 size_t old_size = blocks->Size();
957 size_t new_size = old_size + number_of_new_blocks;
958 blocks->SetSize(new_size);
959 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
960 blocks->Put(j, blocks->Get(i));
961 }
962}
963
964void HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000965 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +0000966 // Simple case of an entry block, a body block, and an exit block.
967 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000968 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +0000969 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
970 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000971 DCHECK(!body->IsExitBlock());
972 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000973
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000974 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
975 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000976
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000977 // Replace the invoke with the return value of the inlined graph.
978 if (last->IsReturn()) {
979 invoke->ReplaceWith(last->InputAt(0));
980 } else {
981 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000982 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000983
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000984 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000985 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000986 // Need to inline multiple blocks. We split `invoke`'s block
987 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +0000988 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000989 // with the second half.
990 ArenaAllocator* allocator = outer_graph->GetArena();
991 HBasicBlock* at = invoke->GetBlock();
992 HBasicBlock* to = at->SplitAfter(invoke);
993
994 HBasicBlock* first = entry_block_->GetSuccessors().Get(0);
995 DCHECK(!first->IsInLoop());
996 at->MergeWith(first);
997 exit_block_->ReplaceWith(to);
998
999 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001000 // to not `HReturn` but `HGoto` instead.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001001 HInstruction* return_value = nullptr;
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001002 bool returns_void = to->GetPredecessors().Get(0)->GetLastInstruction()->IsReturnVoid();
1003 if (to->GetPredecessors().Size() == 1) {
1004 HBasicBlock* predecessor = to->GetPredecessors().Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001005 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001006 if (!returns_void) {
1007 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001008 }
1009 predecessor->AddInstruction(new (allocator) HGoto());
1010 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001011 } else {
1012 if (!returns_void) {
1013 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001014 return_value = new (allocator) HPhi(
1015 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001016 to->AddPhi(return_value->AsPhi());
1017 }
1018 for (size_t i = 0, e = to->GetPredecessors().Size(); i < e; ++i) {
1019 HBasicBlock* predecessor = to->GetPredecessors().Get(i);
1020 HInstruction* last = predecessor->GetLastInstruction();
1021 if (!returns_void) {
1022 return_value->AsPhi()->AddInput(last->InputAt(0));
1023 }
1024 predecessor->AddInstruction(new (allocator) HGoto());
1025 predecessor->RemoveInstruction(last);
1026 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001027 }
1028
1029 if (return_value != nullptr) {
1030 invoke->ReplaceWith(return_value);
1031 }
1032
1033 // Update the meta information surrounding blocks:
1034 // (1) the graph they are now in,
1035 // (2) the reverse post order of that graph,
1036 // (3) the potential loop information they are now in.
1037
1038 // We don't add the entry block, the exit block, and the first block, which
1039 // has been merged with `at`.
1040 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1041
1042 // We add the `to` block.
1043 static constexpr int kNumberOfNewBlocksInCaller = 1;
1044 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1045 + kNumberOfNewBlocksInCaller;
1046
1047 // Find the location of `at` in the outer graph's reverse post order. The new
1048 // blocks will be added after it.
1049 size_t index_of_at = 0;
1050 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1051 index_of_at++;
1052 }
1053 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1054
1055 // Do a reverse post order of the blocks in the callee and do (1), (2),
1056 // and (3) to the blocks that apply.
1057 HLoopInformation* info = at->GetLoopInformation();
1058 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1059 HBasicBlock* current = it.Current();
1060 if (current != exit_block_ && current != entry_block_ && current != first) {
1061 DCHECK(!current->IsInLoop());
1062 DCHECK(current->GetGraph() == this);
1063 current->SetGraph(outer_graph);
1064 outer_graph->AddBlock(current);
1065 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1066 if (info != nullptr) {
1067 info->Add(current);
1068 current->SetLoopInformation(info);
1069 }
1070 }
1071 }
1072
1073 // Do (1), (2), and (3) to `to`.
1074 to->SetGraph(outer_graph);
1075 outer_graph->AddBlock(to);
1076 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1077 if (info != nullptr) {
1078 info->Add(to);
1079 to->SetLoopInformation(info);
David Brazdil46e2a392015-03-16 17:31:52 +00001080 if (info->IsBackEdge(*at)) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001081 // Only `at` can become a back edge, as the inlined blocks
1082 // are predecessors of `at`.
1083 DCHECK_EQ(1u, info->NumberOfBackEdges());
1084 info->ClearBackEdges();
1085 info->AddBackEdge(to);
1086 }
1087 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001088 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001089
David Brazdil05144f42015-04-16 15:18:00 +01001090 // Update the next instruction id of the outer graph, so that instructions
1091 // added later get bigger ids than those in the inner graph.
1092 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1093
1094 // Walk over the entry block and:
1095 // - Move constants from the entry block to the outer_graph's entry block,
1096 // - Replace HParameterValue instructions with their real value.
1097 // - Remove suspend checks, that hold an environment.
1098 // We must do this after the other blocks have been inlined, otherwise ids of
1099 // constants could overlap with the inner graph.
1100 int parameter_index = 0;
1101 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1102 HInstruction* current = it.Current();
1103 if (current->IsNullConstant()) {
1104 current->ReplaceWith(outer_graph->GetNullConstant());
1105 } else if (current->IsIntConstant()) {
1106 current->ReplaceWith(outer_graph->GetIntConstant(current->AsIntConstant()->GetValue()));
1107 } else if (current->IsLongConstant()) {
1108 current->ReplaceWith(outer_graph->GetLongConstant(current->AsLongConstant()->GetValue()));
1109 } else if (current->IsFloatConstant() || current->IsDoubleConstant()) {
1110 // TODO: Don't duplicate floating-point constants.
1111 current->MoveBefore(outer_graph->GetEntryBlock()->GetLastInstruction());
1112 } else if (current->IsParameterValue()) {
1113 current->ReplaceWith(invoke->InputAt(parameter_index++));
1114 } else {
1115 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1116 entry_block_->RemoveInstruction(current);
1117 }
1118 }
1119
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001120 // Finally remove the invoke from the caller.
1121 invoke->GetBlock()->RemoveInstruction(invoke);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001122}
1123
David Brazdil46e2a392015-03-16 17:31:52 +00001124void HGraph::MergeEmptyBranches(HBasicBlock* start_block, HBasicBlock* end_block) {
David Brazdilb2bd1c52015-03-25 11:17:37 +00001125 // Find the two branches of an If.
David Brazdil46e2a392015-03-16 17:31:52 +00001126 DCHECK_EQ(start_block->GetSuccessors().Size(), 2u);
David Brazdil46e2a392015-03-16 17:31:52 +00001127 HBasicBlock* left_branch = start_block->GetSuccessors().Get(0);
1128 HBasicBlock* right_branch = start_block->GetSuccessors().Get(1);
David Brazdilb2bd1c52015-03-25 11:17:37 +00001129
1130 // Make sure this is a diamond control-flow path.
David Brazdil46e2a392015-03-16 17:31:52 +00001131 DCHECK_EQ(left_branch->GetSuccessors().Get(0), end_block);
1132 DCHECK_EQ(right_branch->GetSuccessors().Get(0), end_block);
David Brazdilb2bd1c52015-03-25 11:17:37 +00001133 DCHECK_EQ(end_block->GetPredecessors().Size(), 2u);
David Brazdil46e2a392015-03-16 17:31:52 +00001134 DCHECK_EQ(start_block, end_block->GetDominator());
1135
1136 // Disconnect the branches and merge the two blocks. This will move
1137 // all instructions from 'end_block' to 'start_block'.
1138 DCHECK(left_branch->IsSingleGoto());
1139 DCHECK(right_branch->IsSingleGoto());
1140 left_branch->DisconnectFromAll();
1141 right_branch->DisconnectFromAll();
1142 start_block->RemoveInstruction(start_block->GetLastInstruction());
1143 start_block->MergeWith(end_block);
1144
1145 // Delete the now redundant blocks from the graph.
1146 blocks_.Put(left_branch->GetBlockId(), nullptr);
1147 blocks_.Put(right_branch->GetBlockId(), nullptr);
1148 blocks_.Put(end_block->GetBlockId(), nullptr);
1149
1150 // Update reverse post order.
1151 reverse_post_order_.Delete(left_branch);
1152 reverse_post_order_.Delete(right_branch);
1153 reverse_post_order_.Delete(end_block);
1154
David Brazdilb2bd1c52015-03-25 11:17:37 +00001155 // Update loops which contain the code.
1156 for (HLoopInformationOutwardIterator it(*start_block); !it.Done(); it.Advance()) {
1157 HLoopInformation* loop_info = it.Current();
1158 DCHECK(loop_info->Contains(*left_branch));
1159 DCHECK(loop_info->Contains(*right_branch));
1160 DCHECK(loop_info->Contains(*end_block));
David Brazdil46e2a392015-03-16 17:31:52 +00001161 loop_info->Remove(left_branch);
1162 loop_info->Remove(right_branch);
1163 loop_info->Remove(end_block);
1164 if (loop_info->IsBackEdge(*end_block)) {
1165 loop_info->RemoveBackEdge(end_block);
1166 loop_info->AddBackEdge(start_block);
1167 }
David Brazdil46e2a392015-03-16 17:31:52 +00001168 }
1169}
1170
Calin Juravleacf735c2015-02-12 15:25:22 +00001171std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1172 ScopedObjectAccess soa(Thread::Current());
1173 os << "["
1174 << " is_top=" << rhs.IsTop()
1175 << " type=" << (rhs.IsTop() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
1176 << " is_exact=" << rhs.IsExact()
1177 << " ]";
1178 return os;
1179}
1180
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001181} // namespace art