blob: b3cf0b3745e0637ffbd7562f288b48fce217df8e [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
David Brazdilbbd733e2015-08-18 17:48:17 +0100348bool HGraph::HasTryCatch() const {
349 for (size_t i = 0, e = blocks_.Size(); i < e; ++i) {
350 HBasicBlock* block = blocks_.Get(i);
351 if (block != nullptr && (block->IsTryBlock() || block->IsCatchBlock())) {
352 return true;
353 }
354 }
355 return false;
356}
357
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100358void HGraph::SimplifyCFG() {
359 // Simplify the CFG for future analysis, and code generation:
360 // (1): Split critical edges.
361 // (2): Simplify loops by having only one back edge, and one preheader.
362 for (size_t i = 0; i < blocks_.Size(); ++i) {
363 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100364 if (block == nullptr) continue;
David Brazdilffee3d32015-07-06 11:48:53 +0100365 if (block->NumberOfNormalSuccessors() > 1) {
Vladimir Marko60584552015-09-03 13:35:12 +0000366 for (size_t j = 0; j < block->GetSuccessors().size(); ++j) {
367 HBasicBlock* successor = block->GetSuccessor(j);
David Brazdilffee3d32015-07-06 11:48:53 +0100368 DCHECK(!successor->IsCatchBlock());
Vladimir Marko60584552015-09-03 13:35:12 +0000369 if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100370 SplitCriticalEdge(block, successor);
371 --j;
372 }
373 }
374 }
375 if (block->IsLoopHeader()) {
376 SimplifyLoop(block);
377 }
378 }
379}
380
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000381bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100382 // Order does not matter.
383 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
384 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100385 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100386 if (block->IsCatchBlock()) {
387 // TODO: Dealing with exceptional back edges could be tricky because
388 // they only approximate the real control flow. Bail out for now.
389 return false;
390 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100391 HLoopInformation* info = block->GetLoopInformation();
392 if (!info->Populate()) {
393 // Abort if the loop is non natural. We currently bailout in such cases.
394 return false;
395 }
396 }
397 }
398 return true;
399}
400
David Brazdil8d5b8b22015-03-24 10:51:52 +0000401void HGraph::InsertConstant(HConstant* constant) {
402 // New constants are inserted before the final control-flow instruction
403 // of the graph, or at its end if called from the graph builder.
404 if (entry_block_->EndsWithControlFlowInstruction()) {
405 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000406 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000407 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000408 }
409}
410
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600411HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100412 // For simplicity, don't bother reviving the cached null constant if it is
413 // not null and not in a block. Otherwise, we need to clear the instruction
414 // id and/or any invariants the graph is assuming when adding new instructions.
415 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600416 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000417 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000418 }
419 return cached_null_constant_;
420}
421
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100422HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100423 // For simplicity, don't bother reviving the cached current method if it is
424 // not null and not in a block. Otherwise, we need to clear the instruction
425 // id and/or any invariants the graph is assuming when adding new instructions.
426 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700427 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600428 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
429 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100430 if (entry_block_->GetFirstInstruction() == nullptr) {
431 entry_block_->AddInstruction(cached_current_method_);
432 } else {
433 entry_block_->InsertInstructionBefore(
434 cached_current_method_, entry_block_->GetFirstInstruction());
435 }
436 }
437 return cached_current_method_;
438}
439
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600440HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000441 switch (type) {
442 case Primitive::Type::kPrimBoolean:
443 DCHECK(IsUint<1>(value));
444 FALLTHROUGH_INTENDED;
445 case Primitive::Type::kPrimByte:
446 case Primitive::Type::kPrimChar:
447 case Primitive::Type::kPrimShort:
448 case Primitive::Type::kPrimInt:
449 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600450 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000451
452 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600453 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000454
455 default:
456 LOG(FATAL) << "Unsupported constant type";
457 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000458 }
David Brazdil46e2a392015-03-16 17:31:52 +0000459}
460
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000461void HGraph::CacheFloatConstant(HFloatConstant* constant) {
462 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
463 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
464 cached_float_constants_.Overwrite(value, constant);
465}
466
467void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
468 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
469 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
470 cached_double_constants_.Overwrite(value, constant);
471}
472
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000473void HLoopInformation::Add(HBasicBlock* block) {
474 blocks_.SetBit(block->GetBlockId());
475}
476
David Brazdil46e2a392015-03-16 17:31:52 +0000477void HLoopInformation::Remove(HBasicBlock* block) {
478 blocks_.ClearBit(block->GetBlockId());
479}
480
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100481void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
482 if (blocks_.IsBitSet(block->GetBlockId())) {
483 return;
484 }
485
486 blocks_.SetBit(block->GetBlockId());
487 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000488 for (HBasicBlock* predecessor : block->GetPredecessors()) {
489 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100490 }
491}
492
493bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100494 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100495 for (size_t i = 0, e = GetBackEdges().Size(); i < e; ++i) {
496 HBasicBlock* back_edge = GetBackEdges().Get(i);
497 DCHECK(back_edge->GetDominator() != nullptr);
498 if (!header_->Dominates(back_edge)) {
499 // This loop is not natural. Do not bother going further.
500 return false;
501 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100502
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100503 // Populate this loop: starting with the back edge, recursively add predecessors
504 // that are not already part of that loop. Set the header as part of the loop
505 // to end the recursion.
506 // This is a recursive implementation of the algorithm described in
507 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
508 blocks_.SetBit(header_->GetBlockId());
509 PopulateRecursive(back_edge);
510 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100511 return true;
512}
513
David Brazdila4b8c212015-05-07 09:59:30 +0100514void HLoopInformation::Update() {
515 HGraph* graph = header_->GetGraph();
516 for (uint32_t id : blocks_.Indexes()) {
517 HBasicBlock* block = graph->GetBlocks().Get(id);
518 // Reset loop information of non-header blocks inside the loop, except
519 // members of inner nested loops because those should already have been
520 // updated by their own LoopInformation.
521 if (block->GetLoopInformation() == this && block != header_) {
522 block->SetLoopInformation(nullptr);
523 }
524 }
525 blocks_.ClearAllBits();
526
527 if (back_edges_.IsEmpty()) {
528 // The loop has been dismantled, delete its suspend check and remove info
529 // from the header.
530 DCHECK(HasSuspendCheck());
531 header_->RemoveInstruction(suspend_check_);
532 header_->SetLoopInformation(nullptr);
533 header_ = nullptr;
534 suspend_check_ = nullptr;
535 } else {
536 if (kIsDebugBuild) {
537 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
538 DCHECK(header_->Dominates(back_edges_.Get(i)));
539 }
540 }
541 // This loop still has reachable back edges. Repopulate the list of blocks.
542 bool populate_successful = Populate();
543 DCHECK(populate_successful);
544 }
545}
546
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100547HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100548 return header_->GetDominator();
549}
550
551bool HLoopInformation::Contains(const HBasicBlock& block) const {
552 return blocks_.IsBitSet(block.GetBlockId());
553}
554
555bool HLoopInformation::IsIn(const HLoopInformation& other) const {
556 return other.blocks_.IsBitSet(header_->GetBlockId());
557}
558
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100559size_t HLoopInformation::GetLifetimeEnd() const {
560 size_t last_position = 0;
561 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
562 last_position = std::max(back_edges_.Get(i)->GetLifetimeEnd(), last_position);
563 }
564 return last_position;
565}
566
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100567bool HBasicBlock::Dominates(HBasicBlock* other) const {
568 // Walk up the dominator tree from `other`, to find out if `this`
569 // is an ancestor.
570 HBasicBlock* current = other;
571 while (current != nullptr) {
572 if (current == this) {
573 return true;
574 }
575 current = current->GetDominator();
576 }
577 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100578}
579
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100580static void UpdateInputsUsers(HInstruction* instruction) {
581 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
582 instruction->InputAt(i)->AddUseAt(instruction, i);
583 }
584 // Environment should be created later.
585 DCHECK(!instruction->HasEnvironment());
586}
587
Roland Levillainccc07a92014-09-16 14:48:16 +0100588void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
589 HInstruction* replacement) {
590 DCHECK(initial->GetBlock() == this);
591 InsertInstructionBefore(replacement, initial);
592 initial->ReplaceWith(replacement);
593 RemoveInstruction(initial);
594}
595
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100596static void Add(HInstructionList* instruction_list,
597 HBasicBlock* block,
598 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000599 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000600 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100601 instruction->SetBlock(block);
602 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100603 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100604 instruction_list->AddInstruction(instruction);
605}
606
607void HBasicBlock::AddInstruction(HInstruction* instruction) {
608 Add(&instructions_, this, instruction);
609}
610
611void HBasicBlock::AddPhi(HPhi* phi) {
612 Add(&phis_, this, phi);
613}
614
David Brazdilc3d743f2015-04-22 13:40:50 +0100615void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
616 DCHECK(!cursor->IsPhi());
617 DCHECK(!instruction->IsPhi());
618 DCHECK_EQ(instruction->GetId(), -1);
619 DCHECK_NE(cursor->GetId(), -1);
620 DCHECK_EQ(cursor->GetBlock(), this);
621 DCHECK(!instruction->IsControlFlow());
622 instruction->SetBlock(this);
623 instruction->SetId(GetGraph()->GetNextInstructionId());
624 UpdateInputsUsers(instruction);
625 instructions_.InsertInstructionBefore(instruction, cursor);
626}
627
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100628void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
629 DCHECK(!cursor->IsPhi());
630 DCHECK(!instruction->IsPhi());
631 DCHECK_EQ(instruction->GetId(), -1);
632 DCHECK_NE(cursor->GetId(), -1);
633 DCHECK_EQ(cursor->GetBlock(), this);
634 DCHECK(!instruction->IsControlFlow());
635 DCHECK(!cursor->IsControlFlow());
636 instruction->SetBlock(this);
637 instruction->SetId(GetGraph()->GetNextInstructionId());
638 UpdateInputsUsers(instruction);
639 instructions_.InsertInstructionAfter(instruction, cursor);
640}
641
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100642void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
643 DCHECK_EQ(phi->GetId(), -1);
644 DCHECK_NE(cursor->GetId(), -1);
645 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100646 phi->SetBlock(this);
647 phi->SetId(GetGraph()->GetNextInstructionId());
648 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100649 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100650}
651
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100652static void Remove(HInstructionList* instruction_list,
653 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000654 HInstruction* instruction,
655 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100656 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100657 instruction->SetBlock(nullptr);
658 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000659 if (ensure_safety) {
660 DCHECK(instruction->GetUses().IsEmpty());
661 DCHECK(instruction->GetEnvUses().IsEmpty());
662 RemoveAsUser(instruction);
663 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100664}
665
David Brazdil1abb4192015-02-17 18:33:36 +0000666void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100667 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000668 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100669}
670
David Brazdil1abb4192015-02-17 18:33:36 +0000671void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
672 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100673}
674
David Brazdilc7508e92015-04-27 13:28:57 +0100675void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
676 if (instruction->IsPhi()) {
677 RemovePhi(instruction->AsPhi(), ensure_safety);
678 } else {
679 RemoveInstruction(instruction, ensure_safety);
680 }
681}
682
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100683void HEnvironment::CopyFrom(const GrowableArray<HInstruction*>& locals) {
684 for (size_t i = 0; i < locals.Size(); i++) {
685 HInstruction* instruction = locals.Get(i);
686 SetRawEnvAt(i, instruction);
687 if (instruction != nullptr) {
688 instruction->AddEnvUseAt(this, i);
689 }
690 }
691}
692
David Brazdiled596192015-01-23 10:39:45 +0000693void HEnvironment::CopyFrom(HEnvironment* env) {
694 for (size_t i = 0; i < env->Size(); i++) {
695 HInstruction* instruction = env->GetInstructionAt(i);
696 SetRawEnvAt(i, instruction);
697 if (instruction != nullptr) {
698 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100699 }
David Brazdiled596192015-01-23 10:39:45 +0000700 }
701}
702
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700703void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
704 HBasicBlock* loop_header) {
705 DCHECK(loop_header->IsLoopHeader());
706 for (size_t i = 0; i < env->Size(); i++) {
707 HInstruction* instruction = env->GetInstructionAt(i);
708 SetRawEnvAt(i, instruction);
709 if (instruction == nullptr) {
710 continue;
711 }
712 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
713 // At the end of the loop pre-header, the corresponding value for instruction
714 // is the first input of the phi.
715 HInstruction* initial = instruction->AsPhi()->InputAt(0);
716 DCHECK(initial->GetBlock()->Dominates(loop_header));
717 SetRawEnvAt(i, initial);
718 initial->AddEnvUseAt(this, i);
719 } else {
720 instruction->AddEnvUseAt(this, i);
721 }
722 }
723}
724
David Brazdil1abb4192015-02-17 18:33:36 +0000725void HEnvironment::RemoveAsUserOfInput(size_t index) const {
726 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
727 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100728}
729
Calin Juravle77520bc2015-01-12 18:45:46 +0000730HInstruction* HInstruction::GetNextDisregardingMoves() const {
731 HInstruction* next = GetNext();
732 while (next != nullptr && next->IsParallelMove()) {
733 next = next->GetNext();
734 }
735 return next;
736}
737
738HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
739 HInstruction* previous = GetPrevious();
740 while (previous != nullptr && previous->IsParallelMove()) {
741 previous = previous->GetPrevious();
742 }
743 return previous;
744}
745
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100746void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000747 if (first_instruction_ == nullptr) {
748 DCHECK(last_instruction_ == nullptr);
749 first_instruction_ = last_instruction_ = instruction;
750 } else {
751 last_instruction_->next_ = instruction;
752 instruction->previous_ = last_instruction_;
753 last_instruction_ = instruction;
754 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000755}
756
David Brazdilc3d743f2015-04-22 13:40:50 +0100757void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
758 DCHECK(Contains(cursor));
759 if (cursor == first_instruction_) {
760 cursor->previous_ = instruction;
761 instruction->next_ = cursor;
762 first_instruction_ = instruction;
763 } else {
764 instruction->previous_ = cursor->previous_;
765 instruction->next_ = cursor;
766 cursor->previous_ = instruction;
767 instruction->previous_->next_ = instruction;
768 }
769}
770
771void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
772 DCHECK(Contains(cursor));
773 if (cursor == last_instruction_) {
774 cursor->next_ = instruction;
775 instruction->previous_ = cursor;
776 last_instruction_ = instruction;
777 } else {
778 instruction->next_ = cursor->next_;
779 instruction->previous_ = cursor;
780 cursor->next_ = instruction;
781 instruction->next_->previous_ = instruction;
782 }
783}
784
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100785void HInstructionList::RemoveInstruction(HInstruction* instruction) {
786 if (instruction->previous_ != nullptr) {
787 instruction->previous_->next_ = instruction->next_;
788 }
789 if (instruction->next_ != nullptr) {
790 instruction->next_->previous_ = instruction->previous_;
791 }
792 if (instruction == first_instruction_) {
793 first_instruction_ = instruction->next_;
794 }
795 if (instruction == last_instruction_) {
796 last_instruction_ = instruction->previous_;
797 }
798}
799
Roland Levillain6b469232014-09-25 10:10:38 +0100800bool HInstructionList::Contains(HInstruction* instruction) const {
801 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
802 if (it.Current() == instruction) {
803 return true;
804 }
805 }
806 return false;
807}
808
Roland Levillainccc07a92014-09-16 14:48:16 +0100809bool HInstructionList::FoundBefore(const HInstruction* instruction1,
810 const HInstruction* instruction2) const {
811 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
812 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
813 if (it.Current() == instruction1) {
814 return true;
815 }
816 if (it.Current() == instruction2) {
817 return false;
818 }
819 }
820 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
821 return true;
822}
823
Roland Levillain6c82d402014-10-13 16:10:27 +0100824bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
825 if (other_instruction == this) {
826 // An instruction does not strictly dominate itself.
827 return false;
828 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100829 HBasicBlock* block = GetBlock();
830 HBasicBlock* other_block = other_instruction->GetBlock();
831 if (block != other_block) {
832 return GetBlock()->Dominates(other_instruction->GetBlock());
833 } else {
834 // If both instructions are in the same block, ensure this
835 // instruction comes before `other_instruction`.
836 if (IsPhi()) {
837 if (!other_instruction->IsPhi()) {
838 // Phis appear before non phi-instructions so this instruction
839 // dominates `other_instruction`.
840 return true;
841 } else {
842 // There is no order among phis.
843 LOG(FATAL) << "There is no dominance between phis of a same block.";
844 return false;
845 }
846 } else {
847 // `this` is not a phi.
848 if (other_instruction->IsPhi()) {
849 // Phis appear before non phi-instructions so this instruction
850 // does not dominate `other_instruction`.
851 return false;
852 } else {
853 // Check whether this instruction comes before
854 // `other_instruction` in the instruction list.
855 return block->GetInstructions().FoundBefore(this, other_instruction);
856 }
857 }
858 }
859}
860
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100861void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100862 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000863 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
864 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100865 HInstruction* user = current->GetUser();
866 size_t input_index = current->GetIndex();
867 user->SetRawInputAt(input_index, other);
868 other->AddUseAt(user, input_index);
869 }
870
David Brazdiled596192015-01-23 10:39:45 +0000871 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
872 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100873 HEnvironment* user = current->GetUser();
874 size_t input_index = current->GetIndex();
875 user->SetRawEnvAt(input_index, other);
876 other->AddEnvUseAt(user, input_index);
877 }
878
David Brazdiled596192015-01-23 10:39:45 +0000879 uses_.Clear();
880 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100881}
882
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100883void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000884 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100885 SetRawInputAt(index, replacement);
886 replacement->AddUseAt(this, index);
887}
888
Nicolas Geoffray39468442014-09-02 15:17:15 +0100889size_t HInstruction::EnvironmentSize() const {
890 return HasEnvironment() ? environment_->Size() : 0;
891}
892
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100893void HPhi::AddInput(HInstruction* input) {
894 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000895 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100896 input->AddUseAt(this, inputs_.Size() - 1);
897}
898
David Brazdil2d7352b2015-04-20 14:52:42 +0100899void HPhi::RemoveInputAt(size_t index) {
900 RemoveAsUserOfInput(index);
901 inputs_.DeleteAt(index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100902 for (size_t i = index, e = InputCount(); i < e; ++i) {
903 InputRecordAt(i).GetUseNode()->SetIndex(i);
904 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100905}
906
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100907#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000908void H##name::Accept(HGraphVisitor* visitor) { \
909 visitor->Visit##name(this); \
910}
911
912FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
913
914#undef DEFINE_ACCEPT
915
916void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100917 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
918 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000919 HBasicBlock* block = blocks.Get(i);
920 if (block != nullptr) {
921 VisitBasicBlock(block);
922 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000923 }
924}
925
Roland Levillain633021e2014-10-01 14:12:25 +0100926void HGraphVisitor::VisitReversePostOrder() {
927 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
928 VisitBasicBlock(it.Current());
929 }
930}
931
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000932void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100933 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100934 it.Current()->Accept(this);
935 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100936 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000937 it.Current()->Accept(this);
938 }
939}
940
Mark Mendelle82549b2015-05-06 10:55:34 -0400941HConstant* HTypeConversion::TryStaticEvaluation() const {
942 HGraph* graph = GetBlock()->GetGraph();
943 if (GetInput()->IsIntConstant()) {
944 int32_t value = GetInput()->AsIntConstant()->GetValue();
945 switch (GetResultType()) {
946 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600947 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400948 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600949 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400950 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600951 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400952 default:
953 return nullptr;
954 }
955 } else if (GetInput()->IsLongConstant()) {
956 int64_t value = GetInput()->AsLongConstant()->GetValue();
957 switch (GetResultType()) {
958 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600959 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400960 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600961 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400962 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600963 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400964 default:
965 return nullptr;
966 }
967 } else if (GetInput()->IsFloatConstant()) {
968 float value = GetInput()->AsFloatConstant()->GetValue();
969 switch (GetResultType()) {
970 case Primitive::kPrimInt:
971 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600972 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400973 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600974 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400975 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600976 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
977 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400978 case Primitive::kPrimLong:
979 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600980 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400981 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600982 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400983 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600984 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
985 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400986 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600987 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400988 default:
989 return nullptr;
990 }
991 } else if (GetInput()->IsDoubleConstant()) {
992 double value = GetInput()->AsDoubleConstant()->GetValue();
993 switch (GetResultType()) {
994 case Primitive::kPrimInt:
995 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600996 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400997 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600998 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400999 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001000 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1001 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001002 case Primitive::kPrimLong:
1003 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001004 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001005 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001006 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001007 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001008 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1009 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001010 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001011 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001012 default:
1013 return nullptr;
1014 }
1015 }
1016 return nullptr;
1017}
1018
Roland Levillain9240d6a2014-10-20 16:47:04 +01001019HConstant* HUnaryOperation::TryStaticEvaluation() const {
1020 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001021 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001022 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001023 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001024 }
1025 return nullptr;
1026}
1027
1028HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001029 if (GetLeft()->IsIntConstant()) {
1030 if (GetRight()->IsIntConstant()) {
1031 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1032 } else if (GetRight()->IsLongConstant()) {
1033 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1034 }
1035 } else if (GetLeft()->IsLongConstant()) {
1036 if (GetRight()->IsIntConstant()) {
1037 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1038 } else if (GetRight()->IsLongConstant()) {
1039 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001040 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001041 }
1042 return nullptr;
1043}
Dave Allison20dfc792014-06-16 20:44:29 -07001044
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001045HConstant* HBinaryOperation::GetConstantRight() const {
1046 if (GetRight()->IsConstant()) {
1047 return GetRight()->AsConstant();
1048 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1049 return GetLeft()->AsConstant();
1050 } else {
1051 return nullptr;
1052 }
1053}
1054
1055// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001056// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001057HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1058 HInstruction* most_constant_right = GetConstantRight();
1059 if (most_constant_right == nullptr) {
1060 return nullptr;
1061 } else if (most_constant_right == GetLeft()) {
1062 return GetRight();
1063 } else {
1064 return GetLeft();
1065 }
1066}
1067
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001068bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1069 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001070}
1071
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001072bool HInstruction::Equals(HInstruction* other) const {
1073 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001074 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001075 if (!InstructionDataEquals(other)) return false;
1076 if (GetType() != other->GetType()) return false;
1077 if (InputCount() != other->InputCount()) return false;
1078
1079 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1080 if (InputAt(i) != other->InputAt(i)) return false;
1081 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001082 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001083 return true;
1084}
1085
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001086std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1087#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1088 switch (rhs) {
1089 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1090 default:
1091 os << "Unknown instruction kind " << static_cast<int>(rhs);
1092 break;
1093 }
1094#undef DECLARE_CASE
1095 return os;
1096}
1097
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001098void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001099 next_->previous_ = previous_;
1100 if (previous_ != nullptr) {
1101 previous_->next_ = next_;
1102 }
1103 if (block_->instructions_.first_instruction_ == this) {
1104 block_->instructions_.first_instruction_ = next_;
1105 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001106 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001107
1108 previous_ = cursor->previous_;
1109 if (previous_ != nullptr) {
1110 previous_->next_ = this;
1111 }
1112 next_ = cursor;
1113 cursor->previous_ = this;
1114 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001115
1116 if (block_->instructions_.first_instruction_ == cursor) {
1117 block_->instructions_.first_instruction_ = this;
1118 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001119}
1120
David Brazdilfc6a86a2015-06-26 10:33:45 +00001121HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
1122 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented";
1123 DCHECK_EQ(cursor->GetBlock(), this);
1124
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001125 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1126 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001127 new_block->instructions_.first_instruction_ = cursor;
1128 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1129 instructions_.last_instruction_ = cursor->previous_;
1130 if (cursor->previous_ == nullptr) {
1131 instructions_.first_instruction_ = nullptr;
1132 } else {
1133 cursor->previous_->next_ = nullptr;
1134 cursor->previous_ = nullptr;
1135 }
1136
1137 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001138 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001139
Vladimir Marko60584552015-09-03 13:35:12 +00001140 for (HBasicBlock* successor : GetSuccessors()) {
1141 new_block->successors_.push_back(successor);
1142 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001143 }
Vladimir Marko60584552015-09-03 13:35:12 +00001144 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001145 AddSuccessor(new_block);
1146
David Brazdil56e1acc2015-06-30 15:41:36 +01001147 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001148 return new_block;
1149}
1150
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001151HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1152 DCHECK(!cursor->IsControlFlow());
1153 DCHECK_NE(instructions_.last_instruction_, cursor);
1154 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001155
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001156 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1157 new_block->instructions_.first_instruction_ = cursor->GetNext();
1158 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1159 cursor->next_->previous_ = nullptr;
1160 cursor->next_ = nullptr;
1161 instructions_.last_instruction_ = cursor;
1162
1163 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001164 for (HBasicBlock* successor : GetSuccessors()) {
1165 new_block->successors_.push_back(successor);
1166 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001167 }
Vladimir Marko60584552015-09-03 13:35:12 +00001168 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001169
Vladimir Marko60584552015-09-03 13:35:12 +00001170 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001171 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001172 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001173 }
Vladimir Marko60584552015-09-03 13:35:12 +00001174 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001175 return new_block;
1176}
1177
David Brazdilec16f792015-08-19 15:04:01 +01001178const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001179 if (EndsWithTryBoundary()) {
1180 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1181 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001182 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001183 return try_boundary;
1184 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001185 DCHECK(IsTryBlock());
1186 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001187 return nullptr;
1188 }
David Brazdilec16f792015-08-19 15:04:01 +01001189 } else if (IsTryBlock()) {
1190 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001191 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001192 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001193 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001194}
1195
1196static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1197 return block.GetPhis().IsEmpty()
1198 && !block.GetInstructions().IsEmpty()
1199 && block.GetFirstInstruction() == block.GetLastInstruction();
1200}
1201
David Brazdil46e2a392015-03-16 17:31:52 +00001202bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001203 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1204}
1205
1206bool HBasicBlock::IsSingleTryBoundary() const {
1207 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001208}
1209
David Brazdil8d5b8b22015-03-24 10:51:52 +00001210bool HBasicBlock::EndsWithControlFlowInstruction() const {
1211 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1212}
1213
David Brazdilb2bd1c52015-03-25 11:17:37 +00001214bool HBasicBlock::EndsWithIf() const {
1215 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1216}
1217
David Brazdilffee3d32015-07-06 11:48:53 +01001218bool HBasicBlock::EndsWithTryBoundary() const {
1219 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1220}
1221
David Brazdilb2bd1c52015-03-25 11:17:37 +00001222bool HBasicBlock::HasSinglePhi() const {
1223 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1224}
1225
David Brazdilffee3d32015-07-06 11:48:53 +01001226bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
Vladimir Marko60584552015-09-03 13:35:12 +00001227 if (GetBlock()->GetSuccessors().size() != other.GetBlock()->GetSuccessors().size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001228 return false;
1229 }
1230
David Brazdilb618ade2015-07-29 10:31:29 +01001231 // Exception handlers need to be stored in the same order.
1232 for (HExceptionHandlerIterator it1(*this), it2(other);
1233 !it1.Done();
1234 it1.Advance(), it2.Advance()) {
1235 DCHECK(!it2.Done());
1236 if (it1.Current() != it2.Current()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001237 return false;
1238 }
1239 }
1240 return true;
1241}
1242
David Brazdil2d7352b2015-04-20 14:52:42 +01001243size_t HInstructionList::CountSize() const {
1244 size_t size = 0;
1245 HInstruction* current = first_instruction_;
1246 for (; current != nullptr; current = current->GetNext()) {
1247 size++;
1248 }
1249 return size;
1250}
1251
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001252void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1253 for (HInstruction* current = first_instruction_;
1254 current != nullptr;
1255 current = current->GetNext()) {
1256 current->SetBlock(block);
1257 }
1258}
1259
1260void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1261 DCHECK(Contains(cursor));
1262 if (!instruction_list.IsEmpty()) {
1263 if (cursor == last_instruction_) {
1264 last_instruction_ = instruction_list.last_instruction_;
1265 } else {
1266 cursor->next_->previous_ = instruction_list.last_instruction_;
1267 }
1268 instruction_list.last_instruction_->next_ = cursor->next_;
1269 cursor->next_ = instruction_list.first_instruction_;
1270 instruction_list.first_instruction_->previous_ = cursor;
1271 }
1272}
1273
1274void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001275 if (IsEmpty()) {
1276 first_instruction_ = instruction_list.first_instruction_;
1277 last_instruction_ = instruction_list.last_instruction_;
1278 } else {
1279 AddAfter(last_instruction_, instruction_list);
1280 }
1281}
1282
David Brazdil2d7352b2015-04-20 14:52:42 +01001283void HBasicBlock::DisconnectAndDelete() {
1284 // Dominators must be removed after all the blocks they dominate. This way
1285 // a loop header is removed last, a requirement for correct loop information
1286 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001287 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001288
David Brazdil2d7352b2015-04-20 14:52:42 +01001289 // Remove the block from all loops it is included in.
1290 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1291 HLoopInformation* loop_info = it.Current();
1292 loop_info->Remove(this);
1293 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001294 // If this was the last back edge of the loop, we deliberately leave the
1295 // loop in an inconsistent state and will fail SSAChecker unless the
1296 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001297 loop_info->RemoveBackEdge(this);
1298 }
1299 }
1300
1301 // Disconnect the block from its predecessors and update their control-flow
1302 // instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001303 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001304 HInstruction* last_instruction = predecessor->GetLastInstruction();
1305 predecessor->RemoveInstruction(last_instruction);
1306 predecessor->RemoveSuccessor(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001307 if (predecessor->GetSuccessors().size() == 1u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001308 DCHECK(last_instruction->IsIf());
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001309 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001310 } else {
1311 // The predecessor has no remaining successors and therefore must be dead.
1312 // We deliberately leave it without a control-flow instruction so that the
1313 // SSAChecker fails unless it is not removed during the pass too.
Vladimir Marko60584552015-09-03 13:35:12 +00001314 DCHECK_EQ(predecessor->GetSuccessors().size(), 0u);
David Brazdil2d7352b2015-04-20 14:52:42 +01001315 }
David Brazdil46e2a392015-03-16 17:31:52 +00001316 }
Vladimir Marko60584552015-09-03 13:35:12 +00001317 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001318
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +01001319 // Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001320 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001321 // Delete this block from the list of predecessors.
1322 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001323 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001324
1325 // Check that `successor` has other predecessors, otherwise `this` is the
1326 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001327 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001328
David Brazdil2d7352b2015-04-20 14:52:42 +01001329 // Remove this block's entries in the successor's phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001330 if (successor->predecessors_.size() == 1u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001331 // The successor has just one predecessor left. Replace phis with the only
1332 // remaining input.
1333 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1334 HPhi* phi = phi_it.Current()->AsPhi();
1335 phi->ReplaceWith(phi->InputAt(1 - this_index));
1336 successor->RemovePhi(phi);
1337 }
1338 } else {
1339 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1340 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1341 }
1342 }
1343 }
Vladimir Marko60584552015-09-03 13:35:12 +00001344 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001345
1346 // Disconnect from the dominator.
1347 dominator_->RemoveDominatedBlock(this);
1348 SetDominator(nullptr);
1349
1350 // Delete from the graph. The function safely deletes remaining instructions
1351 // and updates the reverse post order.
1352 graph_->DeleteDeadBlock(this);
1353 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001354}
1355
1356void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001357 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001358 DCHECK(ContainsElement(dominated_blocks_, other));
1359 DCHECK_EQ(GetSingleSuccessor(), other);
1360 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001361 DCHECK(other->GetPhis().IsEmpty());
1362
David Brazdil2d7352b2015-04-20 14:52:42 +01001363 // Move instructions from `other` to `this`.
1364 DCHECK(EndsWithControlFlowInstruction());
1365 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001366 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001367 other->instructions_.SetBlockOfInstructions(this);
1368 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001369
David Brazdil2d7352b2015-04-20 14:52:42 +01001370 // Remove `other` from the loops it is included in.
1371 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1372 HLoopInformation* loop_info = it.Current();
1373 loop_info->Remove(other);
1374 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001375 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001376 }
1377 }
1378
1379 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001380 successors_.clear();
1381 while (!other->successors_.empty()) {
1382 HBasicBlock* successor = other->GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001383 successor->ReplacePredecessor(other, this);
1384 }
1385
David Brazdil2d7352b2015-04-20 14:52:42 +01001386 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001387 RemoveDominatedBlock(other);
1388 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1389 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001390 dominated->SetDominator(this);
1391 }
Vladimir Marko60584552015-09-03 13:35:12 +00001392 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001393 other->dominator_ = nullptr;
1394
1395 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001396 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001397
1398 // Delete `other` from the graph. The function updates reverse post order.
1399 graph_->DeleteDeadBlock(other);
1400 other->SetGraph(nullptr);
1401}
1402
1403void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1404 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001405 DCHECK(GetDominatedBlocks().empty());
1406 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001407 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001408 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001409 DCHECK(other->GetPhis().IsEmpty());
1410 DCHECK(!other->IsInLoop());
1411
1412 // Move instructions from `other` to `this`.
1413 instructions_.Add(other->GetInstructions());
1414 other->instructions_.SetBlockOfInstructions(this);
1415
1416 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001417 successors_.clear();
1418 while (!other->successors_.empty()) {
1419 HBasicBlock* successor = other->GetSuccessor(0);
David Brazdil2d7352b2015-04-20 14:52:42 +01001420 successor->ReplacePredecessor(other, this);
1421 }
1422
1423 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001424 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1425 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001426 dominated->SetDominator(this);
1427 }
Vladimir Marko60584552015-09-03 13:35:12 +00001428 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001429 other->dominator_ = nullptr;
1430 other->graph_ = nullptr;
1431}
1432
1433void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001434 while (!GetPredecessors().empty()) {
1435 HBasicBlock* predecessor = GetPredecessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001436 predecessor->ReplaceSuccessor(this, other);
1437 }
Vladimir Marko60584552015-09-03 13:35:12 +00001438 while (!GetSuccessors().empty()) {
1439 HBasicBlock* successor = GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001440 successor->ReplacePredecessor(this, other);
1441 }
Vladimir Marko60584552015-09-03 13:35:12 +00001442 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1443 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001444 }
1445 GetDominator()->ReplaceDominatedBlock(this, other);
1446 other->SetDominator(GetDominator());
1447 dominator_ = nullptr;
1448 graph_ = nullptr;
1449}
1450
1451// Create space in `blocks` for adding `number_of_new_blocks` entries
1452// starting at location `at`. Blocks after `at` are moved accordingly.
1453static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
1454 size_t number_of_new_blocks,
1455 size_t at) {
1456 size_t old_size = blocks->Size();
1457 size_t new_size = old_size + number_of_new_blocks;
1458 blocks->SetSize(new_size);
1459 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
1460 blocks->Put(j, blocks->Get(i));
1461 }
1462}
1463
David Brazdil2d7352b2015-04-20 14:52:42 +01001464void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1465 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001466 DCHECK(block->GetSuccessors().empty());
1467 DCHECK(block->GetPredecessors().empty());
1468 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001469 DCHECK(block->GetDominator() == nullptr);
1470
1471 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1472 block->RemoveInstruction(it.Current());
1473 }
1474 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1475 block->RemovePhi(it.Current()->AsPhi());
1476 }
1477
David Brazdilc7af85d2015-05-26 12:05:55 +01001478 if (block->IsExitBlock()) {
1479 exit_block_ = nullptr;
1480 }
1481
David Brazdil2d7352b2015-04-20 14:52:42 +01001482 reverse_post_order_.Delete(block);
1483 blocks_.Put(block->GetBlockId(), nullptr);
1484}
1485
Calin Juravle2e768302015-07-28 14:41:11 +00001486HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001487 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001488 // Update the environments in this graph to have the invoke's environment
1489 // as parent.
1490 {
1491 HReversePostOrderIterator it(*this);
1492 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1493 for (; !it.Done(); it.Advance()) {
1494 HBasicBlock* block = it.Current();
1495 for (HInstructionIterator instr_it(block->GetInstructions());
1496 !instr_it.Done();
1497 instr_it.Advance()) {
1498 HInstruction* current = instr_it.Current();
1499 if (current->NeedsEnvironment()) {
1500 current->GetEnvironment()->SetAndCopyParentChain(
1501 outer_graph->GetArena(), invoke->GetEnvironment());
1502 }
1503 }
1504 }
1505 }
1506 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1507 if (HasBoundsChecks()) {
1508 outer_graph->SetHasBoundsChecks(true);
1509 }
1510
Calin Juravle2e768302015-07-28 14:41:11 +00001511 HInstruction* return_value = nullptr;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001512 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001513 // Simple case of an entry block, a body block, and an exit block.
1514 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001515 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001516 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
1517 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001518 DCHECK(!body->IsExitBlock());
1519 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001520
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001521 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1522 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001523
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001524 // Replace the invoke with the return value of the inlined graph.
1525 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001526 return_value = last->InputAt(0);
1527 invoke->ReplaceWith(return_value);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001528 } else {
1529 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001530 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001531
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001532 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001533 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001534 // Need to inline multiple blocks. We split `invoke`'s block
1535 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001536 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001537 // with the second half.
1538 ArenaAllocator* allocator = outer_graph->GetArena();
1539 HBasicBlock* at = invoke->GetBlock();
1540 HBasicBlock* to = at->SplitAfter(invoke);
1541
Vladimir Marko60584552015-09-03 13:35:12 +00001542 HBasicBlock* first = entry_block_->GetSuccessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001543 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001544 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001545 exit_block_->ReplaceWith(to);
1546
1547 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001548 // to not `HReturn` but `HGoto` instead.
Vladimir Marko60584552015-09-03 13:35:12 +00001549 bool returns_void = to->GetPredecessor(0)->GetLastInstruction()->IsReturnVoid();
1550 if (to->GetPredecessors().size() == 1) {
1551 HBasicBlock* predecessor = to->GetPredecessor(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001552 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001553 if (!returns_void) {
1554 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001555 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001556 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001557 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001558 } else {
1559 if (!returns_void) {
1560 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001561 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001562 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001563 to->AddPhi(return_value->AsPhi());
1564 }
Vladimir Marko60584552015-09-03 13:35:12 +00001565 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001566 HInstruction* last = predecessor->GetLastInstruction();
1567 if (!returns_void) {
1568 return_value->AsPhi()->AddInput(last->InputAt(0));
1569 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001570 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001571 predecessor->RemoveInstruction(last);
1572 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001573 }
1574
1575 if (return_value != nullptr) {
1576 invoke->ReplaceWith(return_value);
1577 }
1578
1579 // Update the meta information surrounding blocks:
1580 // (1) the graph they are now in,
1581 // (2) the reverse post order of that graph,
1582 // (3) the potential loop information they are now in.
1583
1584 // We don't add the entry block, the exit block, and the first block, which
1585 // has been merged with `at`.
1586 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1587
1588 // We add the `to` block.
1589 static constexpr int kNumberOfNewBlocksInCaller = 1;
1590 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1591 + kNumberOfNewBlocksInCaller;
1592
1593 // Find the location of `at` in the outer graph's reverse post order. The new
1594 // blocks will be added after it.
1595 size_t index_of_at = 0;
1596 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1597 index_of_at++;
1598 }
1599 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1600
1601 // Do a reverse post order of the blocks in the callee and do (1), (2),
1602 // and (3) to the blocks that apply.
1603 HLoopInformation* info = at->GetLoopInformation();
1604 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1605 HBasicBlock* current = it.Current();
1606 if (current != exit_block_ && current != entry_block_ && current != first) {
1607 DCHECK(!current->IsInLoop());
1608 DCHECK(current->GetGraph() == this);
1609 current->SetGraph(outer_graph);
1610 outer_graph->AddBlock(current);
1611 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1612 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001613 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001614 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1615 loop_it.Current()->Add(current);
1616 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001617 }
1618 }
1619 }
1620
1621 // Do (1), (2), and (3) to `to`.
1622 to->SetGraph(outer_graph);
1623 outer_graph->AddBlock(to);
1624 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1625 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001626 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001627 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1628 loop_it.Current()->Add(to);
1629 }
David Brazdil46e2a392015-03-16 17:31:52 +00001630 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001631 // Only `to` can become a back edge, as the inlined blocks
1632 // are predecessors of `to`.
1633 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001634 }
1635 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001636 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001637
David Brazdil05144f42015-04-16 15:18:00 +01001638 // Update the next instruction id of the outer graph, so that instructions
1639 // added later get bigger ids than those in the inner graph.
1640 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1641
1642 // Walk over the entry block and:
1643 // - Move constants from the entry block to the outer_graph's entry block,
1644 // - Replace HParameterValue instructions with their real value.
1645 // - Remove suspend checks, that hold an environment.
1646 // We must do this after the other blocks have been inlined, otherwise ids of
1647 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001648 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001649 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1650 HInstruction* current = it.Current();
1651 if (current->IsNullConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001652 current->ReplaceWith(outer_graph->GetNullConstant(current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001653 } else if (current->IsIntConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001654 current->ReplaceWith(outer_graph->GetIntConstant(
1655 current->AsIntConstant()->GetValue(), current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001656 } else if (current->IsLongConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001657 current->ReplaceWith(outer_graph->GetLongConstant(
1658 current->AsLongConstant()->GetValue(), current->GetDexPc()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001659 } else if (current->IsFloatConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001660 current->ReplaceWith(outer_graph->GetFloatConstant(
1661 current->AsFloatConstant()->GetValue(), current->GetDexPc()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001662 } else if (current->IsDoubleConstant()) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001663 current->ReplaceWith(outer_graph->GetDoubleConstant(
1664 current->AsDoubleConstant()->GetValue(), current->GetDexPc()));
David Brazdil05144f42015-04-16 15:18:00 +01001665 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001666 if (kIsDebugBuild
1667 && invoke->IsInvokeStaticOrDirect()
1668 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1669 // Ensure we do not use the last input of `invoke`, as it
1670 // contains a clinit check which is not an actual argument.
1671 size_t last_input_index = invoke->InputCount() - 1;
1672 DCHECK(parameter_index != last_input_index);
1673 }
David Brazdil05144f42015-04-16 15:18:00 +01001674 current->ReplaceWith(invoke->InputAt(parameter_index++));
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001675 } else if (current->IsCurrentMethod()) {
1676 current->ReplaceWith(outer_graph->GetCurrentMethod());
David Brazdil05144f42015-04-16 15:18:00 +01001677 } else {
1678 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1679 entry_block_->RemoveInstruction(current);
1680 }
1681 }
1682
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001683 // Finally remove the invoke from the caller.
1684 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00001685
1686 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001687}
1688
Mingyao Yang3584bce2015-05-19 16:01:59 -07001689/*
1690 * Loop will be transformed to:
1691 * old_pre_header
1692 * |
1693 * if_block
1694 * / \
1695 * dummy_block deopt_block
1696 * \ /
1697 * new_pre_header
1698 * |
1699 * header
1700 */
1701void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1702 DCHECK(header->IsLoopHeader());
1703 HBasicBlock* pre_header = header->GetDominator();
1704
1705 // Need this to avoid critical edge.
1706 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1707 // Need this to avoid critical edge.
1708 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1709 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1710 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1711 AddBlock(if_block);
1712 AddBlock(dummy_block);
1713 AddBlock(deopt_block);
1714 AddBlock(new_pre_header);
1715
1716 header->ReplacePredecessor(pre_header, new_pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001717 pre_header->successors_.clear();
1718 pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07001719
1720 pre_header->AddSuccessor(if_block);
1721 if_block->AddSuccessor(dummy_block); // True successor
1722 if_block->AddSuccessor(deopt_block); // False successor
1723 dummy_block->AddSuccessor(new_pre_header);
1724 deopt_block->AddSuccessor(new_pre_header);
1725
Vladimir Marko60584552015-09-03 13:35:12 +00001726 pre_header->dominated_blocks_.push_back(if_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001727 if_block->SetDominator(pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001728 if_block->dominated_blocks_.push_back(dummy_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001729 dummy_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001730 if_block->dominated_blocks_.push_back(deopt_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001731 deopt_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001732 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001733 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001734 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001735 header->SetDominator(new_pre_header);
1736
1737 size_t index_of_header = 0;
1738 while (reverse_post_order_.Get(index_of_header) != header) {
1739 index_of_header++;
1740 }
1741 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
1742 reverse_post_order_.Put(index_of_header++, if_block);
1743 reverse_post_order_.Put(index_of_header++, dummy_block);
1744 reverse_post_order_.Put(index_of_header++, deopt_block);
1745 reverse_post_order_.Put(index_of_header++, new_pre_header);
1746
1747 HLoopInformation* info = pre_header->GetLoopInformation();
1748 if (info != nullptr) {
1749 if_block->SetLoopInformation(info);
1750 dummy_block->SetLoopInformation(info);
1751 deopt_block->SetLoopInformation(info);
1752 new_pre_header->SetLoopInformation(info);
1753 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1754 !loop_it.Done();
1755 loop_it.Advance()) {
1756 loop_it.Current()->Add(if_block);
1757 loop_it.Current()->Add(dummy_block);
1758 loop_it.Current()->Add(deopt_block);
1759 loop_it.Current()->Add(new_pre_header);
1760 }
1761 }
1762}
1763
Calin Juravle2e768302015-07-28 14:41:11 +00001764void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
1765 if (kIsDebugBuild) {
1766 DCHECK_EQ(GetType(), Primitive::kPrimNot);
1767 ScopedObjectAccess soa(Thread::Current());
1768 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
1769 if (IsBoundType()) {
1770 // Having the test here spares us from making the method virtual just for
1771 // the sake of a DCHECK.
1772 ReferenceTypeInfo upper_bound_rti = AsBoundType()->GetUpperBound();
1773 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
1774 << " upper_bound_rti: " << upper_bound_rti
1775 << " rti: " << rti;
1776 DCHECK(!upper_bound_rti.GetTypeHandle()->IsFinal() || rti.IsExact());
1777 }
1778 }
1779 reference_type_info_ = rti;
1780}
1781
1782ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
1783
1784ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
1785 : type_handle_(type_handle), is_exact_(is_exact) {
1786 if (kIsDebugBuild) {
1787 ScopedObjectAccess soa(Thread::Current());
1788 DCHECK(IsValidHandle(type_handle));
1789 }
1790}
1791
Calin Juravleacf735c2015-02-12 15:25:22 +00001792std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1793 ScopedObjectAccess soa(Thread::Current());
1794 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00001795 << " is_valid=" << rhs.IsValid()
1796 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00001797 << " is_exact=" << rhs.IsExact()
1798 << " ]";
1799 return os;
1800}
1801
Mark Mendellc4701932015-04-10 13:18:51 -04001802bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
1803 // For now, assume that instructions in different blocks may use the
1804 // environment.
1805 // TODO: Use the control flow to decide if this is true.
1806 if (GetBlock() != other->GetBlock()) {
1807 return true;
1808 }
1809
1810 // We know that we are in the same block. Walk from 'this' to 'other',
1811 // checking to see if there is any instruction with an environment.
1812 HInstruction* current = this;
1813 for (; current != other && current != nullptr; current = current->GetNext()) {
1814 // This is a conservative check, as the instruction result may not be in
1815 // the referenced environment.
1816 if (current->HasEnvironment()) {
1817 return true;
1818 }
1819 }
1820
1821 // We should have been called with 'this' before 'other' in the block.
1822 // Just confirm this.
1823 DCHECK(current != nullptr);
1824 return false;
1825}
1826
1827void HInstruction::RemoveEnvironmentUsers() {
1828 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
1829 HUseListNode<HEnvironment*>* user_node = use_it.Current();
1830 HEnvironment* user = user_node->GetUser();
1831 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
1832 }
1833 env_uses_.Clear();
1834}
1835
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001836} // namespace art