blob: 46ef04a868b8eb8ebdd9f9714a4a356df6f68196 [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"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000023#include "utils/growable_array.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000024#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000025
26namespace art {
27
28void HGraph::AddBlock(HBasicBlock* block) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000029 block->SetBlockId(blocks_.Size());
Nicolas Geoffray818f2102014-02-18 16:43:35 +000030 blocks_.Add(block);
31}
32
Nicolas Geoffray804d0932014-05-02 08:46:00 +010033void HGraph::FindBackEdges(ArenaBitVector* visited) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000034 ArenaBitVector visiting(arena_, blocks_.Size(), false);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000035 VisitBlockForBackEdges(entry_block_, visited, &visiting);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000036}
37
Roland Levillainfc600dc2014-12-02 17:16:31 +000038static void RemoveAsUser(HInstruction* instruction) {
39 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000040 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000041 }
42
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010043 for (HEnvironment* environment = instruction->GetEnvironment();
44 environment != nullptr;
45 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000046 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000047 if (environment->GetInstructionAt(i) != nullptr) {
48 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000049 }
50 }
51 }
52}
53
54void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
55 for (size_t i = 0; i < blocks_.Size(); ++i) {
56 if (!visited.IsBitSet(i)) {
57 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010058 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000059 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
60 RemoveAsUser(it.Current());
61 }
62 }
63 }
64}
65
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010066void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010067 for (size_t i = 0; i < blocks_.Size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000068 if (!visited.IsBitSet(i)) {
David Brazdil1abb4192015-02-17 18:33:36 +000069 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010070 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +000071 for (HBasicBlock* successor : block->GetSuccessors()) {
72 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +000073 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010074 // Remove the block from the list of blocks, so that further analyses
75 // never see it.
76 blocks_.Put(i, nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000077 }
78 }
79}
80
81void HGraph::VisitBlockForBackEdges(HBasicBlock* block,
82 ArenaBitVector* visited,
Nicolas Geoffray804d0932014-05-02 08:46:00 +010083 ArenaBitVector* visiting) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000084 int id = block->GetBlockId();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000085 if (visited->IsBitSet(id)) return;
86
87 visited->SetBit(id);
88 visiting->SetBit(id);
Vladimir Marko60584552015-09-03 13:35:12 +000089 for (HBasicBlock* successor : block->GetSuccessors()) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000090 if (visiting->IsBitSet(successor->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000091 successor->AddBackEdge(block);
92 } else {
93 VisitBlockForBackEdges(successor, visited, visiting);
94 }
95 }
96 visiting->ClearBit(id);
97}
98
99void HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100100 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
101 // edges. This invariant simplifies building SSA form because Phis cannot
102 // collect both normal- and exceptional-flow values at the same time.
103 SimplifyCatchBlocks();
104
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000105 ArenaBitVector visited(arena_, blocks_.Size(), false);
106
David Brazdilffee3d32015-07-06 11:48:53 +0100107 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000108 FindBackEdges(&visited);
109
David Brazdilffee3d32015-07-06 11:48:53 +0100110 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000111 // the initial DFS as users from other instructions, so that
112 // users can be safely removed before uses later.
113 RemoveInstructionsAsUsersFromDeadBlocks(visited);
114
David Brazdilffee3d32015-07-06 11:48:53 +0100115 // (4) Remove blocks not visited during the initial DFS.
Roland Levillainfc600dc2014-12-02 17:16:31 +0000116 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000117 // predecessors list of live blocks.
118 RemoveDeadBlocks(visited);
119
David Brazdilffee3d32015-07-06 11:48:53 +0100120 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100121 // dominators and the reverse post order.
122 SimplifyCFG();
123
David Brazdilffee3d32015-07-06 11:48:53 +0100124 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100125 ComputeDominanceInformation();
126}
127
128void HGraph::ClearDominanceInformation() {
129 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
130 it.Current()->ClearDominanceInformation();
131 }
132 reverse_post_order_.Reset();
133}
134
135void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000136 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100137 dominator_ = nullptr;
138}
139
140void HGraph::ComputeDominanceInformation() {
141 DCHECK(reverse_post_order_.IsEmpty());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000142 GrowableArray<size_t> visits(arena_, blocks_.Size());
143 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100144 reverse_post_order_.Add(entry_block_);
Vladimir Marko60584552015-09-03 13:35:12 +0000145 for (HBasicBlock* successor : entry_block_->GetSuccessors()) {
146 VisitBlockForDominatorTree(successor, entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000147 }
148}
149
150HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
151 ArenaBitVector visited(arena_, blocks_.Size(), false);
152 // Walk the dominator tree of the first block and mark the visited blocks.
153 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000154 visited.SetBit(first->GetBlockId());
155 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000156 }
157 // Walk the dominator tree of the second block until a marked block is found.
158 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000159 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000160 return second;
161 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000162 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000163 }
164 LOG(ERROR) << "Could not find common dominator";
165 return nullptr;
166}
167
168void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
169 HBasicBlock* predecessor,
170 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000171 if (block->GetDominator() == nullptr) {
172 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000173 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000174 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000175 }
176
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000177 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000178 // Once all the forward edges have been visited, we know the immediate
179 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000180 if (visits->Get(block->GetBlockId()) ==
Vladimir Marko60584552015-09-03 13:35:12 +0000181 block->GetPredecessors().size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100182 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100183 reverse_post_order_.Add(block);
Vladimir Marko60584552015-09-03 13:35:12 +0000184 for (HBasicBlock* successor : block->GetSuccessors()) {
185 VisitBlockForDominatorTree(successor, block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000186 }
187 }
188}
189
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000190void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100191 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100192 SsaBuilder ssa_builder(this);
193 ssa_builder.BuildSsa();
194}
195
David Brazdilfc6a86a2015-06-26 10:33:45 +0000196HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000197 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
198 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000199 // Use `InsertBetween` to ensure the predecessor index and successor index of
200 // `block` and `successor` are preserved.
201 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000202 return new_block;
203}
204
205void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
206 // Insert a new node between `block` and `successor` to split the
207 // critical edge.
208 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600209 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100210 if (successor->IsLoopHeader()) {
211 // If we split at a back edge boundary, make the new block the back edge.
212 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000213 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100214 info->RemoveBackEdge(block);
215 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100216 }
217 }
218}
219
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100220void HGraph::SimplifyLoop(HBasicBlock* header) {
221 HLoopInformation* info = header->GetLoopInformation();
222
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100223 // Make sure the loop has only one pre header. This simplifies SSA building by having
224 // to just look at the pre header to know which locals are initialized at entry of the
225 // loop.
Vladimir Marko60584552015-09-03 13:35:12 +0000226 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100227 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100228 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100229 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600230 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100231
Vladimir Marko60584552015-09-03 13:35:12 +0000232 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
233 HBasicBlock* predecessor = header->GetPredecessor(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100234 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100235 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100236 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100237 }
238 }
239 pre_header->AddSuccessor(header);
240 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100241
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100242 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Marko60584552015-09-03 13:35:12 +0000243 if (info->IsBackEdge(*header->GetPredecessor(0))) {
244 HBasicBlock* to_swap = header->GetPredecessor(0);
245 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
246 HBasicBlock* predecessor = header->GetPredecessor(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100247 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000248 header->predecessors_[pred] = to_swap;
249 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100250 break;
251 }
252 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100253 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100254
255 // Place the suspend check at the beginning of the header, so that live registers
256 // will be known when allocating registers. Note that code generation can still
257 // generate the suspend check at the back edge, but needs to be careful with
258 // loop phi spill slots (which are not written to at back edge).
259 HInstruction* first_instruction = header->GetFirstInstruction();
260 if (!first_instruction->IsSuspendCheck()) {
261 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
262 header->InsertInstructionBefore(check, first_instruction);
263 first_instruction = check;
264 }
265 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100266}
267
David Brazdilffee3d32015-07-06 11:48:53 +0100268static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Marko60584552015-09-03 13:35:12 +0000269 HBasicBlock* predecessor = block.GetPredecessor(pred_idx);
David Brazdilffee3d32015-07-06 11:48:53 +0100270 if (!predecessor->EndsWithTryBoundary()) {
271 // Only edges from HTryBoundary can be exceptional.
272 return false;
273 }
274 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
275 if (try_boundary->GetNormalFlowSuccessor() == &block) {
276 // This block is the normal-flow successor of `try_boundary`, but it could
277 // also be one of its exception handlers if catch blocks have not been
278 // simplified yet. Predecessors are unordered, so we will consider the first
279 // occurrence to be the normal edge and a possible second occurrence to be
280 // the exceptional edge.
281 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
282 } else {
283 // This is not the normal-flow successor of `try_boundary`, hence it must be
284 // one of its exception handlers.
285 DCHECK(try_boundary->HasExceptionHandler(block));
286 return true;
287 }
288}
289
290void HGraph::SimplifyCatchBlocks() {
291 for (size_t i = 0; i < blocks_.Size(); ++i) {
292 HBasicBlock* catch_block = blocks_.Get(i);
293 if (!catch_block->IsCatchBlock()) {
294 continue;
295 }
296
297 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000298 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100299 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
300 exceptional_predecessors_only = false;
301 break;
302 }
303 }
304
305 if (!exceptional_predecessors_only) {
306 // Catch block has normal-flow predecessors and needs to be simplified.
307 // Splitting the block before its first instruction moves all its
308 // instructions into `normal_block` and links the two blocks with a Goto.
309 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
310 // leaving `catch_block` with the exceptional edges only.
311 // Note that catch blocks with normal-flow predecessors cannot begin with
312 // a MOVE_EXCEPTION instruction, as guaranteed by the verifier.
313 DCHECK(!catch_block->GetFirstInstruction()->IsLoadException());
314 HBasicBlock* normal_block = catch_block->SplitBefore(catch_block->GetFirstInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +0000315 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100316 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000317 catch_block->GetPredecessor(j)->ReplaceSuccessor(catch_block, normal_block);
David Brazdilffee3d32015-07-06 11:48:53 +0100318 --j;
319 }
320 }
321 }
322 }
323}
324
325void HGraph::ComputeTryBlockInformation() {
326 // Iterate in reverse post order to propagate try membership information from
327 // predecessors to their successors.
328 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
329 HBasicBlock* block = it.Current();
330 if (block->IsEntryBlock() || block->IsCatchBlock()) {
331 // Catch blocks after simplification have only exceptional predecessors
332 // and hence are never in tries.
333 continue;
334 }
335
336 // Infer try membership from the first predecessor. Having simplified loops,
337 // the first predecessor can never be a back edge and therefore it must have
338 // been visited already and had its try membership set.
Vladimir Marko60584552015-09-03 13:35:12 +0000339 HBasicBlock* first_predecessor = block->GetPredecessor(0);
David Brazdilffee3d32015-07-06 11:48:53 +0100340 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100341 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
342 if (try_entry != nullptr) {
343 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
344 }
David Brazdilffee3d32015-07-06 11:48:53 +0100345 }
346}
347
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100348void HGraph::SimplifyCFG() {
349 // Simplify the CFG for future analysis, and code generation:
350 // (1): Split critical edges.
351 // (2): Simplify loops by having only one back edge, and one preheader.
352 for (size_t i = 0; i < blocks_.Size(); ++i) {
353 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100354 if (block == nullptr) continue;
David Brazdilffee3d32015-07-06 11:48:53 +0100355 if (block->NumberOfNormalSuccessors() > 1) {
Vladimir Marko60584552015-09-03 13:35:12 +0000356 for (size_t j = 0; j < block->GetSuccessors().size(); ++j) {
357 HBasicBlock* successor = block->GetSuccessor(j);
David Brazdilffee3d32015-07-06 11:48:53 +0100358 DCHECK(!successor->IsCatchBlock());
Vladimir Marko60584552015-09-03 13:35:12 +0000359 if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100360 SplitCriticalEdge(block, successor);
361 --j;
362 }
363 }
364 }
365 if (block->IsLoopHeader()) {
366 SimplifyLoop(block);
367 }
368 }
369}
370
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000371bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100372 // Order does not matter.
373 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
374 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100375 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100376 if (block->IsCatchBlock()) {
377 // TODO: Dealing with exceptional back edges could be tricky because
378 // they only approximate the real control flow. Bail out for now.
379 return false;
380 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100381 HLoopInformation* info = block->GetLoopInformation();
382 if (!info->Populate()) {
383 // Abort if the loop is non natural. We currently bailout in such cases.
384 return false;
385 }
386 }
387 }
388 return true;
389}
390
David Brazdil8d5b8b22015-03-24 10:51:52 +0000391void HGraph::InsertConstant(HConstant* constant) {
392 // New constants are inserted before the final control-flow instruction
393 // of the graph, or at its end if called from the graph builder.
394 if (entry_block_->EndsWithControlFlowInstruction()) {
395 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000396 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000397 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000398 }
399}
400
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600401HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100402 // For simplicity, don't bother reviving the cached null constant if it is
403 // not null and not in a block. Otherwise, we need to clear the instruction
404 // id and/or any invariants the graph is assuming when adding new instructions.
405 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600406 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000407 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000408 }
409 return cached_null_constant_;
410}
411
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100412HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100413 // For simplicity, don't bother reviving the cached current method if it is
414 // not null and not in a block. Otherwise, we need to clear the instruction
415 // id and/or any invariants the graph is assuming when adding new instructions.
416 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700417 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600418 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
419 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100420 if (entry_block_->GetFirstInstruction() == nullptr) {
421 entry_block_->AddInstruction(cached_current_method_);
422 } else {
423 entry_block_->InsertInstructionBefore(
424 cached_current_method_, entry_block_->GetFirstInstruction());
425 }
426 }
427 return cached_current_method_;
428}
429
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600430HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000431 switch (type) {
432 case Primitive::Type::kPrimBoolean:
433 DCHECK(IsUint<1>(value));
434 FALLTHROUGH_INTENDED;
435 case Primitive::Type::kPrimByte:
436 case Primitive::Type::kPrimChar:
437 case Primitive::Type::kPrimShort:
438 case Primitive::Type::kPrimInt:
439 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600440 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000441
442 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600443 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000444
445 default:
446 LOG(FATAL) << "Unsupported constant type";
447 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000448 }
David Brazdil46e2a392015-03-16 17:31:52 +0000449}
450
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000451void HGraph::CacheFloatConstant(HFloatConstant* constant) {
452 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
453 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
454 cached_float_constants_.Overwrite(value, constant);
455}
456
457void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
458 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
459 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
460 cached_double_constants_.Overwrite(value, constant);
461}
462
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000463void HLoopInformation::Add(HBasicBlock* block) {
464 blocks_.SetBit(block->GetBlockId());
465}
466
David Brazdil46e2a392015-03-16 17:31:52 +0000467void HLoopInformation::Remove(HBasicBlock* block) {
468 blocks_.ClearBit(block->GetBlockId());
469}
470
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100471void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
472 if (blocks_.IsBitSet(block->GetBlockId())) {
473 return;
474 }
475
476 blocks_.SetBit(block->GetBlockId());
477 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000478 for (HBasicBlock* predecessor : block->GetPredecessors()) {
479 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100480 }
481}
482
483bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100484 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100485 for (size_t i = 0, e = GetBackEdges().Size(); i < e; ++i) {
486 HBasicBlock* back_edge = GetBackEdges().Get(i);
487 DCHECK(back_edge->GetDominator() != nullptr);
488 if (!header_->Dominates(back_edge)) {
489 // This loop is not natural. Do not bother going further.
490 return false;
491 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100492
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100493 // Populate this loop: starting with the back edge, recursively add predecessors
494 // that are not already part of that loop. Set the header as part of the loop
495 // to end the recursion.
496 // This is a recursive implementation of the algorithm described in
497 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
498 blocks_.SetBit(header_->GetBlockId());
499 PopulateRecursive(back_edge);
500 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100501 return true;
502}
503
David Brazdila4b8c212015-05-07 09:59:30 +0100504void HLoopInformation::Update() {
505 HGraph* graph = header_->GetGraph();
506 for (uint32_t id : blocks_.Indexes()) {
507 HBasicBlock* block = graph->GetBlocks().Get(id);
508 // Reset loop information of non-header blocks inside the loop, except
509 // members of inner nested loops because those should already have been
510 // updated by their own LoopInformation.
511 if (block->GetLoopInformation() == this && block != header_) {
512 block->SetLoopInformation(nullptr);
513 }
514 }
515 blocks_.ClearAllBits();
516
517 if (back_edges_.IsEmpty()) {
518 // The loop has been dismantled, delete its suspend check and remove info
519 // from the header.
520 DCHECK(HasSuspendCheck());
521 header_->RemoveInstruction(suspend_check_);
522 header_->SetLoopInformation(nullptr);
523 header_ = nullptr;
524 suspend_check_ = nullptr;
525 } else {
526 if (kIsDebugBuild) {
527 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
528 DCHECK(header_->Dominates(back_edges_.Get(i)));
529 }
530 }
531 // This loop still has reachable back edges. Repopulate the list of blocks.
532 bool populate_successful = Populate();
533 DCHECK(populate_successful);
534 }
535}
536
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100537HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100538 return header_->GetDominator();
539}
540
541bool HLoopInformation::Contains(const HBasicBlock& block) const {
542 return blocks_.IsBitSet(block.GetBlockId());
543}
544
545bool HLoopInformation::IsIn(const HLoopInformation& other) const {
546 return other.blocks_.IsBitSet(header_->GetBlockId());
547}
548
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100549size_t HLoopInformation::GetLifetimeEnd() const {
550 size_t last_position = 0;
551 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
552 last_position = std::max(back_edges_.Get(i)->GetLifetimeEnd(), last_position);
553 }
554 return last_position;
555}
556
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100557bool HBasicBlock::Dominates(HBasicBlock* other) const {
558 // Walk up the dominator tree from `other`, to find out if `this`
559 // is an ancestor.
560 HBasicBlock* current = other;
561 while (current != nullptr) {
562 if (current == this) {
563 return true;
564 }
565 current = current->GetDominator();
566 }
567 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100568}
569
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100570static void UpdateInputsUsers(HInstruction* instruction) {
571 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
572 instruction->InputAt(i)->AddUseAt(instruction, i);
573 }
574 // Environment should be created later.
575 DCHECK(!instruction->HasEnvironment());
576}
577
Roland Levillainccc07a92014-09-16 14:48:16 +0100578void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
579 HInstruction* replacement) {
580 DCHECK(initial->GetBlock() == this);
581 InsertInstructionBefore(replacement, initial);
582 initial->ReplaceWith(replacement);
583 RemoveInstruction(initial);
584}
585
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100586static void Add(HInstructionList* instruction_list,
587 HBasicBlock* block,
588 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000589 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000590 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100591 instruction->SetBlock(block);
592 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100593 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100594 instruction_list->AddInstruction(instruction);
595}
596
597void HBasicBlock::AddInstruction(HInstruction* instruction) {
598 Add(&instructions_, this, instruction);
599}
600
601void HBasicBlock::AddPhi(HPhi* phi) {
602 Add(&phis_, this, phi);
603}
604
David Brazdilc3d743f2015-04-22 13:40:50 +0100605void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
606 DCHECK(!cursor->IsPhi());
607 DCHECK(!instruction->IsPhi());
608 DCHECK_EQ(instruction->GetId(), -1);
609 DCHECK_NE(cursor->GetId(), -1);
610 DCHECK_EQ(cursor->GetBlock(), this);
611 DCHECK(!instruction->IsControlFlow());
612 instruction->SetBlock(this);
613 instruction->SetId(GetGraph()->GetNextInstructionId());
614 UpdateInputsUsers(instruction);
615 instructions_.InsertInstructionBefore(instruction, cursor);
616}
617
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100618void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
619 DCHECK(!cursor->IsPhi());
620 DCHECK(!instruction->IsPhi());
621 DCHECK_EQ(instruction->GetId(), -1);
622 DCHECK_NE(cursor->GetId(), -1);
623 DCHECK_EQ(cursor->GetBlock(), this);
624 DCHECK(!instruction->IsControlFlow());
625 DCHECK(!cursor->IsControlFlow());
626 instruction->SetBlock(this);
627 instruction->SetId(GetGraph()->GetNextInstructionId());
628 UpdateInputsUsers(instruction);
629 instructions_.InsertInstructionAfter(instruction, cursor);
630}
631
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100632void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
633 DCHECK_EQ(phi->GetId(), -1);
634 DCHECK_NE(cursor->GetId(), -1);
635 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100636 phi->SetBlock(this);
637 phi->SetId(GetGraph()->GetNextInstructionId());
638 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100639 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100640}
641
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100642static void Remove(HInstructionList* instruction_list,
643 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000644 HInstruction* instruction,
645 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100646 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100647 instruction->SetBlock(nullptr);
648 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000649 if (ensure_safety) {
650 DCHECK(instruction->GetUses().IsEmpty());
651 DCHECK(instruction->GetEnvUses().IsEmpty());
652 RemoveAsUser(instruction);
653 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100654}
655
David Brazdil1abb4192015-02-17 18:33:36 +0000656void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100657 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000658 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100659}
660
David Brazdil1abb4192015-02-17 18:33:36 +0000661void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
662 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100663}
664
David Brazdilc7508e92015-04-27 13:28:57 +0100665void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
666 if (instruction->IsPhi()) {
667 RemovePhi(instruction->AsPhi(), ensure_safety);
668 } else {
669 RemoveInstruction(instruction, ensure_safety);
670 }
671}
672
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100673void HEnvironment::CopyFrom(const GrowableArray<HInstruction*>& locals) {
674 for (size_t i = 0; i < locals.Size(); i++) {
675 HInstruction* instruction = locals.Get(i);
676 SetRawEnvAt(i, instruction);
677 if (instruction != nullptr) {
678 instruction->AddEnvUseAt(this, i);
679 }
680 }
681}
682
David Brazdiled596192015-01-23 10:39:45 +0000683void HEnvironment::CopyFrom(HEnvironment* env) {
684 for (size_t i = 0; i < env->Size(); i++) {
685 HInstruction* instruction = env->GetInstructionAt(i);
686 SetRawEnvAt(i, instruction);
687 if (instruction != nullptr) {
688 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100689 }
David Brazdiled596192015-01-23 10:39:45 +0000690 }
691}
692
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700693void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
694 HBasicBlock* loop_header) {
695 DCHECK(loop_header->IsLoopHeader());
696 for (size_t i = 0; i < env->Size(); i++) {
697 HInstruction* instruction = env->GetInstructionAt(i);
698 SetRawEnvAt(i, instruction);
699 if (instruction == nullptr) {
700 continue;
701 }
702 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
703 // At the end of the loop pre-header, the corresponding value for instruction
704 // is the first input of the phi.
705 HInstruction* initial = instruction->AsPhi()->InputAt(0);
706 DCHECK(initial->GetBlock()->Dominates(loop_header));
707 SetRawEnvAt(i, initial);
708 initial->AddEnvUseAt(this, i);
709 } else {
710 instruction->AddEnvUseAt(this, i);
711 }
712 }
713}
714
David Brazdil1abb4192015-02-17 18:33:36 +0000715void HEnvironment::RemoveAsUserOfInput(size_t index) const {
716 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
717 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100718}
719
Calin Juravle77520bc2015-01-12 18:45:46 +0000720HInstruction* HInstruction::GetNextDisregardingMoves() const {
721 HInstruction* next = GetNext();
722 while (next != nullptr && next->IsParallelMove()) {
723 next = next->GetNext();
724 }
725 return next;
726}
727
728HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
729 HInstruction* previous = GetPrevious();
730 while (previous != nullptr && previous->IsParallelMove()) {
731 previous = previous->GetPrevious();
732 }
733 return previous;
734}
735
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100736void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000737 if (first_instruction_ == nullptr) {
738 DCHECK(last_instruction_ == nullptr);
739 first_instruction_ = last_instruction_ = instruction;
740 } else {
741 last_instruction_->next_ = instruction;
742 instruction->previous_ = last_instruction_;
743 last_instruction_ = instruction;
744 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000745}
746
David Brazdilc3d743f2015-04-22 13:40:50 +0100747void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
748 DCHECK(Contains(cursor));
749 if (cursor == first_instruction_) {
750 cursor->previous_ = instruction;
751 instruction->next_ = cursor;
752 first_instruction_ = instruction;
753 } else {
754 instruction->previous_ = cursor->previous_;
755 instruction->next_ = cursor;
756 cursor->previous_ = instruction;
757 instruction->previous_->next_ = instruction;
758 }
759}
760
761void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
762 DCHECK(Contains(cursor));
763 if (cursor == last_instruction_) {
764 cursor->next_ = instruction;
765 instruction->previous_ = cursor;
766 last_instruction_ = instruction;
767 } else {
768 instruction->next_ = cursor->next_;
769 instruction->previous_ = cursor;
770 cursor->next_ = instruction;
771 instruction->next_->previous_ = instruction;
772 }
773}
774
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100775void HInstructionList::RemoveInstruction(HInstruction* instruction) {
776 if (instruction->previous_ != nullptr) {
777 instruction->previous_->next_ = instruction->next_;
778 }
779 if (instruction->next_ != nullptr) {
780 instruction->next_->previous_ = instruction->previous_;
781 }
782 if (instruction == first_instruction_) {
783 first_instruction_ = instruction->next_;
784 }
785 if (instruction == last_instruction_) {
786 last_instruction_ = instruction->previous_;
787 }
788}
789
Roland Levillain6b469232014-09-25 10:10:38 +0100790bool HInstructionList::Contains(HInstruction* instruction) const {
791 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
792 if (it.Current() == instruction) {
793 return true;
794 }
795 }
796 return false;
797}
798
Roland Levillainccc07a92014-09-16 14:48:16 +0100799bool HInstructionList::FoundBefore(const HInstruction* instruction1,
800 const HInstruction* instruction2) const {
801 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
802 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
803 if (it.Current() == instruction1) {
804 return true;
805 }
806 if (it.Current() == instruction2) {
807 return false;
808 }
809 }
810 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
811 return true;
812}
813
Roland Levillain6c82d402014-10-13 16:10:27 +0100814bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
815 if (other_instruction == this) {
816 // An instruction does not strictly dominate itself.
817 return false;
818 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100819 HBasicBlock* block = GetBlock();
820 HBasicBlock* other_block = other_instruction->GetBlock();
821 if (block != other_block) {
822 return GetBlock()->Dominates(other_instruction->GetBlock());
823 } else {
824 // If both instructions are in the same block, ensure this
825 // instruction comes before `other_instruction`.
826 if (IsPhi()) {
827 if (!other_instruction->IsPhi()) {
828 // Phis appear before non phi-instructions so this instruction
829 // dominates `other_instruction`.
830 return true;
831 } else {
832 // There is no order among phis.
833 LOG(FATAL) << "There is no dominance between phis of a same block.";
834 return false;
835 }
836 } else {
837 // `this` is not a phi.
838 if (other_instruction->IsPhi()) {
839 // Phis appear before non phi-instructions so this instruction
840 // does not dominate `other_instruction`.
841 return false;
842 } else {
843 // Check whether this instruction comes before
844 // `other_instruction` in the instruction list.
845 return block->GetInstructions().FoundBefore(this, other_instruction);
846 }
847 }
848 }
849}
850
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100851void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100852 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000853 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
854 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100855 HInstruction* user = current->GetUser();
856 size_t input_index = current->GetIndex();
857 user->SetRawInputAt(input_index, other);
858 other->AddUseAt(user, input_index);
859 }
860
David Brazdiled596192015-01-23 10:39:45 +0000861 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
862 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100863 HEnvironment* user = current->GetUser();
864 size_t input_index = current->GetIndex();
865 user->SetRawEnvAt(input_index, other);
866 other->AddEnvUseAt(user, input_index);
867 }
868
David Brazdiled596192015-01-23 10:39:45 +0000869 uses_.Clear();
870 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100871}
872
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100873void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000874 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100875 SetRawInputAt(index, replacement);
876 replacement->AddUseAt(this, index);
877}
878
Nicolas Geoffray39468442014-09-02 15:17:15 +0100879size_t HInstruction::EnvironmentSize() const {
880 return HasEnvironment() ? environment_->Size() : 0;
881}
882
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100883void HPhi::AddInput(HInstruction* input) {
884 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000885 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100886 input->AddUseAt(this, inputs_.Size() - 1);
887}
888
David Brazdil2d7352b2015-04-20 14:52:42 +0100889void HPhi::RemoveInputAt(size_t index) {
890 RemoveAsUserOfInput(index);
891 inputs_.DeleteAt(index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100892 for (size_t i = index, e = InputCount(); i < e; ++i) {
893 InputRecordAt(i).GetUseNode()->SetIndex(i);
894 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100895}
896
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100897#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000898void H##name::Accept(HGraphVisitor* visitor) { \
899 visitor->Visit##name(this); \
900}
901
902FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
903
904#undef DEFINE_ACCEPT
905
906void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100907 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
908 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000909 HBasicBlock* block = blocks.Get(i);
910 if (block != nullptr) {
911 VisitBasicBlock(block);
912 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000913 }
914}
915
Roland Levillain633021e2014-10-01 14:12:25 +0100916void HGraphVisitor::VisitReversePostOrder() {
917 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
918 VisitBasicBlock(it.Current());
919 }
920}
921
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000922void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100923 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100924 it.Current()->Accept(this);
925 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100926 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000927 it.Current()->Accept(this);
928 }
929}
930
Mark Mendelle82549b2015-05-06 10:55:34 -0400931HConstant* HTypeConversion::TryStaticEvaluation() const {
932 HGraph* graph = GetBlock()->GetGraph();
933 if (GetInput()->IsIntConstant()) {
934 int32_t value = GetInput()->AsIntConstant()->GetValue();
935 switch (GetResultType()) {
936 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600937 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400938 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600939 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400940 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600941 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400942 default:
943 return nullptr;
944 }
945 } else if (GetInput()->IsLongConstant()) {
946 int64_t value = GetInput()->AsLongConstant()->GetValue();
947 switch (GetResultType()) {
948 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600949 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400950 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600951 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400952 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600953 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400954 default:
955 return nullptr;
956 }
957 } else if (GetInput()->IsFloatConstant()) {
958 float value = GetInput()->AsFloatConstant()->GetValue();
959 switch (GetResultType()) {
960 case Primitive::kPrimInt:
961 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600962 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400963 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600964 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400965 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600966 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
967 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400968 case Primitive::kPrimLong:
969 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600970 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400971 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600972 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400973 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600974 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
975 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400976 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600977 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400978 default:
979 return nullptr;
980 }
981 } else if (GetInput()->IsDoubleConstant()) {
982 double value = GetInput()->AsDoubleConstant()->GetValue();
983 switch (GetResultType()) {
984 case Primitive::kPrimInt:
985 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600986 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400987 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600988 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400989 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600990 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
991 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400992 case Primitive::kPrimLong:
993 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600994 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400995 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600996 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400997 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600998 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
999 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001000 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001001 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001002 default:
1003 return nullptr;
1004 }
1005 }
1006 return nullptr;
1007}
1008
Roland Levillain9240d6a2014-10-20 16:47:04 +01001009HConstant* HUnaryOperation::TryStaticEvaluation() const {
1010 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001011 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001012 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001013 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001014 }
1015 return nullptr;
1016}
1017
1018HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001019 if (GetLeft()->IsIntConstant()) {
1020 if (GetRight()->IsIntConstant()) {
1021 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1022 } else if (GetRight()->IsLongConstant()) {
1023 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1024 }
1025 } else if (GetLeft()->IsLongConstant()) {
1026 if (GetRight()->IsIntConstant()) {
1027 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1028 } else if (GetRight()->IsLongConstant()) {
1029 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001030 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001031 }
1032 return nullptr;
1033}
Dave Allison20dfc792014-06-16 20:44:29 -07001034
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001035HConstant* HBinaryOperation::GetConstantRight() const {
1036 if (GetRight()->IsConstant()) {
1037 return GetRight()->AsConstant();
1038 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1039 return GetLeft()->AsConstant();
1040 } else {
1041 return nullptr;
1042 }
1043}
1044
1045// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001046// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001047HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1048 HInstruction* most_constant_right = GetConstantRight();
1049 if (most_constant_right == nullptr) {
1050 return nullptr;
1051 } else if (most_constant_right == GetLeft()) {
1052 return GetRight();
1053 } else {
1054 return GetLeft();
1055 }
1056}
1057
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001058bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1059 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001060}
1061
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001062bool HInstruction::Equals(HInstruction* other) const {
1063 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001064 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001065 if (!InstructionDataEquals(other)) return false;
1066 if (GetType() != other->GetType()) return false;
1067 if (InputCount() != other->InputCount()) return false;
1068
1069 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1070 if (InputAt(i) != other->InputAt(i)) return false;
1071 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001072 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001073 return true;
1074}
1075
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001076std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1077#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1078 switch (rhs) {
1079 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1080 default:
1081 os << "Unknown instruction kind " << static_cast<int>(rhs);
1082 break;
1083 }
1084#undef DECLARE_CASE
1085 return os;
1086}
1087
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001088void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001089 next_->previous_ = previous_;
1090 if (previous_ != nullptr) {
1091 previous_->next_ = next_;
1092 }
1093 if (block_->instructions_.first_instruction_ == this) {
1094 block_->instructions_.first_instruction_ = next_;
1095 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001096 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001097
1098 previous_ = cursor->previous_;
1099 if (previous_ != nullptr) {
1100 previous_->next_ = this;
1101 }
1102 next_ = cursor;
1103 cursor->previous_ = this;
1104 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001105
1106 if (block_->instructions_.first_instruction_ == cursor) {
1107 block_->instructions_.first_instruction_ = this;
1108 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001109}
1110
David Brazdilfc6a86a2015-06-26 10:33:45 +00001111HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
1112 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented";
1113 DCHECK_EQ(cursor->GetBlock(), this);
1114
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001115 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1116 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001117 new_block->instructions_.first_instruction_ = cursor;
1118 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1119 instructions_.last_instruction_ = cursor->previous_;
1120 if (cursor->previous_ == nullptr) {
1121 instructions_.first_instruction_ = nullptr;
1122 } else {
1123 cursor->previous_->next_ = nullptr;
1124 cursor->previous_ = nullptr;
1125 }
1126
1127 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001128 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001129
Vladimir Marko60584552015-09-03 13:35:12 +00001130 for (HBasicBlock* successor : GetSuccessors()) {
1131 new_block->successors_.push_back(successor);
1132 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001133 }
Vladimir Marko60584552015-09-03 13:35:12 +00001134 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001135 AddSuccessor(new_block);
1136
David Brazdil56e1acc2015-06-30 15:41:36 +01001137 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001138 return new_block;
1139}
1140
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001141HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1142 DCHECK(!cursor->IsControlFlow());
1143 DCHECK_NE(instructions_.last_instruction_, cursor);
1144 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001145
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001146 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1147 new_block->instructions_.first_instruction_ = cursor->GetNext();
1148 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1149 cursor->next_->previous_ = nullptr;
1150 cursor->next_ = nullptr;
1151 instructions_.last_instruction_ = cursor;
1152
1153 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001154 for (HBasicBlock* successor : GetSuccessors()) {
1155 new_block->successors_.push_back(successor);
1156 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001157 }
Vladimir Marko60584552015-09-03 13:35:12 +00001158 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001159
Vladimir Marko60584552015-09-03 13:35:12 +00001160 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001161 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001162 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001163 }
Vladimir Marko60584552015-09-03 13:35:12 +00001164 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001165 return new_block;
1166}
1167
David Brazdilec16f792015-08-19 15:04:01 +01001168const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001169 if (EndsWithTryBoundary()) {
1170 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1171 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001172 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001173 return try_boundary;
1174 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001175 DCHECK(IsTryBlock());
1176 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001177 return nullptr;
1178 }
David Brazdilec16f792015-08-19 15:04:01 +01001179 } else if (IsTryBlock()) {
1180 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001181 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001182 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001183 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001184}
1185
1186static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1187 return block.GetPhis().IsEmpty()
1188 && !block.GetInstructions().IsEmpty()
1189 && block.GetFirstInstruction() == block.GetLastInstruction();
1190}
1191
David Brazdil46e2a392015-03-16 17:31:52 +00001192bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001193 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1194}
1195
1196bool HBasicBlock::IsSingleTryBoundary() const {
1197 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001198}
1199
David Brazdil8d5b8b22015-03-24 10:51:52 +00001200bool HBasicBlock::EndsWithControlFlowInstruction() const {
1201 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1202}
1203
David Brazdilb2bd1c52015-03-25 11:17:37 +00001204bool HBasicBlock::EndsWithIf() const {
1205 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1206}
1207
David Brazdilffee3d32015-07-06 11:48:53 +01001208bool HBasicBlock::EndsWithTryBoundary() const {
1209 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1210}
1211
David Brazdilb2bd1c52015-03-25 11:17:37 +00001212bool HBasicBlock::HasSinglePhi() const {
1213 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1214}
1215
David Brazdilffee3d32015-07-06 11:48:53 +01001216bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
Vladimir Marko60584552015-09-03 13:35:12 +00001217 if (GetBlock()->GetSuccessors().size() != other.GetBlock()->GetSuccessors().size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001218 return false;
1219 }
1220
David Brazdilb618ade2015-07-29 10:31:29 +01001221 // Exception handlers need to be stored in the same order.
1222 for (HExceptionHandlerIterator it1(*this), it2(other);
1223 !it1.Done();
1224 it1.Advance(), it2.Advance()) {
1225 DCHECK(!it2.Done());
1226 if (it1.Current() != it2.Current()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001227 return false;
1228 }
1229 }
1230 return true;
1231}
1232
David Brazdil2d7352b2015-04-20 14:52:42 +01001233size_t HInstructionList::CountSize() const {
1234 size_t size = 0;
1235 HInstruction* current = first_instruction_;
1236 for (; current != nullptr; current = current->GetNext()) {
1237 size++;
1238 }
1239 return size;
1240}
1241
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001242void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1243 for (HInstruction* current = first_instruction_;
1244 current != nullptr;
1245 current = current->GetNext()) {
1246 current->SetBlock(block);
1247 }
1248}
1249
1250void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1251 DCHECK(Contains(cursor));
1252 if (!instruction_list.IsEmpty()) {
1253 if (cursor == last_instruction_) {
1254 last_instruction_ = instruction_list.last_instruction_;
1255 } else {
1256 cursor->next_->previous_ = instruction_list.last_instruction_;
1257 }
1258 instruction_list.last_instruction_->next_ = cursor->next_;
1259 cursor->next_ = instruction_list.first_instruction_;
1260 instruction_list.first_instruction_->previous_ = cursor;
1261 }
1262}
1263
1264void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001265 if (IsEmpty()) {
1266 first_instruction_ = instruction_list.first_instruction_;
1267 last_instruction_ = instruction_list.last_instruction_;
1268 } else {
1269 AddAfter(last_instruction_, instruction_list);
1270 }
1271}
1272
David Brazdil2d7352b2015-04-20 14:52:42 +01001273void HBasicBlock::DisconnectAndDelete() {
1274 // Dominators must be removed after all the blocks they dominate. This way
1275 // a loop header is removed last, a requirement for correct loop information
1276 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001277 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001278
David Brazdil2d7352b2015-04-20 14:52:42 +01001279 // Remove the block from all loops it is included in.
1280 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1281 HLoopInformation* loop_info = it.Current();
1282 loop_info->Remove(this);
1283 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001284 // If this was the last back edge of the loop, we deliberately leave the
1285 // loop in an inconsistent state and will fail SSAChecker unless the
1286 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001287 loop_info->RemoveBackEdge(this);
1288 }
1289 }
1290
1291 // Disconnect the block from its predecessors and update their control-flow
1292 // instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001293 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001294 HInstruction* last_instruction = predecessor->GetLastInstruction();
1295 predecessor->RemoveInstruction(last_instruction);
1296 predecessor->RemoveSuccessor(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001297 if (predecessor->GetSuccessors().size() == 1u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001298 DCHECK(last_instruction->IsIf());
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001299 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001300 } else {
1301 // The predecessor has no remaining successors and therefore must be dead.
1302 // We deliberately leave it without a control-flow instruction so that the
1303 // SSAChecker fails unless it is not removed during the pass too.
Vladimir Marko60584552015-09-03 13:35:12 +00001304 DCHECK_EQ(predecessor->GetSuccessors().size(), 0u);
David Brazdil2d7352b2015-04-20 14:52:42 +01001305 }
David Brazdil46e2a392015-03-16 17:31:52 +00001306 }
Vladimir Marko60584552015-09-03 13:35:12 +00001307 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001308
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +01001309 // Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001310 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001311 // Delete this block from the list of predecessors.
1312 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001313 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001314
1315 // Check that `successor` has other predecessors, otherwise `this` is the
1316 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001317 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001318
David Brazdil2d7352b2015-04-20 14:52:42 +01001319 // Remove this block's entries in the successor's phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001320 if (successor->predecessors_.size() == 1u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001321 // The successor has just one predecessor left. Replace phis with the only
1322 // remaining input.
1323 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1324 HPhi* phi = phi_it.Current()->AsPhi();
1325 phi->ReplaceWith(phi->InputAt(1 - this_index));
1326 successor->RemovePhi(phi);
1327 }
1328 } else {
1329 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1330 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1331 }
1332 }
1333 }
Vladimir Marko60584552015-09-03 13:35:12 +00001334 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001335
1336 // Disconnect from the dominator.
1337 dominator_->RemoveDominatedBlock(this);
1338 SetDominator(nullptr);
1339
1340 // Delete from the graph. The function safely deletes remaining instructions
1341 // and updates the reverse post order.
1342 graph_->DeleteDeadBlock(this);
1343 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001344}
1345
1346void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001347 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001348 DCHECK(ContainsElement(dominated_blocks_, other));
1349 DCHECK_EQ(GetSingleSuccessor(), other);
1350 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001351 DCHECK(other->GetPhis().IsEmpty());
1352
David Brazdil2d7352b2015-04-20 14:52:42 +01001353 // Move instructions from `other` to `this`.
1354 DCHECK(EndsWithControlFlowInstruction());
1355 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001356 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001357 other->instructions_.SetBlockOfInstructions(this);
1358 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001359
David Brazdil2d7352b2015-04-20 14:52:42 +01001360 // Remove `other` from the loops it is included in.
1361 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1362 HLoopInformation* loop_info = it.Current();
1363 loop_info->Remove(other);
1364 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001365 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001366 }
1367 }
1368
1369 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001370 successors_.clear();
1371 while (!other->successors_.empty()) {
1372 HBasicBlock* successor = other->GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001373 successor->ReplacePredecessor(other, this);
1374 }
1375
David Brazdil2d7352b2015-04-20 14:52:42 +01001376 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001377 RemoveDominatedBlock(other);
1378 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1379 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001380 dominated->SetDominator(this);
1381 }
Vladimir Marko60584552015-09-03 13:35:12 +00001382 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001383 other->dominator_ = nullptr;
1384
1385 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001386 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001387
1388 // Delete `other` from the graph. The function updates reverse post order.
1389 graph_->DeleteDeadBlock(other);
1390 other->SetGraph(nullptr);
1391}
1392
1393void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1394 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001395 DCHECK(GetDominatedBlocks().empty());
1396 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001397 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001398 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001399 DCHECK(other->GetPhis().IsEmpty());
1400 DCHECK(!other->IsInLoop());
1401
1402 // Move instructions from `other` to `this`.
1403 instructions_.Add(other->GetInstructions());
1404 other->instructions_.SetBlockOfInstructions(this);
1405
1406 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001407 successors_.clear();
1408 while (!other->successors_.empty()) {
1409 HBasicBlock* successor = other->GetSuccessor(0);
David Brazdil2d7352b2015-04-20 14:52:42 +01001410 successor->ReplacePredecessor(other, this);
1411 }
1412
1413 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001414 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1415 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001416 dominated->SetDominator(this);
1417 }
Vladimir Marko60584552015-09-03 13:35:12 +00001418 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001419 other->dominator_ = nullptr;
1420 other->graph_ = nullptr;
1421}
1422
1423void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001424 while (!GetPredecessors().empty()) {
1425 HBasicBlock* predecessor = GetPredecessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001426 predecessor->ReplaceSuccessor(this, other);
1427 }
Vladimir Marko60584552015-09-03 13:35:12 +00001428 while (!GetSuccessors().empty()) {
1429 HBasicBlock* successor = GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001430 successor->ReplacePredecessor(this, other);
1431 }
Vladimir Marko60584552015-09-03 13:35:12 +00001432 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1433 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001434 }
1435 GetDominator()->ReplaceDominatedBlock(this, other);
1436 other->SetDominator(GetDominator());
1437 dominator_ = nullptr;
1438 graph_ = nullptr;
1439}
1440
1441// Create space in `blocks` for adding `number_of_new_blocks` entries
1442// starting at location `at`. Blocks after `at` are moved accordingly.
1443static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
1444 size_t number_of_new_blocks,
1445 size_t at) {
1446 size_t old_size = blocks->Size();
1447 size_t new_size = old_size + number_of_new_blocks;
1448 blocks->SetSize(new_size);
1449 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
1450 blocks->Put(j, blocks->Get(i));
1451 }
1452}
1453
David Brazdil2d7352b2015-04-20 14:52:42 +01001454void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1455 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001456 DCHECK(block->GetSuccessors().empty());
1457 DCHECK(block->GetPredecessors().empty());
1458 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001459 DCHECK(block->GetDominator() == nullptr);
1460
1461 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1462 block->RemoveInstruction(it.Current());
1463 }
1464 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1465 block->RemovePhi(it.Current()->AsPhi());
1466 }
1467
David Brazdilc7af85d2015-05-26 12:05:55 +01001468 if (block->IsExitBlock()) {
1469 exit_block_ = nullptr;
1470 }
1471
David Brazdil2d7352b2015-04-20 14:52:42 +01001472 reverse_post_order_.Delete(block);
1473 blocks_.Put(block->GetBlockId(), nullptr);
1474}
1475
Calin Juravle2e768302015-07-28 14:41:11 +00001476HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001477 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001478 // Update the environments in this graph to have the invoke's environment
1479 // as parent.
1480 {
1481 HReversePostOrderIterator it(*this);
1482 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1483 for (; !it.Done(); it.Advance()) {
1484 HBasicBlock* block = it.Current();
1485 for (HInstructionIterator instr_it(block->GetInstructions());
1486 !instr_it.Done();
1487 instr_it.Advance()) {
1488 HInstruction* current = instr_it.Current();
1489 if (current->NeedsEnvironment()) {
1490 current->GetEnvironment()->SetAndCopyParentChain(
1491 outer_graph->GetArena(), invoke->GetEnvironment());
1492 }
1493 }
1494 }
1495 }
1496 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1497 if (HasBoundsChecks()) {
1498 outer_graph->SetHasBoundsChecks(true);
1499 }
1500
Calin Juravle2e768302015-07-28 14:41:11 +00001501 HInstruction* return_value = nullptr;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001502 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001503 // Simple case of an entry block, a body block, and an exit block.
1504 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001505 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001506 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
1507 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001508 DCHECK(!body->IsExitBlock());
1509 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001510
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001511 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1512 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001513
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001514 // Replace the invoke with the return value of the inlined graph.
1515 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001516 return_value = last->InputAt(0);
1517 invoke->ReplaceWith(return_value);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001518 } else {
1519 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001520 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001521
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001522 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001523 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001524 // Need to inline multiple blocks. We split `invoke`'s block
1525 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001526 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001527 // with the second half.
1528 ArenaAllocator* allocator = outer_graph->GetArena();
1529 HBasicBlock* at = invoke->GetBlock();
1530 HBasicBlock* to = at->SplitAfter(invoke);
1531
Vladimir Marko60584552015-09-03 13:35:12 +00001532 HBasicBlock* first = entry_block_->GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001533 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001534 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001535 exit_block_->ReplaceWith(to);
1536
1537 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001538 // to not `HReturn` but `HGoto` instead.
Vladimir Marko60584552015-09-03 13:35:12 +00001539 bool returns_void = to->GetPredecessor(0)->GetLastInstruction()->IsReturnVoid();
1540 if (to->GetPredecessors().size() == 1) {
1541 HBasicBlock* predecessor = to->GetPredecessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001542 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001543 if (!returns_void) {
1544 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001545 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001546 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001547 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001548 } else {
1549 if (!returns_void) {
1550 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001551 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001552 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001553 to->AddPhi(return_value->AsPhi());
1554 }
Vladimir Marko60584552015-09-03 13:35:12 +00001555 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001556 HInstruction* last = predecessor->GetLastInstruction();
1557 if (!returns_void) {
1558 return_value->AsPhi()->AddInput(last->InputAt(0));
1559 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001560 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001561 predecessor->RemoveInstruction(last);
1562 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001563 }
1564
1565 if (return_value != nullptr) {
1566 invoke->ReplaceWith(return_value);
1567 }
1568
1569 // Update the meta information surrounding blocks:
1570 // (1) the graph they are now in,
1571 // (2) the reverse post order of that graph,
1572 // (3) the potential loop information they are now in.
1573
1574 // We don't add the entry block, the exit block, and the first block, which
1575 // has been merged with `at`.
1576 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1577
1578 // We add the `to` block.
1579 static constexpr int kNumberOfNewBlocksInCaller = 1;
1580 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1581 + kNumberOfNewBlocksInCaller;
1582
1583 // Find the location of `at` in the outer graph's reverse post order. The new
1584 // blocks will be added after it.
1585 size_t index_of_at = 0;
1586 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1587 index_of_at++;
1588 }
1589 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1590
1591 // Do a reverse post order of the blocks in the callee and do (1), (2),
1592 // and (3) to the blocks that apply.
1593 HLoopInformation* info = at->GetLoopInformation();
1594 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1595 HBasicBlock* current = it.Current();
1596 if (current != exit_block_ && current != entry_block_ && current != first) {
1597 DCHECK(!current->IsInLoop());
1598 DCHECK(current->GetGraph() == this);
1599 current->SetGraph(outer_graph);
1600 outer_graph->AddBlock(current);
1601 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1602 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001603 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001604 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1605 loop_it.Current()->Add(current);
1606 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001607 }
1608 }
1609 }
1610
1611 // Do (1), (2), and (3) to `to`.
1612 to->SetGraph(outer_graph);
1613 outer_graph->AddBlock(to);
1614 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1615 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001616 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001617 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1618 loop_it.Current()->Add(to);
1619 }
David Brazdil46e2a392015-03-16 17:31:52 +00001620 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001621 // Only `to` can become a back edge, as the inlined blocks
1622 // are predecessors of `to`.
1623 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001624 }
1625 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001626 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001627
David Brazdil05144f42015-04-16 15:18:00 +01001628 // Update the next instruction id of the outer graph, so that instructions
1629 // added later get bigger ids than those in the inner graph.
1630 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1631
1632 // Walk over the entry block and:
1633 // - Move constants from the entry block to the outer_graph's entry block,
1634 // - Replace HParameterValue instructions with their real value.
1635 // - Remove suspend checks, that hold an environment.
1636 // We must do this after the other blocks have been inlined, otherwise ids of
1637 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001638 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001639 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1640 HInstruction* current = it.Current();
1641 if (current->IsNullConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001642 current->ReplaceWith(outer_graph->GetNullConstant(current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001643 } else if (current->IsIntConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001644 current->ReplaceWith(outer_graph->GetIntConstant(
1645 current->AsIntConstant()->GetValue(), current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001646 } else if (current->IsLongConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001647 current->ReplaceWith(outer_graph->GetLongConstant(
1648 current->AsLongConstant()->GetValue(), current->GetDexPc()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001649 } else if (current->IsFloatConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001650 current->ReplaceWith(outer_graph->GetFloatConstant(
1651 current->AsFloatConstant()->GetValue(), current->GetDexPc()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001652 } else if (current->IsDoubleConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001653 current->ReplaceWith(outer_graph->GetDoubleConstant(
1654 current->AsDoubleConstant()->GetValue(), current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001655 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001656 if (kIsDebugBuild
1657 && invoke->IsInvokeStaticOrDirect()
1658 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1659 // Ensure we do not use the last input of `invoke`, as it
1660 // contains a clinit check which is not an actual argument.
1661 size_t last_input_index = invoke->InputCount() - 1;
1662 DCHECK(parameter_index != last_input_index);
1663 }
David Brazdil05144f42015-04-16 15:18:00 +01001664 current->ReplaceWith(invoke->InputAt(parameter_index++));
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001665 } else if (current->IsCurrentMethod()) {
1666 current->ReplaceWith(outer_graph->GetCurrentMethod());
David Brazdil05144f42015-04-16 15:18:00 +01001667 } else {
1668 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1669 entry_block_->RemoveInstruction(current);
1670 }
1671 }
1672
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001673 // Finally remove the invoke from the caller.
1674 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00001675
1676 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001677}
1678
Mingyao Yang3584bce2015-05-19 16:01:59 -07001679/*
1680 * Loop will be transformed to:
1681 * old_pre_header
1682 * |
1683 * if_block
1684 * / \
1685 * dummy_block deopt_block
1686 * \ /
1687 * new_pre_header
1688 * |
1689 * header
1690 */
1691void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1692 DCHECK(header->IsLoopHeader());
1693 HBasicBlock* pre_header = header->GetDominator();
1694
1695 // Need this to avoid critical edge.
1696 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1697 // Need this to avoid critical edge.
1698 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1699 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1700 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1701 AddBlock(if_block);
1702 AddBlock(dummy_block);
1703 AddBlock(deopt_block);
1704 AddBlock(new_pre_header);
1705
1706 header->ReplacePredecessor(pre_header, new_pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001707 pre_header->successors_.clear();
1708 pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07001709
1710 pre_header->AddSuccessor(if_block);
1711 if_block->AddSuccessor(dummy_block); // True successor
1712 if_block->AddSuccessor(deopt_block); // False successor
1713 dummy_block->AddSuccessor(new_pre_header);
1714 deopt_block->AddSuccessor(new_pre_header);
1715
Vladimir Marko60584552015-09-03 13:35:12 +00001716 pre_header->dominated_blocks_.push_back(if_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001717 if_block->SetDominator(pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001718 if_block->dominated_blocks_.push_back(dummy_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001719 dummy_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001720 if_block->dominated_blocks_.push_back(deopt_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001721 deopt_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001722 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001723 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001724 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001725 header->SetDominator(new_pre_header);
1726
1727 size_t index_of_header = 0;
1728 while (reverse_post_order_.Get(index_of_header) != header) {
1729 index_of_header++;
1730 }
1731 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
1732 reverse_post_order_.Put(index_of_header++, if_block);
1733 reverse_post_order_.Put(index_of_header++, dummy_block);
1734 reverse_post_order_.Put(index_of_header++, deopt_block);
1735 reverse_post_order_.Put(index_of_header++, new_pre_header);
1736
1737 HLoopInformation* info = pre_header->GetLoopInformation();
1738 if (info != nullptr) {
1739 if_block->SetLoopInformation(info);
1740 dummy_block->SetLoopInformation(info);
1741 deopt_block->SetLoopInformation(info);
1742 new_pre_header->SetLoopInformation(info);
1743 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1744 !loop_it.Done();
1745 loop_it.Advance()) {
1746 loop_it.Current()->Add(if_block);
1747 loop_it.Current()->Add(dummy_block);
1748 loop_it.Current()->Add(deopt_block);
1749 loop_it.Current()->Add(new_pre_header);
1750 }
1751 }
1752}
1753
Calin Juravle2e768302015-07-28 14:41:11 +00001754void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
1755 if (kIsDebugBuild) {
1756 DCHECK_EQ(GetType(), Primitive::kPrimNot);
1757 ScopedObjectAccess soa(Thread::Current());
1758 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
1759 if (IsBoundType()) {
1760 // Having the test here spares us from making the method virtual just for
1761 // the sake of a DCHECK.
1762 ReferenceTypeInfo upper_bound_rti = AsBoundType()->GetUpperBound();
1763 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
1764 << " upper_bound_rti: " << upper_bound_rti
1765 << " rti: " << rti;
1766 DCHECK(!upper_bound_rti.GetTypeHandle()->IsFinal() || rti.IsExact());
1767 }
1768 }
1769 reference_type_info_ = rti;
1770}
1771
1772ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
1773
1774ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
1775 : type_handle_(type_handle), is_exact_(is_exact) {
1776 if (kIsDebugBuild) {
1777 ScopedObjectAccess soa(Thread::Current());
1778 DCHECK(IsValidHandle(type_handle));
1779 }
1780}
1781
Calin Juravleacf735c2015-02-12 15:25:22 +00001782std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1783 ScopedObjectAccess soa(Thread::Current());
1784 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00001785 << " is_valid=" << rhs.IsValid()
1786 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00001787 << " is_exact=" << rhs.IsExact()
1788 << " ]";
1789 return os;
1790}
1791
Mark Mendellc4701932015-04-10 13:18:51 -04001792bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
1793 // For now, assume that instructions in different blocks may use the
1794 // environment.
1795 // TODO: Use the control flow to decide if this is true.
1796 if (GetBlock() != other->GetBlock()) {
1797 return true;
1798 }
1799
1800 // We know that we are in the same block. Walk from 'this' to 'other',
1801 // checking to see if there is any instruction with an environment.
1802 HInstruction* current = this;
1803 for (; current != other && current != nullptr; current = current->GetNext()) {
1804 // This is a conservative check, as the instruction result may not be in
1805 // the referenced environment.
1806 if (current->HasEnvironment()) {
1807 return true;
1808 }
1809 }
1810
1811 // We should have been called with 'this' before 'other' in the block.
1812 // Just confirm this.
1813 DCHECK(current != nullptr);
1814 return false;
1815}
1816
1817void HInstruction::RemoveEnvironmentUsers() {
1818 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
1819 HUseListNode<HEnvironment*>* user_node = use_it.Current();
1820 HEnvironment* user = user_node->GetUser();
1821 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
1822 }
1823 env_uses_.Clear();
1824}
1825
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001826} // namespace art