blob: cc12a1035431afa1797fb039e348c5410d5eab16 [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
Mark Mendelle82549b2015-05-06 10:55:34 -040019#include "code_generator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010020#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010021#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010022#include "base/bit_utils.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010023#include "mirror/class-inl.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000024#include "utils/growable_array.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000025#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000026
27namespace art {
28
29void HGraph::AddBlock(HBasicBlock* block) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000030 block->SetBlockId(blocks_.Size());
Nicolas Geoffray818f2102014-02-18 16:43:35 +000031 blocks_.Add(block);
32}
33
Nicolas Geoffray804d0932014-05-02 08:46:00 +010034void HGraph::FindBackEdges(ArenaBitVector* visited) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000035 ArenaBitVector visiting(arena_, blocks_.Size(), false);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000036 VisitBlockForBackEdges(entry_block_, visited, &visiting);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000037}
38
Roland Levillainfc600dc2014-12-02 17:16:31 +000039static void RemoveAsUser(HInstruction* instruction) {
40 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000041 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000042 }
43
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010044 for (HEnvironment* environment = instruction->GetEnvironment();
45 environment != nullptr;
46 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000047 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000048 if (environment->GetInstructionAt(i) != nullptr) {
49 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000050 }
51 }
52 }
53}
54
55void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
56 for (size_t i = 0; i < blocks_.Size(); ++i) {
57 if (!visited.IsBitSet(i)) {
58 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010059 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000060 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
61 RemoveAsUser(it.Current());
62 }
63 }
64 }
65}
66
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010067void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010068 for (size_t i = 0; i < blocks_.Size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000069 if (!visited.IsBitSet(i)) {
David Brazdil1abb4192015-02-17 18:33:36 +000070 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010071 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +000072 for (HBasicBlock* successor : block->GetSuccessors()) {
73 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +000074 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010075 // Remove the block from the list of blocks, so that further analyses
76 // never see it.
77 blocks_.Put(i, nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000078 }
79 }
80}
81
82void HGraph::VisitBlockForBackEdges(HBasicBlock* block,
83 ArenaBitVector* visited,
Nicolas Geoffray804d0932014-05-02 08:46:00 +010084 ArenaBitVector* visiting) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000085 int id = block->GetBlockId();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000086 if (visited->IsBitSet(id)) return;
87
88 visited->SetBit(id);
89 visiting->SetBit(id);
Vladimir Marko60584552015-09-03 13:35:12 +000090 for (HBasicBlock* successor : block->GetSuccessors()) {
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() {
David Brazdilffee3d32015-07-06 11:48:53 +0100101 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
102 // edges. This invariant simplifies building SSA form because Phis cannot
103 // collect both normal- and exceptional-flow values at the same time.
104 SimplifyCatchBlocks();
105
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000106 ArenaBitVector visited(arena_, blocks_.Size(), false);
107
David Brazdilffee3d32015-07-06 11:48:53 +0100108 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000109 FindBackEdges(&visited);
110
David Brazdilffee3d32015-07-06 11:48:53 +0100111 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000112 // the initial DFS as users from other instructions, so that
113 // users can be safely removed before uses later.
114 RemoveInstructionsAsUsersFromDeadBlocks(visited);
115
David Brazdilffee3d32015-07-06 11:48:53 +0100116 // (4) Remove blocks not visited during the initial DFS.
Roland Levillainfc600dc2014-12-02 17:16:31 +0000117 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000118 // predecessors list of live blocks.
119 RemoveDeadBlocks(visited);
120
David Brazdilffee3d32015-07-06 11:48:53 +0100121 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100122 // dominators and the reverse post order.
123 SimplifyCFG();
124
David Brazdilffee3d32015-07-06 11:48:53 +0100125 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100126 ComputeDominanceInformation();
127}
128
129void HGraph::ClearDominanceInformation() {
130 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
131 it.Current()->ClearDominanceInformation();
132 }
133 reverse_post_order_.Reset();
134}
135
136void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000137 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100138 dominator_ = nullptr;
139}
140
141void HGraph::ComputeDominanceInformation() {
142 DCHECK(reverse_post_order_.IsEmpty());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000143 GrowableArray<size_t> visits(arena_, blocks_.Size());
144 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100145 reverse_post_order_.Add(entry_block_);
Vladimir Marko60584552015-09-03 13:35:12 +0000146 for (HBasicBlock* successor : entry_block_->GetSuccessors()) {
147 VisitBlockForDominatorTree(successor, entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000148 }
149}
150
151HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
152 ArenaBitVector visited(arena_, blocks_.Size(), false);
153 // Walk the dominator tree of the first block and mark the visited blocks.
154 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000155 visited.SetBit(first->GetBlockId());
156 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000157 }
158 // Walk the dominator tree of the second block until a marked block is found.
159 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000160 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000161 return second;
162 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000163 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000164 }
165 LOG(ERROR) << "Could not find common dominator";
166 return nullptr;
167}
168
169void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
170 HBasicBlock* predecessor,
171 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000172 if (block->GetDominator() == nullptr) {
173 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000174 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000175 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000176 }
177
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000178 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000179 // Once all the forward edges have been visited, we know the immediate
180 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000181 if (visits->Get(block->GetBlockId()) ==
Vladimir Marko60584552015-09-03 13:35:12 +0000182 block->GetPredecessors().size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100183 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100184 reverse_post_order_.Add(block);
Vladimir Marko60584552015-09-03 13:35:12 +0000185 for (HBasicBlock* successor : block->GetSuccessors()) {
186 VisitBlockForDominatorTree(successor, block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000187 }
188 }
189}
190
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000191void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100192 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100193 SsaBuilder ssa_builder(this);
194 ssa_builder.BuildSsa();
195}
196
David Brazdilfc6a86a2015-06-26 10:33:45 +0000197HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000198 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
199 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000200 // Use `InsertBetween` to ensure the predecessor index and successor index of
201 // `block` and `successor` are preserved.
202 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000203 return new_block;
204}
205
206void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
207 // Insert a new node between `block` and `successor` to split the
208 // critical edge.
209 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600210 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100211 if (successor->IsLoopHeader()) {
212 // If we split at a back edge boundary, make the new block the back edge.
213 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000214 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100215 info->RemoveBackEdge(block);
216 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100217 }
218 }
219}
220
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100221void HGraph::SimplifyLoop(HBasicBlock* header) {
222 HLoopInformation* info = header->GetLoopInformation();
223
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100224 // Make sure the loop has only one pre header. This simplifies SSA building by having
225 // to just look at the pre header to know which locals are initialized at entry of the
226 // loop.
Vladimir Marko60584552015-09-03 13:35:12 +0000227 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100228 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100229 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100230 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600231 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100232
Vladimir Marko60584552015-09-03 13:35:12 +0000233 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
234 HBasicBlock* predecessor = header->GetPredecessor(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100235 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100236 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100237 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100238 }
239 }
240 pre_header->AddSuccessor(header);
241 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100242
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100243 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Marko60584552015-09-03 13:35:12 +0000244 if (info->IsBackEdge(*header->GetPredecessor(0))) {
245 HBasicBlock* to_swap = header->GetPredecessor(0);
246 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
247 HBasicBlock* predecessor = header->GetPredecessor(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100248 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000249 header->predecessors_[pred] = to_swap;
250 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100251 break;
252 }
253 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100254 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100255
256 // Place the suspend check at the beginning of the header, so that live registers
257 // will be known when allocating registers. Note that code generation can still
258 // generate the suspend check at the back edge, but needs to be careful with
259 // loop phi spill slots (which are not written to at back edge).
260 HInstruction* first_instruction = header->GetFirstInstruction();
261 if (!first_instruction->IsSuspendCheck()) {
262 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
263 header->InsertInstructionBefore(check, first_instruction);
264 first_instruction = check;
265 }
266 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100267}
268
David Brazdilffee3d32015-07-06 11:48:53 +0100269static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Marko60584552015-09-03 13:35:12 +0000270 HBasicBlock* predecessor = block.GetPredecessor(pred_idx);
David Brazdilffee3d32015-07-06 11:48:53 +0100271 if (!predecessor->EndsWithTryBoundary()) {
272 // Only edges from HTryBoundary can be exceptional.
273 return false;
274 }
275 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
276 if (try_boundary->GetNormalFlowSuccessor() == &block) {
277 // This block is the normal-flow successor of `try_boundary`, but it could
278 // also be one of its exception handlers if catch blocks have not been
279 // simplified yet. Predecessors are unordered, so we will consider the first
280 // occurrence to be the normal edge and a possible second occurrence to be
281 // the exceptional edge.
282 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
283 } else {
284 // This is not the normal-flow successor of `try_boundary`, hence it must be
285 // one of its exception handlers.
286 DCHECK(try_boundary->HasExceptionHandler(block));
287 return true;
288 }
289}
290
291void HGraph::SimplifyCatchBlocks() {
292 for (size_t i = 0; i < blocks_.Size(); ++i) {
293 HBasicBlock* catch_block = blocks_.Get(i);
294 if (!catch_block->IsCatchBlock()) {
295 continue;
296 }
297
298 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000299 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100300 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
301 exceptional_predecessors_only = false;
302 break;
303 }
304 }
305
306 if (!exceptional_predecessors_only) {
307 // Catch block has normal-flow predecessors and needs to be simplified.
308 // Splitting the block before its first instruction moves all its
309 // instructions into `normal_block` and links the two blocks with a Goto.
310 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
311 // leaving `catch_block` with the exceptional edges only.
312 // Note that catch blocks with normal-flow predecessors cannot begin with
313 // a MOVE_EXCEPTION instruction, as guaranteed by the verifier.
314 DCHECK(!catch_block->GetFirstInstruction()->IsLoadException());
315 HBasicBlock* normal_block = catch_block->SplitBefore(catch_block->GetFirstInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +0000316 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100317 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000318 catch_block->GetPredecessor(j)->ReplaceSuccessor(catch_block, normal_block);
David Brazdilffee3d32015-07-06 11:48:53 +0100319 --j;
320 }
321 }
322 }
323 }
324}
325
326void HGraph::ComputeTryBlockInformation() {
327 // Iterate in reverse post order to propagate try membership information from
328 // predecessors to their successors.
329 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
330 HBasicBlock* block = it.Current();
331 if (block->IsEntryBlock() || block->IsCatchBlock()) {
332 // Catch blocks after simplification have only exceptional predecessors
333 // and hence are never in tries.
334 continue;
335 }
336
337 // Infer try membership from the first predecessor. Having simplified loops,
338 // the first predecessor can never be a back edge and therefore it must have
339 // been visited already and had its try membership set.
Vladimir Marko60584552015-09-03 13:35:12 +0000340 HBasicBlock* first_predecessor = block->GetPredecessor(0);
David Brazdilffee3d32015-07-06 11:48:53 +0100341 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100342 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
343 if (try_entry != nullptr) {
344 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
345 }
David Brazdilffee3d32015-07-06 11:48:53 +0100346 }
347}
348
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100349void HGraph::SimplifyCFG() {
350 // Simplify the CFG for future analysis, and code generation:
351 // (1): Split critical edges.
352 // (2): Simplify loops by having only one back edge, and one preheader.
353 for (size_t i = 0; i < blocks_.Size(); ++i) {
354 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100355 if (block == nullptr) continue;
David Brazdilffee3d32015-07-06 11:48:53 +0100356 if (block->NumberOfNormalSuccessors() > 1) {
Vladimir Marko60584552015-09-03 13:35:12 +0000357 for (size_t j = 0; j < block->GetSuccessors().size(); ++j) {
358 HBasicBlock* successor = block->GetSuccessor(j);
David Brazdilffee3d32015-07-06 11:48:53 +0100359 DCHECK(!successor->IsCatchBlock());
Vladimir Marko60584552015-09-03 13:35:12 +0000360 if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100361 SplitCriticalEdge(block, successor);
362 --j;
363 }
364 }
365 }
366 if (block->IsLoopHeader()) {
367 SimplifyLoop(block);
368 }
369 }
370}
371
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000372bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100373 // Order does not matter.
374 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
375 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100376 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100377 if (block->IsCatchBlock()) {
378 // TODO: Dealing with exceptional back edges could be tricky because
379 // they only approximate the real control flow. Bail out for now.
380 return false;
381 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100382 HLoopInformation* info = block->GetLoopInformation();
383 if (!info->Populate()) {
384 // Abort if the loop is non natural. We currently bailout in such cases.
385 return false;
386 }
387 }
388 }
389 return true;
390}
391
David Brazdil8d5b8b22015-03-24 10:51:52 +0000392void HGraph::InsertConstant(HConstant* constant) {
393 // New constants are inserted before the final control-flow instruction
394 // of the graph, or at its end if called from the graph builder.
395 if (entry_block_->EndsWithControlFlowInstruction()) {
396 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000397 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000398 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000399 }
400}
401
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600402HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100403 // For simplicity, don't bother reviving the cached null constant if it is
404 // not null and not in a block. Otherwise, we need to clear the instruction
405 // id and/or any invariants the graph is assuming when adding new instructions.
406 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600407 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000408 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000409 }
410 return cached_null_constant_;
411}
412
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100413HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100414 // For simplicity, don't bother reviving the cached current method if it is
415 // not null and not in a block. Otherwise, we need to clear the instruction
416 // id and/or any invariants the graph is assuming when adding new instructions.
417 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700418 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600419 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
420 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100421 if (entry_block_->GetFirstInstruction() == nullptr) {
422 entry_block_->AddInstruction(cached_current_method_);
423 } else {
424 entry_block_->InsertInstructionBefore(
425 cached_current_method_, entry_block_->GetFirstInstruction());
426 }
427 }
428 return cached_current_method_;
429}
430
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600431HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000432 switch (type) {
433 case Primitive::Type::kPrimBoolean:
434 DCHECK(IsUint<1>(value));
435 FALLTHROUGH_INTENDED;
436 case Primitive::Type::kPrimByte:
437 case Primitive::Type::kPrimChar:
438 case Primitive::Type::kPrimShort:
439 case Primitive::Type::kPrimInt:
440 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600441 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000442
443 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600444 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000445
446 default:
447 LOG(FATAL) << "Unsupported constant type";
448 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000449 }
David Brazdil46e2a392015-03-16 17:31:52 +0000450}
451
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000452void HGraph::CacheFloatConstant(HFloatConstant* constant) {
453 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
454 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
455 cached_float_constants_.Overwrite(value, constant);
456}
457
458void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
459 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
460 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
461 cached_double_constants_.Overwrite(value, constant);
462}
463
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000464void HLoopInformation::Add(HBasicBlock* block) {
465 blocks_.SetBit(block->GetBlockId());
466}
467
David Brazdil46e2a392015-03-16 17:31:52 +0000468void HLoopInformation::Remove(HBasicBlock* block) {
469 blocks_.ClearBit(block->GetBlockId());
470}
471
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100472void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
473 if (blocks_.IsBitSet(block->GetBlockId())) {
474 return;
475 }
476
477 blocks_.SetBit(block->GetBlockId());
478 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000479 for (HBasicBlock* predecessor : block->GetPredecessors()) {
480 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100481 }
482}
483
484bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100485 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100486 for (size_t i = 0, e = GetBackEdges().Size(); i < e; ++i) {
487 HBasicBlock* back_edge = GetBackEdges().Get(i);
488 DCHECK(back_edge->GetDominator() != nullptr);
489 if (!header_->Dominates(back_edge)) {
490 // This loop is not natural. Do not bother going further.
491 return false;
492 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100493
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100494 // Populate this loop: starting with the back edge, recursively add predecessors
495 // that are not already part of that loop. Set the header as part of the loop
496 // to end the recursion.
497 // This is a recursive implementation of the algorithm described in
498 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
499 blocks_.SetBit(header_->GetBlockId());
500 PopulateRecursive(back_edge);
501 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100502 return true;
503}
504
David Brazdila4b8c212015-05-07 09:59:30 +0100505void HLoopInformation::Update() {
506 HGraph* graph = header_->GetGraph();
507 for (uint32_t id : blocks_.Indexes()) {
508 HBasicBlock* block = graph->GetBlocks().Get(id);
509 // Reset loop information of non-header blocks inside the loop, except
510 // members of inner nested loops because those should already have been
511 // updated by their own LoopInformation.
512 if (block->GetLoopInformation() == this && block != header_) {
513 block->SetLoopInformation(nullptr);
514 }
515 }
516 blocks_.ClearAllBits();
517
518 if (back_edges_.IsEmpty()) {
519 // The loop has been dismantled, delete its suspend check and remove info
520 // from the header.
521 DCHECK(HasSuspendCheck());
522 header_->RemoveInstruction(suspend_check_);
523 header_->SetLoopInformation(nullptr);
524 header_ = nullptr;
525 suspend_check_ = nullptr;
526 } else {
527 if (kIsDebugBuild) {
528 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
529 DCHECK(header_->Dominates(back_edges_.Get(i)));
530 }
531 }
532 // This loop still has reachable back edges. Repopulate the list of blocks.
533 bool populate_successful = Populate();
534 DCHECK(populate_successful);
535 }
536}
537
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100538HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100539 return header_->GetDominator();
540}
541
542bool HLoopInformation::Contains(const HBasicBlock& block) const {
543 return blocks_.IsBitSet(block.GetBlockId());
544}
545
546bool HLoopInformation::IsIn(const HLoopInformation& other) const {
547 return other.blocks_.IsBitSet(header_->GetBlockId());
548}
549
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100550size_t HLoopInformation::GetLifetimeEnd() const {
551 size_t last_position = 0;
552 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
553 last_position = std::max(back_edges_.Get(i)->GetLifetimeEnd(), last_position);
554 }
555 return last_position;
556}
557
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100558bool HBasicBlock::Dominates(HBasicBlock* other) const {
559 // Walk up the dominator tree from `other`, to find out if `this`
560 // is an ancestor.
561 HBasicBlock* current = other;
562 while (current != nullptr) {
563 if (current == this) {
564 return true;
565 }
566 current = current->GetDominator();
567 }
568 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100569}
570
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100571static void UpdateInputsUsers(HInstruction* instruction) {
572 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
573 instruction->InputAt(i)->AddUseAt(instruction, i);
574 }
575 // Environment should be created later.
576 DCHECK(!instruction->HasEnvironment());
577}
578
Roland Levillainccc07a92014-09-16 14:48:16 +0100579void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
580 HInstruction* replacement) {
581 DCHECK(initial->GetBlock() == this);
582 InsertInstructionBefore(replacement, initial);
583 initial->ReplaceWith(replacement);
584 RemoveInstruction(initial);
585}
586
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100587static void Add(HInstructionList* instruction_list,
588 HBasicBlock* block,
589 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000590 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000591 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100592 instruction->SetBlock(block);
593 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100594 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100595 instruction_list->AddInstruction(instruction);
596}
597
598void HBasicBlock::AddInstruction(HInstruction* instruction) {
599 Add(&instructions_, this, instruction);
600}
601
602void HBasicBlock::AddPhi(HPhi* phi) {
603 Add(&phis_, this, phi);
604}
605
David Brazdilc3d743f2015-04-22 13:40:50 +0100606void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
607 DCHECK(!cursor->IsPhi());
608 DCHECK(!instruction->IsPhi());
609 DCHECK_EQ(instruction->GetId(), -1);
610 DCHECK_NE(cursor->GetId(), -1);
611 DCHECK_EQ(cursor->GetBlock(), this);
612 DCHECK(!instruction->IsControlFlow());
613 instruction->SetBlock(this);
614 instruction->SetId(GetGraph()->GetNextInstructionId());
615 UpdateInputsUsers(instruction);
616 instructions_.InsertInstructionBefore(instruction, cursor);
617}
618
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100619void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
620 DCHECK(!cursor->IsPhi());
621 DCHECK(!instruction->IsPhi());
622 DCHECK_EQ(instruction->GetId(), -1);
623 DCHECK_NE(cursor->GetId(), -1);
624 DCHECK_EQ(cursor->GetBlock(), this);
625 DCHECK(!instruction->IsControlFlow());
626 DCHECK(!cursor->IsControlFlow());
627 instruction->SetBlock(this);
628 instruction->SetId(GetGraph()->GetNextInstructionId());
629 UpdateInputsUsers(instruction);
630 instructions_.InsertInstructionAfter(instruction, cursor);
631}
632
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100633void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
634 DCHECK_EQ(phi->GetId(), -1);
635 DCHECK_NE(cursor->GetId(), -1);
636 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100637 phi->SetBlock(this);
638 phi->SetId(GetGraph()->GetNextInstructionId());
639 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100640 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100641}
642
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100643static void Remove(HInstructionList* instruction_list,
644 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000645 HInstruction* instruction,
646 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100647 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100648 instruction->SetBlock(nullptr);
649 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000650 if (ensure_safety) {
651 DCHECK(instruction->GetUses().IsEmpty());
652 DCHECK(instruction->GetEnvUses().IsEmpty());
653 RemoveAsUser(instruction);
654 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100655}
656
David Brazdil1abb4192015-02-17 18:33:36 +0000657void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100658 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000659 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100660}
661
David Brazdil1abb4192015-02-17 18:33:36 +0000662void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
663 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100664}
665
David Brazdilc7508e92015-04-27 13:28:57 +0100666void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
667 if (instruction->IsPhi()) {
668 RemovePhi(instruction->AsPhi(), ensure_safety);
669 } else {
670 RemoveInstruction(instruction, ensure_safety);
671 }
672}
673
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100674void HEnvironment::CopyFrom(const GrowableArray<HInstruction*>& locals) {
675 for (size_t i = 0; i < locals.Size(); i++) {
676 HInstruction* instruction = locals.Get(i);
677 SetRawEnvAt(i, instruction);
678 if (instruction != nullptr) {
679 instruction->AddEnvUseAt(this, i);
680 }
681 }
682}
683
David Brazdiled596192015-01-23 10:39:45 +0000684void HEnvironment::CopyFrom(HEnvironment* env) {
685 for (size_t i = 0; i < env->Size(); i++) {
686 HInstruction* instruction = env->GetInstructionAt(i);
687 SetRawEnvAt(i, instruction);
688 if (instruction != nullptr) {
689 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100690 }
David Brazdiled596192015-01-23 10:39:45 +0000691 }
692}
693
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700694void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
695 HBasicBlock* loop_header) {
696 DCHECK(loop_header->IsLoopHeader());
697 for (size_t i = 0; i < env->Size(); i++) {
698 HInstruction* instruction = env->GetInstructionAt(i);
699 SetRawEnvAt(i, instruction);
700 if (instruction == nullptr) {
701 continue;
702 }
703 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
704 // At the end of the loop pre-header, the corresponding value for instruction
705 // is the first input of the phi.
706 HInstruction* initial = instruction->AsPhi()->InputAt(0);
707 DCHECK(initial->GetBlock()->Dominates(loop_header));
708 SetRawEnvAt(i, initial);
709 initial->AddEnvUseAt(this, i);
710 } else {
711 instruction->AddEnvUseAt(this, i);
712 }
713 }
714}
715
David Brazdil1abb4192015-02-17 18:33:36 +0000716void HEnvironment::RemoveAsUserOfInput(size_t index) const {
717 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
718 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100719}
720
Calin Juravle77520bc2015-01-12 18:45:46 +0000721HInstruction* HInstruction::GetNextDisregardingMoves() const {
722 HInstruction* next = GetNext();
723 while (next != nullptr && next->IsParallelMove()) {
724 next = next->GetNext();
725 }
726 return next;
727}
728
729HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
730 HInstruction* previous = GetPrevious();
731 while (previous != nullptr && previous->IsParallelMove()) {
732 previous = previous->GetPrevious();
733 }
734 return previous;
735}
736
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100737void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000738 if (first_instruction_ == nullptr) {
739 DCHECK(last_instruction_ == nullptr);
740 first_instruction_ = last_instruction_ = instruction;
741 } else {
742 last_instruction_->next_ = instruction;
743 instruction->previous_ = last_instruction_;
744 last_instruction_ = instruction;
745 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000746}
747
David Brazdilc3d743f2015-04-22 13:40:50 +0100748void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
749 DCHECK(Contains(cursor));
750 if (cursor == first_instruction_) {
751 cursor->previous_ = instruction;
752 instruction->next_ = cursor;
753 first_instruction_ = instruction;
754 } else {
755 instruction->previous_ = cursor->previous_;
756 instruction->next_ = cursor;
757 cursor->previous_ = instruction;
758 instruction->previous_->next_ = instruction;
759 }
760}
761
762void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
763 DCHECK(Contains(cursor));
764 if (cursor == last_instruction_) {
765 cursor->next_ = instruction;
766 instruction->previous_ = cursor;
767 last_instruction_ = instruction;
768 } else {
769 instruction->next_ = cursor->next_;
770 instruction->previous_ = cursor;
771 cursor->next_ = instruction;
772 instruction->next_->previous_ = instruction;
773 }
774}
775
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100776void HInstructionList::RemoveInstruction(HInstruction* instruction) {
777 if (instruction->previous_ != nullptr) {
778 instruction->previous_->next_ = instruction->next_;
779 }
780 if (instruction->next_ != nullptr) {
781 instruction->next_->previous_ = instruction->previous_;
782 }
783 if (instruction == first_instruction_) {
784 first_instruction_ = instruction->next_;
785 }
786 if (instruction == last_instruction_) {
787 last_instruction_ = instruction->previous_;
788 }
789}
790
Roland Levillain6b469232014-09-25 10:10:38 +0100791bool HInstructionList::Contains(HInstruction* instruction) const {
792 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
793 if (it.Current() == instruction) {
794 return true;
795 }
796 }
797 return false;
798}
799
Roland Levillainccc07a92014-09-16 14:48:16 +0100800bool HInstructionList::FoundBefore(const HInstruction* instruction1,
801 const HInstruction* instruction2) const {
802 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
803 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
804 if (it.Current() == instruction1) {
805 return true;
806 }
807 if (it.Current() == instruction2) {
808 return false;
809 }
810 }
811 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
812 return true;
813}
814
Roland Levillain6c82d402014-10-13 16:10:27 +0100815bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
816 if (other_instruction == this) {
817 // An instruction does not strictly dominate itself.
818 return false;
819 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100820 HBasicBlock* block = GetBlock();
821 HBasicBlock* other_block = other_instruction->GetBlock();
822 if (block != other_block) {
823 return GetBlock()->Dominates(other_instruction->GetBlock());
824 } else {
825 // If both instructions are in the same block, ensure this
826 // instruction comes before `other_instruction`.
827 if (IsPhi()) {
828 if (!other_instruction->IsPhi()) {
829 // Phis appear before non phi-instructions so this instruction
830 // dominates `other_instruction`.
831 return true;
832 } else {
833 // There is no order among phis.
834 LOG(FATAL) << "There is no dominance between phis of a same block.";
835 return false;
836 }
837 } else {
838 // `this` is not a phi.
839 if (other_instruction->IsPhi()) {
840 // Phis appear before non phi-instructions so this instruction
841 // does not dominate `other_instruction`.
842 return false;
843 } else {
844 // Check whether this instruction comes before
845 // `other_instruction` in the instruction list.
846 return block->GetInstructions().FoundBefore(this, other_instruction);
847 }
848 }
849 }
850}
851
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100852void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100853 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000854 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
855 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100856 HInstruction* user = current->GetUser();
857 size_t input_index = current->GetIndex();
858 user->SetRawInputAt(input_index, other);
859 other->AddUseAt(user, input_index);
860 }
861
David Brazdiled596192015-01-23 10:39:45 +0000862 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
863 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100864 HEnvironment* user = current->GetUser();
865 size_t input_index = current->GetIndex();
866 user->SetRawEnvAt(input_index, other);
867 other->AddEnvUseAt(user, input_index);
868 }
869
David Brazdiled596192015-01-23 10:39:45 +0000870 uses_.Clear();
871 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100872}
873
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100874void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000875 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100876 SetRawInputAt(index, replacement);
877 replacement->AddUseAt(this, index);
878}
879
Nicolas Geoffray39468442014-09-02 15:17:15 +0100880size_t HInstruction::EnvironmentSize() const {
881 return HasEnvironment() ? environment_->Size() : 0;
882}
883
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100884void HPhi::AddInput(HInstruction* input) {
885 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000886 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100887 input->AddUseAt(this, inputs_.Size() - 1);
888}
889
David Brazdil2d7352b2015-04-20 14:52:42 +0100890void HPhi::RemoveInputAt(size_t index) {
891 RemoveAsUserOfInput(index);
892 inputs_.DeleteAt(index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100893 for (size_t i = index, e = InputCount(); i < e; ++i) {
894 InputRecordAt(i).GetUseNode()->SetIndex(i);
895 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100896}
897
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100898#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000899void H##name::Accept(HGraphVisitor* visitor) { \
900 visitor->Visit##name(this); \
901}
902
903FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
904
905#undef DEFINE_ACCEPT
906
907void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100908 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
909 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000910 HBasicBlock* block = blocks.Get(i);
911 if (block != nullptr) {
912 VisitBasicBlock(block);
913 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000914 }
915}
916
Roland Levillain633021e2014-10-01 14:12:25 +0100917void HGraphVisitor::VisitReversePostOrder() {
918 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
919 VisitBasicBlock(it.Current());
920 }
921}
922
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000923void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100924 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100925 it.Current()->Accept(this);
926 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100927 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000928 it.Current()->Accept(this);
929 }
930}
931
Mark Mendelle82549b2015-05-06 10:55:34 -0400932HConstant* HTypeConversion::TryStaticEvaluation() const {
933 HGraph* graph = GetBlock()->GetGraph();
934 if (GetInput()->IsIntConstant()) {
935 int32_t value = GetInput()->AsIntConstant()->GetValue();
936 switch (GetResultType()) {
937 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600938 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400939 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600940 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400941 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600942 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400943 default:
944 return nullptr;
945 }
946 } else if (GetInput()->IsLongConstant()) {
947 int64_t value = GetInput()->AsLongConstant()->GetValue();
948 switch (GetResultType()) {
949 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600950 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400951 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600952 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400953 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600954 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400955 default:
956 return nullptr;
957 }
958 } else if (GetInput()->IsFloatConstant()) {
959 float value = GetInput()->AsFloatConstant()->GetValue();
960 switch (GetResultType()) {
961 case Primitive::kPrimInt:
962 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600963 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400964 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600965 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400966 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600967 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
968 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400969 case Primitive::kPrimLong:
970 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600971 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400972 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600973 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400974 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600975 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
976 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400977 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600978 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400979 default:
980 return nullptr;
981 }
982 } else if (GetInput()->IsDoubleConstant()) {
983 double value = GetInput()->AsDoubleConstant()->GetValue();
984 switch (GetResultType()) {
985 case Primitive::kPrimInt:
986 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600987 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400988 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600989 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400990 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600991 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
992 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400993 case Primitive::kPrimLong:
994 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600995 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400996 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600997 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400998 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600999 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1000 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001001 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001002 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001003 default:
1004 return nullptr;
1005 }
1006 }
1007 return nullptr;
1008}
1009
Roland Levillain9240d6a2014-10-20 16:47:04 +01001010HConstant* HUnaryOperation::TryStaticEvaluation() const {
1011 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001012 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001013 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001014 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001015 }
1016 return nullptr;
1017}
1018
1019HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001020 if (GetLeft()->IsIntConstant()) {
1021 if (GetRight()->IsIntConstant()) {
1022 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1023 } else if (GetRight()->IsLongConstant()) {
1024 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1025 }
1026 } else if (GetLeft()->IsLongConstant()) {
1027 if (GetRight()->IsIntConstant()) {
1028 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1029 } else if (GetRight()->IsLongConstant()) {
1030 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001031 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001032 }
1033 return nullptr;
1034}
Dave Allison20dfc792014-06-16 20:44:29 -07001035
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001036HConstant* HBinaryOperation::GetConstantRight() const {
1037 if (GetRight()->IsConstant()) {
1038 return GetRight()->AsConstant();
1039 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1040 return GetLeft()->AsConstant();
1041 } else {
1042 return nullptr;
1043 }
1044}
1045
1046// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001047// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001048HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1049 HInstruction* most_constant_right = GetConstantRight();
1050 if (most_constant_right == nullptr) {
1051 return nullptr;
1052 } else if (most_constant_right == GetLeft()) {
1053 return GetRight();
1054 } else {
1055 return GetLeft();
1056 }
1057}
1058
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001059bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1060 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001061}
1062
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001063bool HInstruction::Equals(HInstruction* other) const {
1064 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001065 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001066 if (!InstructionDataEquals(other)) return false;
1067 if (GetType() != other->GetType()) return false;
1068 if (InputCount() != other->InputCount()) return false;
1069
1070 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1071 if (InputAt(i) != other->InputAt(i)) return false;
1072 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001073 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001074 return true;
1075}
1076
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001077std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1078#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1079 switch (rhs) {
1080 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1081 default:
1082 os << "Unknown instruction kind " << static_cast<int>(rhs);
1083 break;
1084 }
1085#undef DECLARE_CASE
1086 return os;
1087}
1088
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001089void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001090 next_->previous_ = previous_;
1091 if (previous_ != nullptr) {
1092 previous_->next_ = next_;
1093 }
1094 if (block_->instructions_.first_instruction_ == this) {
1095 block_->instructions_.first_instruction_ = next_;
1096 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001097 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001098
1099 previous_ = cursor->previous_;
1100 if (previous_ != nullptr) {
1101 previous_->next_ = this;
1102 }
1103 next_ = cursor;
1104 cursor->previous_ = this;
1105 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001106
1107 if (block_->instructions_.first_instruction_ == cursor) {
1108 block_->instructions_.first_instruction_ = this;
1109 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001110}
1111
David Brazdilfc6a86a2015-06-26 10:33:45 +00001112HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
1113 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented";
1114 DCHECK_EQ(cursor->GetBlock(), this);
1115
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001116 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1117 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001118 new_block->instructions_.first_instruction_ = cursor;
1119 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1120 instructions_.last_instruction_ = cursor->previous_;
1121 if (cursor->previous_ == nullptr) {
1122 instructions_.first_instruction_ = nullptr;
1123 } else {
1124 cursor->previous_->next_ = nullptr;
1125 cursor->previous_ = nullptr;
1126 }
1127
1128 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001129 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001130
Vladimir Marko60584552015-09-03 13:35:12 +00001131 for (HBasicBlock* successor : GetSuccessors()) {
1132 new_block->successors_.push_back(successor);
1133 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001134 }
Vladimir Marko60584552015-09-03 13:35:12 +00001135 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001136 AddSuccessor(new_block);
1137
David Brazdil56e1acc2015-06-30 15:41:36 +01001138 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001139 return new_block;
1140}
1141
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001142HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1143 DCHECK(!cursor->IsControlFlow());
1144 DCHECK_NE(instructions_.last_instruction_, cursor);
1145 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001146
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001147 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1148 new_block->instructions_.first_instruction_ = cursor->GetNext();
1149 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1150 cursor->next_->previous_ = nullptr;
1151 cursor->next_ = nullptr;
1152 instructions_.last_instruction_ = cursor;
1153
1154 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001155 for (HBasicBlock* successor : GetSuccessors()) {
1156 new_block->successors_.push_back(successor);
1157 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001158 }
Vladimir Marko60584552015-09-03 13:35:12 +00001159 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001160
Vladimir Marko60584552015-09-03 13:35:12 +00001161 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001162 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001163 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001164 }
Vladimir Marko60584552015-09-03 13:35:12 +00001165 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001166 return new_block;
1167}
1168
David Brazdilec16f792015-08-19 15:04:01 +01001169const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001170 if (EndsWithTryBoundary()) {
1171 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1172 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001173 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001174 return try_boundary;
1175 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001176 DCHECK(IsTryBlock());
1177 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001178 return nullptr;
1179 }
David Brazdilec16f792015-08-19 15:04:01 +01001180 } else if (IsTryBlock()) {
1181 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001182 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001183 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001184 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001185}
1186
1187static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1188 return block.GetPhis().IsEmpty()
1189 && !block.GetInstructions().IsEmpty()
1190 && block.GetFirstInstruction() == block.GetLastInstruction();
1191}
1192
David Brazdil46e2a392015-03-16 17:31:52 +00001193bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001194 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1195}
1196
1197bool HBasicBlock::IsSingleTryBoundary() const {
1198 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001199}
1200
David Brazdil8d5b8b22015-03-24 10:51:52 +00001201bool HBasicBlock::EndsWithControlFlowInstruction() const {
1202 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1203}
1204
David Brazdilb2bd1c52015-03-25 11:17:37 +00001205bool HBasicBlock::EndsWithIf() const {
1206 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1207}
1208
David Brazdilffee3d32015-07-06 11:48:53 +01001209bool HBasicBlock::EndsWithTryBoundary() const {
1210 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1211}
1212
David Brazdilb2bd1c52015-03-25 11:17:37 +00001213bool HBasicBlock::HasSinglePhi() const {
1214 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1215}
1216
David Brazdilffee3d32015-07-06 11:48:53 +01001217bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
Vladimir Marko60584552015-09-03 13:35:12 +00001218 if (GetBlock()->GetSuccessors().size() != other.GetBlock()->GetSuccessors().size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001219 return false;
1220 }
1221
David Brazdilb618ade2015-07-29 10:31:29 +01001222 // Exception handlers need to be stored in the same order.
1223 for (HExceptionHandlerIterator it1(*this), it2(other);
1224 !it1.Done();
1225 it1.Advance(), it2.Advance()) {
1226 DCHECK(!it2.Done());
1227 if (it1.Current() != it2.Current()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001228 return false;
1229 }
1230 }
1231 return true;
1232}
1233
David Brazdil2d7352b2015-04-20 14:52:42 +01001234size_t HInstructionList::CountSize() const {
1235 size_t size = 0;
1236 HInstruction* current = first_instruction_;
1237 for (; current != nullptr; current = current->GetNext()) {
1238 size++;
1239 }
1240 return size;
1241}
1242
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001243void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1244 for (HInstruction* current = first_instruction_;
1245 current != nullptr;
1246 current = current->GetNext()) {
1247 current->SetBlock(block);
1248 }
1249}
1250
1251void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1252 DCHECK(Contains(cursor));
1253 if (!instruction_list.IsEmpty()) {
1254 if (cursor == last_instruction_) {
1255 last_instruction_ = instruction_list.last_instruction_;
1256 } else {
1257 cursor->next_->previous_ = instruction_list.last_instruction_;
1258 }
1259 instruction_list.last_instruction_->next_ = cursor->next_;
1260 cursor->next_ = instruction_list.first_instruction_;
1261 instruction_list.first_instruction_->previous_ = cursor;
1262 }
1263}
1264
1265void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001266 if (IsEmpty()) {
1267 first_instruction_ = instruction_list.first_instruction_;
1268 last_instruction_ = instruction_list.last_instruction_;
1269 } else {
1270 AddAfter(last_instruction_, instruction_list);
1271 }
1272}
1273
David Brazdil2d7352b2015-04-20 14:52:42 +01001274void HBasicBlock::DisconnectAndDelete() {
1275 // Dominators must be removed after all the blocks they dominate. This way
1276 // a loop header is removed last, a requirement for correct loop information
1277 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001278 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001279
David Brazdil2d7352b2015-04-20 14:52:42 +01001280 // Remove the block from all loops it is included in.
1281 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1282 HLoopInformation* loop_info = it.Current();
1283 loop_info->Remove(this);
1284 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001285 // If this was the last back edge of the loop, we deliberately leave the
1286 // loop in an inconsistent state and will fail SSAChecker unless the
1287 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001288 loop_info->RemoveBackEdge(this);
1289 }
1290 }
1291
1292 // Disconnect the block from its predecessors and update their control-flow
1293 // instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001294 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001295 HInstruction* last_instruction = predecessor->GetLastInstruction();
1296 predecessor->RemoveInstruction(last_instruction);
1297 predecessor->RemoveSuccessor(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001298 if (predecessor->GetSuccessors().size() == 1u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001299 DCHECK(last_instruction->IsIf());
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001300 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001301 } else {
1302 // The predecessor has no remaining successors and therefore must be dead.
1303 // We deliberately leave it without a control-flow instruction so that the
1304 // SSAChecker fails unless it is not removed during the pass too.
Vladimir Marko60584552015-09-03 13:35:12 +00001305 DCHECK_EQ(predecessor->GetSuccessors().size(), 0u);
David Brazdil2d7352b2015-04-20 14:52:42 +01001306 }
David Brazdil46e2a392015-03-16 17:31:52 +00001307 }
Vladimir Marko60584552015-09-03 13:35:12 +00001308 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001309
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +01001310 // Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001311 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001312 // Delete this block from the list of predecessors.
1313 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001314 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001315
1316 // Check that `successor` has other predecessors, otherwise `this` is the
1317 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001318 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001319
David Brazdil2d7352b2015-04-20 14:52:42 +01001320 // Remove this block's entries in the successor's phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001321 if (successor->predecessors_.size() == 1u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001322 // The successor has just one predecessor left. Replace phis with the only
1323 // remaining input.
1324 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1325 HPhi* phi = phi_it.Current()->AsPhi();
1326 phi->ReplaceWith(phi->InputAt(1 - this_index));
1327 successor->RemovePhi(phi);
1328 }
1329 } else {
1330 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1331 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1332 }
1333 }
1334 }
Vladimir Marko60584552015-09-03 13:35:12 +00001335 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001336
1337 // Disconnect from the dominator.
1338 dominator_->RemoveDominatedBlock(this);
1339 SetDominator(nullptr);
1340
1341 // Delete from the graph. The function safely deletes remaining instructions
1342 // and updates the reverse post order.
1343 graph_->DeleteDeadBlock(this);
1344 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001345}
1346
1347void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001348 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001349 DCHECK(ContainsElement(dominated_blocks_, other));
1350 DCHECK_EQ(GetSingleSuccessor(), other);
1351 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001352 DCHECK(other->GetPhis().IsEmpty());
1353
David Brazdil2d7352b2015-04-20 14:52:42 +01001354 // Move instructions from `other` to `this`.
1355 DCHECK(EndsWithControlFlowInstruction());
1356 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001357 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001358 other->instructions_.SetBlockOfInstructions(this);
1359 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001360
David Brazdil2d7352b2015-04-20 14:52:42 +01001361 // Remove `other` from the loops it is included in.
1362 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1363 HLoopInformation* loop_info = it.Current();
1364 loop_info->Remove(other);
1365 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001366 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001367 }
1368 }
1369
1370 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001371 successors_.clear();
1372 while (!other->successors_.empty()) {
1373 HBasicBlock* successor = other->GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001374 successor->ReplacePredecessor(other, this);
1375 }
1376
David Brazdil2d7352b2015-04-20 14:52:42 +01001377 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001378 RemoveDominatedBlock(other);
1379 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1380 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001381 dominated->SetDominator(this);
1382 }
Vladimir Marko60584552015-09-03 13:35:12 +00001383 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001384 other->dominator_ = nullptr;
1385
1386 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001387 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001388
1389 // Delete `other` from the graph. The function updates reverse post order.
1390 graph_->DeleteDeadBlock(other);
1391 other->SetGraph(nullptr);
1392}
1393
1394void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1395 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001396 DCHECK(GetDominatedBlocks().empty());
1397 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001398 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001399 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001400 DCHECK(other->GetPhis().IsEmpty());
1401 DCHECK(!other->IsInLoop());
1402
1403 // Move instructions from `other` to `this`.
1404 instructions_.Add(other->GetInstructions());
1405 other->instructions_.SetBlockOfInstructions(this);
1406
1407 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001408 successors_.clear();
1409 while (!other->successors_.empty()) {
1410 HBasicBlock* successor = other->GetSuccessor(0);
David Brazdil2d7352b2015-04-20 14:52:42 +01001411 successor->ReplacePredecessor(other, this);
1412 }
1413
1414 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001415 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1416 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001417 dominated->SetDominator(this);
1418 }
Vladimir Marko60584552015-09-03 13:35:12 +00001419 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001420 other->dominator_ = nullptr;
1421 other->graph_ = nullptr;
1422}
1423
1424void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001425 while (!GetPredecessors().empty()) {
1426 HBasicBlock* predecessor = GetPredecessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001427 predecessor->ReplaceSuccessor(this, other);
1428 }
Vladimir Marko60584552015-09-03 13:35:12 +00001429 while (!GetSuccessors().empty()) {
1430 HBasicBlock* successor = GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001431 successor->ReplacePredecessor(this, other);
1432 }
Vladimir Marko60584552015-09-03 13:35:12 +00001433 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1434 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001435 }
1436 GetDominator()->ReplaceDominatedBlock(this, other);
1437 other->SetDominator(GetDominator());
1438 dominator_ = nullptr;
1439 graph_ = nullptr;
1440}
1441
1442// Create space in `blocks` for adding `number_of_new_blocks` entries
1443// starting at location `at`. Blocks after `at` are moved accordingly.
1444static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
1445 size_t number_of_new_blocks,
1446 size_t at) {
1447 size_t old_size = blocks->Size();
1448 size_t new_size = old_size + number_of_new_blocks;
1449 blocks->SetSize(new_size);
1450 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
1451 blocks->Put(j, blocks->Get(i));
1452 }
1453}
1454
David Brazdil2d7352b2015-04-20 14:52:42 +01001455void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1456 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001457 DCHECK(block->GetSuccessors().empty());
1458 DCHECK(block->GetPredecessors().empty());
1459 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001460 DCHECK(block->GetDominator() == nullptr);
1461
1462 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1463 block->RemoveInstruction(it.Current());
1464 }
1465 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1466 block->RemovePhi(it.Current()->AsPhi());
1467 }
1468
David Brazdilc7af85d2015-05-26 12:05:55 +01001469 if (block->IsExitBlock()) {
1470 exit_block_ = nullptr;
1471 }
1472
David Brazdil2d7352b2015-04-20 14:52:42 +01001473 reverse_post_order_.Delete(block);
1474 blocks_.Put(block->GetBlockId(), nullptr);
1475}
1476
Calin Juravle2e768302015-07-28 14:41:11 +00001477HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001478 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001479 // Update the environments in this graph to have the invoke's environment
1480 // as parent.
1481 {
1482 HReversePostOrderIterator it(*this);
1483 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1484 for (; !it.Done(); it.Advance()) {
1485 HBasicBlock* block = it.Current();
1486 for (HInstructionIterator instr_it(block->GetInstructions());
1487 !instr_it.Done();
1488 instr_it.Advance()) {
1489 HInstruction* current = instr_it.Current();
1490 if (current->NeedsEnvironment()) {
1491 current->GetEnvironment()->SetAndCopyParentChain(
1492 outer_graph->GetArena(), invoke->GetEnvironment());
1493 }
1494 }
1495 }
1496 }
1497 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1498 if (HasBoundsChecks()) {
1499 outer_graph->SetHasBoundsChecks(true);
1500 }
1501
Calin Juravle2e768302015-07-28 14:41:11 +00001502 HInstruction* return_value = nullptr;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001503 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001504 // Simple case of an entry block, a body block, and an exit block.
1505 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001506 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001507 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
1508 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001509 DCHECK(!body->IsExitBlock());
1510 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001511
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001512 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1513 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001514
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001515 // Replace the invoke with the return value of the inlined graph.
1516 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001517 return_value = last->InputAt(0);
1518 invoke->ReplaceWith(return_value);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001519 } else {
1520 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001521 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001522
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001523 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001524 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001525 // Need to inline multiple blocks. We split `invoke`'s block
1526 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001527 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001528 // with the second half.
1529 ArenaAllocator* allocator = outer_graph->GetArena();
1530 HBasicBlock* at = invoke->GetBlock();
1531 HBasicBlock* to = at->SplitAfter(invoke);
1532
Vladimir Marko60584552015-09-03 13:35:12 +00001533 HBasicBlock* first = entry_block_->GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001534 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001535 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001536 exit_block_->ReplaceWith(to);
1537
1538 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001539 // to not `HReturn` but `HGoto` instead.
Vladimir Marko60584552015-09-03 13:35:12 +00001540 bool returns_void = to->GetPredecessor(0)->GetLastInstruction()->IsReturnVoid();
1541 if (to->GetPredecessors().size() == 1) {
1542 HBasicBlock* predecessor = to->GetPredecessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001543 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001544 if (!returns_void) {
1545 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001546 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001547 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001548 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001549 } else {
1550 if (!returns_void) {
1551 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001552 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001553 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001554 to->AddPhi(return_value->AsPhi());
1555 }
Vladimir Marko60584552015-09-03 13:35:12 +00001556 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001557 HInstruction* last = predecessor->GetLastInstruction();
1558 if (!returns_void) {
1559 return_value->AsPhi()->AddInput(last->InputAt(0));
1560 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001561 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001562 predecessor->RemoveInstruction(last);
1563 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001564 }
1565
1566 if (return_value != nullptr) {
1567 invoke->ReplaceWith(return_value);
1568 }
1569
1570 // Update the meta information surrounding blocks:
1571 // (1) the graph they are now in,
1572 // (2) the reverse post order of that graph,
1573 // (3) the potential loop information they are now in.
1574
1575 // We don't add the entry block, the exit block, and the first block, which
1576 // has been merged with `at`.
1577 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1578
1579 // We add the `to` block.
1580 static constexpr int kNumberOfNewBlocksInCaller = 1;
1581 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1582 + kNumberOfNewBlocksInCaller;
1583
1584 // Find the location of `at` in the outer graph's reverse post order. The new
1585 // blocks will be added after it.
1586 size_t index_of_at = 0;
1587 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1588 index_of_at++;
1589 }
1590 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1591
1592 // Do a reverse post order of the blocks in the callee and do (1), (2),
1593 // and (3) to the blocks that apply.
1594 HLoopInformation* info = at->GetLoopInformation();
1595 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1596 HBasicBlock* current = it.Current();
1597 if (current != exit_block_ && current != entry_block_ && current != first) {
1598 DCHECK(!current->IsInLoop());
1599 DCHECK(current->GetGraph() == this);
1600 current->SetGraph(outer_graph);
1601 outer_graph->AddBlock(current);
1602 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1603 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001604 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001605 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1606 loop_it.Current()->Add(current);
1607 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001608 }
1609 }
1610 }
1611
1612 // Do (1), (2), and (3) to `to`.
1613 to->SetGraph(outer_graph);
1614 outer_graph->AddBlock(to);
1615 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1616 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001617 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001618 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1619 loop_it.Current()->Add(to);
1620 }
David Brazdil46e2a392015-03-16 17:31:52 +00001621 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001622 // Only `to` can become a back edge, as the inlined blocks
1623 // are predecessors of `to`.
1624 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001625 }
1626 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001627 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001628
David Brazdil05144f42015-04-16 15:18:00 +01001629 // Update the next instruction id of the outer graph, so that instructions
1630 // added later get bigger ids than those in the inner graph.
1631 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1632
1633 // Walk over the entry block and:
1634 // - Move constants from the entry block to the outer_graph's entry block,
1635 // - Replace HParameterValue instructions with their real value.
1636 // - Remove suspend checks, that hold an environment.
1637 // We must do this after the other blocks have been inlined, otherwise ids of
1638 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001639 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001640 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1641 HInstruction* current = it.Current();
1642 if (current->IsNullConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001643 current->ReplaceWith(outer_graph->GetNullConstant(current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001644 } else if (current->IsIntConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001645 current->ReplaceWith(outer_graph->GetIntConstant(
1646 current->AsIntConstant()->GetValue(), current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001647 } else if (current->IsLongConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001648 current->ReplaceWith(outer_graph->GetLongConstant(
1649 current->AsLongConstant()->GetValue(), current->GetDexPc()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001650 } else if (current->IsFloatConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001651 current->ReplaceWith(outer_graph->GetFloatConstant(
1652 current->AsFloatConstant()->GetValue(), current->GetDexPc()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001653 } else if (current->IsDoubleConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001654 current->ReplaceWith(outer_graph->GetDoubleConstant(
1655 current->AsDoubleConstant()->GetValue(), current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001656 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001657 if (kIsDebugBuild
1658 && invoke->IsInvokeStaticOrDirect()
1659 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1660 // Ensure we do not use the last input of `invoke`, as it
1661 // contains a clinit check which is not an actual argument.
1662 size_t last_input_index = invoke->InputCount() - 1;
1663 DCHECK(parameter_index != last_input_index);
1664 }
David Brazdil05144f42015-04-16 15:18:00 +01001665 current->ReplaceWith(invoke->InputAt(parameter_index++));
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001666 } else if (current->IsCurrentMethod()) {
1667 current->ReplaceWith(outer_graph->GetCurrentMethod());
David Brazdil05144f42015-04-16 15:18:00 +01001668 } else {
1669 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1670 entry_block_->RemoveInstruction(current);
1671 }
1672 }
1673
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001674 // Finally remove the invoke from the caller.
1675 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00001676
1677 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001678}
1679
Mingyao Yang3584bce2015-05-19 16:01:59 -07001680/*
1681 * Loop will be transformed to:
1682 * old_pre_header
1683 * |
1684 * if_block
1685 * / \
1686 * dummy_block deopt_block
1687 * \ /
1688 * new_pre_header
1689 * |
1690 * header
1691 */
1692void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1693 DCHECK(header->IsLoopHeader());
1694 HBasicBlock* pre_header = header->GetDominator();
1695
1696 // Need this to avoid critical edge.
1697 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1698 // Need this to avoid critical edge.
1699 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1700 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1701 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1702 AddBlock(if_block);
1703 AddBlock(dummy_block);
1704 AddBlock(deopt_block);
1705 AddBlock(new_pre_header);
1706
1707 header->ReplacePredecessor(pre_header, new_pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001708 pre_header->successors_.clear();
1709 pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07001710
1711 pre_header->AddSuccessor(if_block);
1712 if_block->AddSuccessor(dummy_block); // True successor
1713 if_block->AddSuccessor(deopt_block); // False successor
1714 dummy_block->AddSuccessor(new_pre_header);
1715 deopt_block->AddSuccessor(new_pre_header);
1716
Vladimir Marko60584552015-09-03 13:35:12 +00001717 pre_header->dominated_blocks_.push_back(if_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001718 if_block->SetDominator(pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001719 if_block->dominated_blocks_.push_back(dummy_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001720 dummy_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001721 if_block->dominated_blocks_.push_back(deopt_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001722 deopt_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001723 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001724 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001725 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001726 header->SetDominator(new_pre_header);
1727
1728 size_t index_of_header = 0;
1729 while (reverse_post_order_.Get(index_of_header) != header) {
1730 index_of_header++;
1731 }
1732 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
1733 reverse_post_order_.Put(index_of_header++, if_block);
1734 reverse_post_order_.Put(index_of_header++, dummy_block);
1735 reverse_post_order_.Put(index_of_header++, deopt_block);
1736 reverse_post_order_.Put(index_of_header++, new_pre_header);
1737
1738 HLoopInformation* info = pre_header->GetLoopInformation();
1739 if (info != nullptr) {
1740 if_block->SetLoopInformation(info);
1741 dummy_block->SetLoopInformation(info);
1742 deopt_block->SetLoopInformation(info);
1743 new_pre_header->SetLoopInformation(info);
1744 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1745 !loop_it.Done();
1746 loop_it.Advance()) {
1747 loop_it.Current()->Add(if_block);
1748 loop_it.Current()->Add(dummy_block);
1749 loop_it.Current()->Add(deopt_block);
1750 loop_it.Current()->Add(new_pre_header);
1751 }
1752 }
1753}
1754
Calin Juravle2e768302015-07-28 14:41:11 +00001755void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
1756 if (kIsDebugBuild) {
1757 DCHECK_EQ(GetType(), Primitive::kPrimNot);
1758 ScopedObjectAccess soa(Thread::Current());
1759 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
1760 if (IsBoundType()) {
1761 // Having the test here spares us from making the method virtual just for
1762 // the sake of a DCHECK.
1763 ReferenceTypeInfo upper_bound_rti = AsBoundType()->GetUpperBound();
1764 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
1765 << " upper_bound_rti: " << upper_bound_rti
1766 << " rti: " << rti;
David Brazdilbaf89b82015-09-15 11:36:54 +01001767 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00001768 }
1769 }
1770 reference_type_info_ = rti;
1771}
1772
1773ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
1774
1775ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
1776 : type_handle_(type_handle), is_exact_(is_exact) {
1777 if (kIsDebugBuild) {
1778 ScopedObjectAccess soa(Thread::Current());
1779 DCHECK(IsValidHandle(type_handle));
1780 }
1781}
1782
Calin Juravleacf735c2015-02-12 15:25:22 +00001783std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1784 ScopedObjectAccess soa(Thread::Current());
1785 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00001786 << " is_valid=" << rhs.IsValid()
1787 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00001788 << " is_exact=" << rhs.IsExact()
1789 << " ]";
1790 return os;
1791}
1792
Mark Mendellc4701932015-04-10 13:18:51 -04001793bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
1794 // For now, assume that instructions in different blocks may use the
1795 // environment.
1796 // TODO: Use the control flow to decide if this is true.
1797 if (GetBlock() != other->GetBlock()) {
1798 return true;
1799 }
1800
1801 // We know that we are in the same block. Walk from 'this' to 'other',
1802 // checking to see if there is any instruction with an environment.
1803 HInstruction* current = this;
1804 for (; current != other && current != nullptr; current = current->GetNext()) {
1805 // This is a conservative check, as the instruction result may not be in
1806 // the referenced environment.
1807 if (current->HasEnvironment()) {
1808 return true;
1809 }
1810 }
1811
1812 // We should have been called with 'this' before 'other' in the block.
1813 // Just confirm this.
1814 DCHECK(current != nullptr);
1815 return false;
1816}
1817
1818void HInstruction::RemoveEnvironmentUsers() {
1819 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
1820 HUseListNode<HEnvironment*>* user_node = use_it.Current();
1821 HEnvironment* user = user_node->GetUser();
1822 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
1823 }
1824 env_uses_.Clear();
1825}
1826
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001827} // namespace art