blob: 0a39ff31bf3d04f92e60f8212da862e3ab3f3fb6 [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"
Vladimir Marko391d01f2015-11-06 11:02:08 +000020#include "common_dominator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010021#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010022#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010023#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010024#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010025#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010026#include "mirror/class-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000027#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000028
29namespace art {
30
31void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010032 block->SetBlockId(blocks_.size());
33 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000034}
35
Nicolas Geoffray804d0932014-05-02 08:46:00 +010036void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010037 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
38 DCHECK_EQ(visited->GetHighestBitSet(), -1);
39
40 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010041 ArenaBitVector visiting(arena_, blocks_.size(), false);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010042 // Number of successors visited from a given node, indexed by block id.
43 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
44 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
45 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
46 constexpr size_t kDefaultWorklistSize = 8;
47 worklist.reserve(kDefaultWorklistSize);
48 visited->SetBit(entry_block_->GetBlockId());
49 visiting.SetBit(entry_block_->GetBlockId());
50 worklist.push_back(entry_block_);
51
52 while (!worklist.empty()) {
53 HBasicBlock* current = worklist.back();
54 uint32_t current_id = current->GetBlockId();
55 if (successors_visited[current_id] == current->GetSuccessors().size()) {
56 visiting.ClearBit(current_id);
57 worklist.pop_back();
58 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010059 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
60 uint32_t successor_id = successor->GetBlockId();
61 if (visiting.IsBitSet(successor_id)) {
62 DCHECK(ContainsElement(worklist, successor));
63 successor->AddBackEdge(current);
64 } else if (!visited->IsBitSet(successor_id)) {
65 visited->SetBit(successor_id);
66 visiting.SetBit(successor_id);
67 worklist.push_back(successor);
68 }
69 }
70 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000071}
72
Roland Levillainfc600dc2014-12-02 17:16:31 +000073static void RemoveAsUser(HInstruction* instruction) {
74 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000075 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000076 }
77
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010078 for (HEnvironment* environment = instruction->GetEnvironment();
79 environment != nullptr;
80 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000081 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000082 if (environment->GetInstructionAt(i) != nullptr) {
83 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000084 }
85 }
86 }
87}
88
89void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010090 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000091 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010092 HBasicBlock* block = blocks_[i];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010093 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000094 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
95 RemoveAsUser(it.Current());
96 }
97 }
98 }
99}
100
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100101void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100102 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000103 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100104 HBasicBlock* block = blocks_[i];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100105 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000106 for (HBasicBlock* successor : block->GetSuccessors()) {
107 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000108 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100109 // Remove the block from the list of blocks, so that further analyses
110 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100111 blocks_[i] = nullptr;
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000112 }
113 }
114}
115
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000116void HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100117 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
118 // edges. This invariant simplifies building SSA form because Phis cannot
119 // collect both normal- and exceptional-flow values at the same time.
120 SimplifyCatchBlocks();
121
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100122 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000123
David Brazdilffee3d32015-07-06 11:48:53 +0100124 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000125 FindBackEdges(&visited);
126
David Brazdilffee3d32015-07-06 11:48:53 +0100127 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000128 // the initial DFS as users from other instructions, so that
129 // users can be safely removed before uses later.
130 RemoveInstructionsAsUsersFromDeadBlocks(visited);
131
David Brazdilffee3d32015-07-06 11:48:53 +0100132 // (4) Remove blocks not visited during the initial DFS.
Roland Levillainfc600dc2014-12-02 17:16:31 +0000133 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000134 // predecessors list of live blocks.
135 RemoveDeadBlocks(visited);
136
David Brazdilffee3d32015-07-06 11:48:53 +0100137 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100138 // dominators and the reverse post order.
139 SimplifyCFG();
140
David Brazdilffee3d32015-07-06 11:48:53 +0100141 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100142 ComputeDominanceInformation();
143}
144
145void HGraph::ClearDominanceInformation() {
146 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
147 it.Current()->ClearDominanceInformation();
148 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100149 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100150}
151
152void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000153 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100154 dominator_ = nullptr;
155}
156
157void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100158 DCHECK(reverse_post_order_.empty());
159 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100160 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100161
162 // Number of visits of a given node, indexed by block id.
163 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
164 // Number of successors visited from a given node, indexed by block id.
165 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
166 // Nodes for which we need to visit successors.
167 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
168 constexpr size_t kDefaultWorklistSize = 8;
169 worklist.reserve(kDefaultWorklistSize);
170 worklist.push_back(entry_block_);
171
172 while (!worklist.empty()) {
173 HBasicBlock* current = worklist.back();
174 uint32_t current_id = current->GetBlockId();
175 if (successors_visited[current_id] == current->GetSuccessors().size()) {
176 worklist.pop_back();
177 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100178 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
179
180 if (successor->GetDominator() == nullptr) {
181 successor->SetDominator(current);
182 } else {
Vladimir Marko391d01f2015-11-06 11:02:08 +0000183 // The CommonDominator can work for multiple blocks as long as the
184 // domination information doesn't change. However, since we're changing
185 // that information here, we can use the finder only for pairs of blocks.
186 successor->SetDominator(CommonDominator::ForPair(successor->GetDominator(), current));
Vladimir Markod76d1392015-09-23 16:07:14 +0100187 }
188
189 // Once all the forward edges have been visited, we know the immediate
190 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100191 if (++visits[successor->GetBlockId()] ==
192 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
193 successor->GetDominator()->AddDominatedBlock(successor);
194 reverse_post_order_.push_back(successor);
195 worklist.push_back(successor);
196 }
197 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000198 }
199}
200
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000201void HGraph::TransformToSsa() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100202 DCHECK(!reverse_post_order_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100203 SsaBuilder ssa_builder(this);
204 ssa_builder.BuildSsa();
205}
206
David Brazdilfc6a86a2015-06-26 10:33:45 +0000207HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000208 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
209 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000210 // Use `InsertBetween` to ensure the predecessor index and successor index of
211 // `block` and `successor` are preserved.
212 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000213 return new_block;
214}
215
216void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
217 // Insert a new node between `block` and `successor` to split the
218 // critical edge.
219 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600220 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100221 if (successor->IsLoopHeader()) {
222 // If we split at a back edge boundary, make the new block the back edge.
223 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000224 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100225 info->RemoveBackEdge(block);
226 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100227 }
228 }
229}
230
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100231void HGraph::SimplifyLoop(HBasicBlock* header) {
232 HLoopInformation* info = header->GetLoopInformation();
233
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100234 // Make sure the loop has only one pre header. This simplifies SSA building by having
235 // to just look at the pre header to know which locals are initialized at entry of the
236 // loop.
Vladimir Marko60584552015-09-03 13:35:12 +0000237 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100238 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100239 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100240 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600241 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100242
Vladimir Marko60584552015-09-03 13:35:12 +0000243 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100244 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100245 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100246 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100247 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100248 }
249 }
250 pre_header->AddSuccessor(header);
251 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100252
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100253 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100254 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
255 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000256 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100257 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100258 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000259 header->predecessors_[pred] = to_swap;
260 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100261 break;
262 }
263 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100264 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100265
266 // Place the suspend check at the beginning of the header, so that live registers
267 // will be known when allocating registers. Note that code generation can still
268 // generate the suspend check at the back edge, but needs to be careful with
269 // loop phi spill slots (which are not written to at back edge).
270 HInstruction* first_instruction = header->GetFirstInstruction();
271 if (!first_instruction->IsSuspendCheck()) {
272 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
273 header->InsertInstructionBefore(check, first_instruction);
274 first_instruction = check;
275 }
276 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100277}
278
David Brazdilffee3d32015-07-06 11:48:53 +0100279static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100280 HBasicBlock* predecessor = block.GetPredecessors()[pred_idx];
David Brazdilffee3d32015-07-06 11:48:53 +0100281 if (!predecessor->EndsWithTryBoundary()) {
282 // Only edges from HTryBoundary can be exceptional.
283 return false;
284 }
285 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
286 if (try_boundary->GetNormalFlowSuccessor() == &block) {
287 // This block is the normal-flow successor of `try_boundary`, but it could
288 // also be one of its exception handlers if catch blocks have not been
289 // simplified yet. Predecessors are unordered, so we will consider the first
290 // occurrence to be the normal edge and a possible second occurrence to be
291 // the exceptional edge.
292 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
293 } else {
294 // This is not the normal-flow successor of `try_boundary`, hence it must be
295 // one of its exception handlers.
296 DCHECK(try_boundary->HasExceptionHandler(block));
297 return true;
298 }
299}
300
301void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100302 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
303 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
304 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
305 HBasicBlock* catch_block = blocks_[block_id];
David Brazdilffee3d32015-07-06 11:48:53 +0100306 if (!catch_block->IsCatchBlock()) {
307 continue;
308 }
309
310 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000311 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100312 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
313 exceptional_predecessors_only = false;
314 break;
315 }
316 }
317
318 if (!exceptional_predecessors_only) {
319 // Catch block has normal-flow predecessors and needs to be simplified.
320 // Splitting the block before its first instruction moves all its
321 // instructions into `normal_block` and links the two blocks with a Goto.
322 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
323 // leaving `catch_block` with the exceptional edges only.
David Brazdil9bc43612015-11-05 21:25:24 +0000324 //
David Brazdilffee3d32015-07-06 11:48:53 +0100325 // Note that catch blocks with normal-flow predecessors cannot begin with
David Brazdil9bc43612015-11-05 21:25:24 +0000326 // a move-exception instruction, as guaranteed by the verifier. However,
327 // trivially dead predecessors are ignored by the verifier and such code
328 // has not been removed at this stage. We therefore ignore the assumption
329 // and rely on GraphChecker to enforce it after initial DCE is run (b/25492628).
330 HBasicBlock* normal_block = catch_block->SplitCatchBlockAfterMoveException();
331 if (normal_block == nullptr) {
332 // Catch block is either empty or only contains a move-exception. It must
333 // therefore be dead and will be removed during initial DCE. Do nothing.
334 DCHECK(!catch_block->EndsWithControlFlowInstruction());
335 } else {
336 // Catch block was split. Re-link normal-flow edges to the new block.
337 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
338 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
339 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
340 --j;
341 }
David Brazdilffee3d32015-07-06 11:48:53 +0100342 }
343 }
344 }
345 }
346}
347
348void HGraph::ComputeTryBlockInformation() {
349 // Iterate in reverse post order to propagate try membership information from
350 // predecessors to their successors.
351 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
352 HBasicBlock* block = it.Current();
353 if (block->IsEntryBlock() || block->IsCatchBlock()) {
354 // Catch blocks after simplification have only exceptional predecessors
355 // and hence are never in tries.
356 continue;
357 }
358
359 // Infer try membership from the first predecessor. Having simplified loops,
360 // the first predecessor can never be a back edge and therefore it must have
361 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100362 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100363 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100364 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000365 if (try_entry != nullptr &&
366 (block->GetTryCatchInformation() == nullptr ||
367 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
368 // We are either setting try block membership for the first time or it
369 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100370 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
371 }
David Brazdilffee3d32015-07-06 11:48:53 +0100372 }
373}
374
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100375void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000376// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100377 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000378 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100379 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
380 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
381 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
382 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100383 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000384 if (block->GetSuccessors().size() > 1) {
385 // Only split normal-flow edges. We cannot split exceptional edges as they
386 // are synthesized (approximate real control flow), and we do not need to
387 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000388 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
389 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
390 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100391 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000392 if (successor == exit_block_) {
393 // Throw->TryBoundary->Exit. Special case which we do not want to split
394 // because Goto->Exit is not allowed.
395 DCHECK(block->IsSingleTryBoundary());
396 DCHECK(block->GetSinglePredecessor()->GetLastInstruction()->IsThrow());
397 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100398 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000399 // SplitCriticalEdge could have invalidated the `normal_successors`
400 // ArrayRef. We must re-acquire it.
401 normal_successors = block->GetNormalSuccessors();
402 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
403 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100404 }
405 }
406 }
407 if (block->IsLoopHeader()) {
408 SimplifyLoop(block);
409 }
410 }
411}
412
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000413bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100414 // Order does not matter.
415 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
416 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100417 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100418 if (block->IsCatchBlock()) {
419 // TODO: Dealing with exceptional back edges could be tricky because
420 // they only approximate the real control flow. Bail out for now.
421 return false;
422 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100423 HLoopInformation* info = block->GetLoopInformation();
424 if (!info->Populate()) {
425 // Abort if the loop is non natural. We currently bailout in such cases.
426 return false;
427 }
428 }
429 }
430 return true;
431}
432
David Brazdil8d5b8b22015-03-24 10:51:52 +0000433void HGraph::InsertConstant(HConstant* constant) {
434 // New constants are inserted before the final control-flow instruction
435 // of the graph, or at its end if called from the graph builder.
436 if (entry_block_->EndsWithControlFlowInstruction()) {
437 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000438 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000439 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000440 }
441}
442
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600443HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100444 // For simplicity, don't bother reviving the cached null constant if it is
445 // not null and not in a block. Otherwise, we need to clear the instruction
446 // id and/or any invariants the graph is assuming when adding new instructions.
447 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600448 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000449 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000450 }
451 return cached_null_constant_;
452}
453
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100454HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100455 // For simplicity, don't bother reviving the cached current method if it is
456 // not null and not in a block. Otherwise, we need to clear the instruction
457 // id and/or any invariants the graph is assuming when adding new instructions.
458 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700459 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600460 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
461 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100462 if (entry_block_->GetFirstInstruction() == nullptr) {
463 entry_block_->AddInstruction(cached_current_method_);
464 } else {
465 entry_block_->InsertInstructionBefore(
466 cached_current_method_, entry_block_->GetFirstInstruction());
467 }
468 }
469 return cached_current_method_;
470}
471
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600472HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000473 switch (type) {
474 case Primitive::Type::kPrimBoolean:
475 DCHECK(IsUint<1>(value));
476 FALLTHROUGH_INTENDED;
477 case Primitive::Type::kPrimByte:
478 case Primitive::Type::kPrimChar:
479 case Primitive::Type::kPrimShort:
480 case Primitive::Type::kPrimInt:
481 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600482 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000483
484 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600485 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000486
487 default:
488 LOG(FATAL) << "Unsupported constant type";
489 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000490 }
David Brazdil46e2a392015-03-16 17:31:52 +0000491}
492
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000493void HGraph::CacheFloatConstant(HFloatConstant* constant) {
494 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
495 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
496 cached_float_constants_.Overwrite(value, constant);
497}
498
499void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
500 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
501 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
502 cached_double_constants_.Overwrite(value, constant);
503}
504
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000505void HLoopInformation::Add(HBasicBlock* block) {
506 blocks_.SetBit(block->GetBlockId());
507}
508
David Brazdil46e2a392015-03-16 17:31:52 +0000509void HLoopInformation::Remove(HBasicBlock* block) {
510 blocks_.ClearBit(block->GetBlockId());
511}
512
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100513void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
514 if (blocks_.IsBitSet(block->GetBlockId())) {
515 return;
516 }
517
518 blocks_.SetBit(block->GetBlockId());
519 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000520 for (HBasicBlock* predecessor : block->GetPredecessors()) {
521 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100522 }
523}
524
525bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100526 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100527 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100528 DCHECK(back_edge->GetDominator() != nullptr);
529 if (!header_->Dominates(back_edge)) {
530 // This loop is not natural. Do not bother going further.
531 return false;
532 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100533
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100534 // Populate this loop: starting with the back edge, recursively add predecessors
535 // that are not already part of that loop. Set the header as part of the loop
536 // to end the recursion.
537 // This is a recursive implementation of the algorithm described in
538 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
539 blocks_.SetBit(header_->GetBlockId());
540 PopulateRecursive(back_edge);
541 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100542 return true;
543}
544
David Brazdila4b8c212015-05-07 09:59:30 +0100545void HLoopInformation::Update() {
546 HGraph* graph = header_->GetGraph();
547 for (uint32_t id : blocks_.Indexes()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100548 HBasicBlock* block = graph->GetBlocks()[id];
David Brazdila4b8c212015-05-07 09:59:30 +0100549 // Reset loop information of non-header blocks inside the loop, except
550 // members of inner nested loops because those should already have been
551 // updated by their own LoopInformation.
552 if (block->GetLoopInformation() == this && block != header_) {
553 block->SetLoopInformation(nullptr);
554 }
555 }
556 blocks_.ClearAllBits();
557
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100558 if (back_edges_.empty()) {
David Brazdila4b8c212015-05-07 09:59:30 +0100559 // The loop has been dismantled, delete its suspend check and remove info
560 // from the header.
561 DCHECK(HasSuspendCheck());
562 header_->RemoveInstruction(suspend_check_);
563 header_->SetLoopInformation(nullptr);
564 header_ = nullptr;
565 suspend_check_ = nullptr;
566 } else {
567 if (kIsDebugBuild) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100568 for (HBasicBlock* back_edge : back_edges_) {
569 DCHECK(header_->Dominates(back_edge));
David Brazdila4b8c212015-05-07 09:59:30 +0100570 }
571 }
572 // This loop still has reachable back edges. Repopulate the list of blocks.
573 bool populate_successful = Populate();
574 DCHECK(populate_successful);
575 }
576}
577
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100578HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100579 return header_->GetDominator();
580}
581
582bool HLoopInformation::Contains(const HBasicBlock& block) const {
583 return blocks_.IsBitSet(block.GetBlockId());
584}
585
586bool HLoopInformation::IsIn(const HLoopInformation& other) const {
587 return other.blocks_.IsBitSet(header_->GetBlockId());
588}
589
Aart Bik73f1f3b2015-10-28 15:28:08 -0700590bool HLoopInformation::IsLoopInvariant(HInstruction* instruction, bool must_dominate) const {
591 HLoopInformation* other_loop = instruction->GetBlock()->GetLoopInformation();
592 if (other_loop != this && (other_loop == nullptr || !other_loop->IsIn(*this))) {
593 if (must_dominate) {
594 return instruction->GetBlock()->Dominates(GetHeader());
595 }
596 return true;
597 }
598 return false;
599}
600
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100601size_t HLoopInformation::GetLifetimeEnd() const {
602 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100603 for (HBasicBlock* back_edge : GetBackEdges()) {
604 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100605 }
606 return last_position;
607}
608
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100609bool HBasicBlock::Dominates(HBasicBlock* other) const {
610 // Walk up the dominator tree from `other`, to find out if `this`
611 // is an ancestor.
612 HBasicBlock* current = other;
613 while (current != nullptr) {
614 if (current == this) {
615 return true;
616 }
617 current = current->GetDominator();
618 }
619 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100620}
621
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100622static void UpdateInputsUsers(HInstruction* instruction) {
623 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
624 instruction->InputAt(i)->AddUseAt(instruction, i);
625 }
626 // Environment should be created later.
627 DCHECK(!instruction->HasEnvironment());
628}
629
Roland Levillainccc07a92014-09-16 14:48:16 +0100630void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
631 HInstruction* replacement) {
632 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400633 if (initial->IsControlFlow()) {
634 // We can only replace a control flow instruction with another control flow instruction.
635 DCHECK(replacement->IsControlFlow());
636 DCHECK_EQ(replacement->GetId(), -1);
637 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
638 DCHECK_EQ(initial->GetBlock(), this);
639 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
640 DCHECK(initial->GetUses().IsEmpty());
641 DCHECK(initial->GetEnvUses().IsEmpty());
642 replacement->SetBlock(this);
643 replacement->SetId(GetGraph()->GetNextInstructionId());
644 instructions_.InsertInstructionBefore(replacement, initial);
645 UpdateInputsUsers(replacement);
646 } else {
647 InsertInstructionBefore(replacement, initial);
648 initial->ReplaceWith(replacement);
649 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100650 RemoveInstruction(initial);
651}
652
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100653static void Add(HInstructionList* instruction_list,
654 HBasicBlock* block,
655 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000656 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000657 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100658 instruction->SetBlock(block);
659 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100660 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100661 instruction_list->AddInstruction(instruction);
662}
663
664void HBasicBlock::AddInstruction(HInstruction* instruction) {
665 Add(&instructions_, this, instruction);
666}
667
668void HBasicBlock::AddPhi(HPhi* phi) {
669 Add(&phis_, this, phi);
670}
671
David Brazdilc3d743f2015-04-22 13:40:50 +0100672void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
673 DCHECK(!cursor->IsPhi());
674 DCHECK(!instruction->IsPhi());
675 DCHECK_EQ(instruction->GetId(), -1);
676 DCHECK_NE(cursor->GetId(), -1);
677 DCHECK_EQ(cursor->GetBlock(), this);
678 DCHECK(!instruction->IsControlFlow());
679 instruction->SetBlock(this);
680 instruction->SetId(GetGraph()->GetNextInstructionId());
681 UpdateInputsUsers(instruction);
682 instructions_.InsertInstructionBefore(instruction, cursor);
683}
684
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100685void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
686 DCHECK(!cursor->IsPhi());
687 DCHECK(!instruction->IsPhi());
688 DCHECK_EQ(instruction->GetId(), -1);
689 DCHECK_NE(cursor->GetId(), -1);
690 DCHECK_EQ(cursor->GetBlock(), this);
691 DCHECK(!instruction->IsControlFlow());
692 DCHECK(!cursor->IsControlFlow());
693 instruction->SetBlock(this);
694 instruction->SetId(GetGraph()->GetNextInstructionId());
695 UpdateInputsUsers(instruction);
696 instructions_.InsertInstructionAfter(instruction, cursor);
697}
698
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100699void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
700 DCHECK_EQ(phi->GetId(), -1);
701 DCHECK_NE(cursor->GetId(), -1);
702 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100703 phi->SetBlock(this);
704 phi->SetId(GetGraph()->GetNextInstructionId());
705 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100706 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100707}
708
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100709static void Remove(HInstructionList* instruction_list,
710 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000711 HInstruction* instruction,
712 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100713 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100714 instruction->SetBlock(nullptr);
715 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000716 if (ensure_safety) {
717 DCHECK(instruction->GetUses().IsEmpty());
718 DCHECK(instruction->GetEnvUses().IsEmpty());
719 RemoveAsUser(instruction);
720 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100721}
722
David Brazdil1abb4192015-02-17 18:33:36 +0000723void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100724 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000725 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100726}
727
David Brazdil1abb4192015-02-17 18:33:36 +0000728void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
729 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100730}
731
David Brazdilc7508e92015-04-27 13:28:57 +0100732void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
733 if (instruction->IsPhi()) {
734 RemovePhi(instruction->AsPhi(), ensure_safety);
735 } else {
736 RemoveInstruction(instruction, ensure_safety);
737 }
738}
739
Vladimir Marko71bf8092015-09-15 15:33:14 +0100740void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
741 for (size_t i = 0; i < locals.size(); i++) {
742 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100743 SetRawEnvAt(i, instruction);
744 if (instruction != nullptr) {
745 instruction->AddEnvUseAt(this, i);
746 }
747 }
748}
749
David Brazdiled596192015-01-23 10:39:45 +0000750void HEnvironment::CopyFrom(HEnvironment* env) {
751 for (size_t i = 0; i < env->Size(); i++) {
752 HInstruction* instruction = env->GetInstructionAt(i);
753 SetRawEnvAt(i, instruction);
754 if (instruction != nullptr) {
755 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100756 }
David Brazdiled596192015-01-23 10:39:45 +0000757 }
758}
759
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700760void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
761 HBasicBlock* loop_header) {
762 DCHECK(loop_header->IsLoopHeader());
763 for (size_t i = 0; i < env->Size(); i++) {
764 HInstruction* instruction = env->GetInstructionAt(i);
765 SetRawEnvAt(i, instruction);
766 if (instruction == nullptr) {
767 continue;
768 }
769 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
770 // At the end of the loop pre-header, the corresponding value for instruction
771 // is the first input of the phi.
772 HInstruction* initial = instruction->AsPhi()->InputAt(0);
773 DCHECK(initial->GetBlock()->Dominates(loop_header));
774 SetRawEnvAt(i, initial);
775 initial->AddEnvUseAt(this, i);
776 } else {
777 instruction->AddEnvUseAt(this, i);
778 }
779 }
780}
781
David Brazdil1abb4192015-02-17 18:33:36 +0000782void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100783 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000784 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100785}
786
Calin Juravle77520bc2015-01-12 18:45:46 +0000787HInstruction* HInstruction::GetNextDisregardingMoves() const {
788 HInstruction* next = GetNext();
789 while (next != nullptr && next->IsParallelMove()) {
790 next = next->GetNext();
791 }
792 return next;
793}
794
795HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
796 HInstruction* previous = GetPrevious();
797 while (previous != nullptr && previous->IsParallelMove()) {
798 previous = previous->GetPrevious();
799 }
800 return previous;
801}
802
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100803void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000804 if (first_instruction_ == nullptr) {
805 DCHECK(last_instruction_ == nullptr);
806 first_instruction_ = last_instruction_ = instruction;
807 } else {
808 last_instruction_->next_ = instruction;
809 instruction->previous_ = last_instruction_;
810 last_instruction_ = instruction;
811 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000812}
813
David Brazdilc3d743f2015-04-22 13:40:50 +0100814void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
815 DCHECK(Contains(cursor));
816 if (cursor == first_instruction_) {
817 cursor->previous_ = instruction;
818 instruction->next_ = cursor;
819 first_instruction_ = instruction;
820 } else {
821 instruction->previous_ = cursor->previous_;
822 instruction->next_ = cursor;
823 cursor->previous_ = instruction;
824 instruction->previous_->next_ = instruction;
825 }
826}
827
828void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
829 DCHECK(Contains(cursor));
830 if (cursor == last_instruction_) {
831 cursor->next_ = instruction;
832 instruction->previous_ = cursor;
833 last_instruction_ = instruction;
834 } else {
835 instruction->next_ = cursor->next_;
836 instruction->previous_ = cursor;
837 cursor->next_ = instruction;
838 instruction->next_->previous_ = instruction;
839 }
840}
841
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100842void HInstructionList::RemoveInstruction(HInstruction* instruction) {
843 if (instruction->previous_ != nullptr) {
844 instruction->previous_->next_ = instruction->next_;
845 }
846 if (instruction->next_ != nullptr) {
847 instruction->next_->previous_ = instruction->previous_;
848 }
849 if (instruction == first_instruction_) {
850 first_instruction_ = instruction->next_;
851 }
852 if (instruction == last_instruction_) {
853 last_instruction_ = instruction->previous_;
854 }
855}
856
Roland Levillain6b469232014-09-25 10:10:38 +0100857bool HInstructionList::Contains(HInstruction* instruction) const {
858 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
859 if (it.Current() == instruction) {
860 return true;
861 }
862 }
863 return false;
864}
865
Roland Levillainccc07a92014-09-16 14:48:16 +0100866bool HInstructionList::FoundBefore(const HInstruction* instruction1,
867 const HInstruction* instruction2) const {
868 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
869 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
870 if (it.Current() == instruction1) {
871 return true;
872 }
873 if (it.Current() == instruction2) {
874 return false;
875 }
876 }
877 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
878 return true;
879}
880
Roland Levillain6c82d402014-10-13 16:10:27 +0100881bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
882 if (other_instruction == this) {
883 // An instruction does not strictly dominate itself.
884 return false;
885 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100886 HBasicBlock* block = GetBlock();
887 HBasicBlock* other_block = other_instruction->GetBlock();
888 if (block != other_block) {
889 return GetBlock()->Dominates(other_instruction->GetBlock());
890 } else {
891 // If both instructions are in the same block, ensure this
892 // instruction comes before `other_instruction`.
893 if (IsPhi()) {
894 if (!other_instruction->IsPhi()) {
895 // Phis appear before non phi-instructions so this instruction
896 // dominates `other_instruction`.
897 return true;
898 } else {
899 // There is no order among phis.
900 LOG(FATAL) << "There is no dominance between phis of a same block.";
901 return false;
902 }
903 } else {
904 // `this` is not a phi.
905 if (other_instruction->IsPhi()) {
906 // Phis appear before non phi-instructions so this instruction
907 // does not dominate `other_instruction`.
908 return false;
909 } else {
910 // Check whether this instruction comes before
911 // `other_instruction` in the instruction list.
912 return block->GetInstructions().FoundBefore(this, other_instruction);
913 }
914 }
915 }
916}
917
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100918void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100919 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000920 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
921 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100922 HInstruction* user = current->GetUser();
923 size_t input_index = current->GetIndex();
924 user->SetRawInputAt(input_index, other);
925 other->AddUseAt(user, input_index);
926 }
927
David Brazdiled596192015-01-23 10:39:45 +0000928 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
929 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100930 HEnvironment* user = current->GetUser();
931 size_t input_index = current->GetIndex();
932 user->SetRawEnvAt(input_index, other);
933 other->AddEnvUseAt(user, input_index);
934 }
935
David Brazdiled596192015-01-23 10:39:45 +0000936 uses_.Clear();
937 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100938}
939
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100940void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000941 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100942 SetRawInputAt(index, replacement);
943 replacement->AddUseAt(this, index);
944}
945
Nicolas Geoffray39468442014-09-02 15:17:15 +0100946size_t HInstruction::EnvironmentSize() const {
947 return HasEnvironment() ? environment_->Size() : 0;
948}
949
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100950void HPhi::AddInput(HInstruction* input) {
951 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100952 inputs_.push_back(HUserRecord<HInstruction*>(input));
953 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100954}
955
David Brazdil2d7352b2015-04-20 14:52:42 +0100956void HPhi::RemoveInputAt(size_t index) {
957 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100958 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100959 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100960 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100961 InputRecordAt(i).GetUseNode()->SetIndex(i);
962 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100963}
964
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100965#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000966void H##name::Accept(HGraphVisitor* visitor) { \
967 visitor->Visit##name(this); \
968}
969
970FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
971
972#undef DEFINE_ACCEPT
973
974void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100975 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
976 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +0000977 if (block != nullptr) {
978 VisitBasicBlock(block);
979 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000980 }
981}
982
Roland Levillain633021e2014-10-01 14:12:25 +0100983void HGraphVisitor::VisitReversePostOrder() {
984 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
985 VisitBasicBlock(it.Current());
986 }
987}
988
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000989void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100990 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100991 it.Current()->Accept(this);
992 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100993 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000994 it.Current()->Accept(this);
995 }
996}
997
Mark Mendelle82549b2015-05-06 10:55:34 -0400998HConstant* HTypeConversion::TryStaticEvaluation() const {
999 HGraph* graph = GetBlock()->GetGraph();
1000 if (GetInput()->IsIntConstant()) {
1001 int32_t value = GetInput()->AsIntConstant()->GetValue();
1002 switch (GetResultType()) {
1003 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001004 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001005 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001006 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001007 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001008 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001009 default:
1010 return nullptr;
1011 }
1012 } else if (GetInput()->IsLongConstant()) {
1013 int64_t value = GetInput()->AsLongConstant()->GetValue();
1014 switch (GetResultType()) {
1015 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001016 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001017 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001018 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001019 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001020 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001021 default:
1022 return nullptr;
1023 }
1024 } else if (GetInput()->IsFloatConstant()) {
1025 float value = GetInput()->AsFloatConstant()->GetValue();
1026 switch (GetResultType()) {
1027 case Primitive::kPrimInt:
1028 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001029 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001030 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001031 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001032 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001033 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1034 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001035 case Primitive::kPrimLong:
1036 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001037 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001038 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001039 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001040 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001041 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1042 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001043 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001044 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001045 default:
1046 return nullptr;
1047 }
1048 } else if (GetInput()->IsDoubleConstant()) {
1049 double value = GetInput()->AsDoubleConstant()->GetValue();
1050 switch (GetResultType()) {
1051 case Primitive::kPrimInt:
1052 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001053 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001054 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001055 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001056 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001057 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1058 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001059 case Primitive::kPrimLong:
1060 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001061 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001062 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001063 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001064 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001065 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1066 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001067 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001068 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001069 default:
1070 return nullptr;
1071 }
1072 }
1073 return nullptr;
1074}
1075
Roland Levillain9240d6a2014-10-20 16:47:04 +01001076HConstant* HUnaryOperation::TryStaticEvaluation() const {
1077 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001078 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001079 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001080 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001081 }
1082 return nullptr;
1083}
1084
1085HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001086 if (GetLeft()->IsIntConstant()) {
1087 if (GetRight()->IsIntConstant()) {
1088 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1089 } else if (GetRight()->IsLongConstant()) {
1090 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1091 }
1092 } else if (GetLeft()->IsLongConstant()) {
1093 if (GetRight()->IsIntConstant()) {
1094 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1095 } else if (GetRight()->IsLongConstant()) {
1096 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001097 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001098 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
1099 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain556c3d12014-09-18 15:25:07 +01001100 }
1101 return nullptr;
1102}
Dave Allison20dfc792014-06-16 20:44:29 -07001103
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001104HConstant* HBinaryOperation::GetConstantRight() const {
1105 if (GetRight()->IsConstant()) {
1106 return GetRight()->AsConstant();
1107 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1108 return GetLeft()->AsConstant();
1109 } else {
1110 return nullptr;
1111 }
1112}
1113
1114// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001115// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001116HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1117 HInstruction* most_constant_right = GetConstantRight();
1118 if (most_constant_right == nullptr) {
1119 return nullptr;
1120 } else if (most_constant_right == GetLeft()) {
1121 return GetRight();
1122 } else {
1123 return GetLeft();
1124 }
1125}
1126
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001127bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1128 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001129}
1130
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001131bool HInstruction::Equals(HInstruction* other) const {
1132 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001133 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001134 if (!InstructionDataEquals(other)) return false;
1135 if (GetType() != other->GetType()) return false;
1136 if (InputCount() != other->InputCount()) return false;
1137
1138 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1139 if (InputAt(i) != other->InputAt(i)) return false;
1140 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001141 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001142 return true;
1143}
1144
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001145std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1146#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1147 switch (rhs) {
1148 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1149 default:
1150 os << "Unknown instruction kind " << static_cast<int>(rhs);
1151 break;
1152 }
1153#undef DECLARE_CASE
1154 return os;
1155}
1156
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001157void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001158 next_->previous_ = previous_;
1159 if (previous_ != nullptr) {
1160 previous_->next_ = next_;
1161 }
1162 if (block_->instructions_.first_instruction_ == this) {
1163 block_->instructions_.first_instruction_ = next_;
1164 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001165 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001166
1167 previous_ = cursor->previous_;
1168 if (previous_ != nullptr) {
1169 previous_->next_ = this;
1170 }
1171 next_ = cursor;
1172 cursor->previous_ = this;
1173 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001174
1175 if (block_->instructions_.first_instruction_ == cursor) {
1176 block_->instructions_.first_instruction_ = this;
1177 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001178}
1179
David Brazdilfc6a86a2015-06-26 10:33:45 +00001180HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001181 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001182 DCHECK_EQ(cursor->GetBlock(), this);
1183
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001184 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1185 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001186 new_block->instructions_.first_instruction_ = cursor;
1187 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1188 instructions_.last_instruction_ = cursor->previous_;
1189 if (cursor->previous_ == nullptr) {
1190 instructions_.first_instruction_ = nullptr;
1191 } else {
1192 cursor->previous_->next_ = nullptr;
1193 cursor->previous_ = nullptr;
1194 }
1195
1196 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001197 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001198
Vladimir Marko60584552015-09-03 13:35:12 +00001199 for (HBasicBlock* successor : GetSuccessors()) {
1200 new_block->successors_.push_back(successor);
1201 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001202 }
Vladimir Marko60584552015-09-03 13:35:12 +00001203 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001204 AddSuccessor(new_block);
1205
David Brazdil56e1acc2015-06-30 15:41:36 +01001206 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001207 return new_block;
1208}
1209
David Brazdild7558da2015-09-22 13:04:14 +01001210HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001211 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001212 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1213
1214 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1215
1216 for (HBasicBlock* predecessor : GetPredecessors()) {
1217 new_block->predecessors_.push_back(predecessor);
1218 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1219 }
1220 predecessors_.clear();
1221 AddPredecessor(new_block);
1222
1223 GetGraph()->AddBlock(new_block);
1224 return new_block;
1225}
1226
David Brazdil9bc43612015-11-05 21:25:24 +00001227HBasicBlock* HBasicBlock::SplitCatchBlockAfterMoveException() {
1228 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
1229 DCHECK(IsCatchBlock()) << "This method is intended for catch blocks only.";
1230
1231 HInstruction* first_insn = GetFirstInstruction();
1232 HInstruction* split_before = nullptr;
1233
1234 if (first_insn != nullptr && first_insn->IsLoadException()) {
1235 // Catch block starts with a LoadException. Split the block after
1236 // the StoreLocal and ClearException which must come after the load.
1237 DCHECK(first_insn->GetNext()->IsStoreLocal());
1238 DCHECK(first_insn->GetNext()->GetNext()->IsClearException());
1239 split_before = first_insn->GetNext()->GetNext()->GetNext();
1240 } else {
1241 // Catch block does not load the exception. Split at the beginning
1242 // to create an empty catch block.
1243 split_before = first_insn;
1244 }
1245
1246 if (split_before == nullptr) {
1247 // Catch block has no instructions after the split point (must be dead).
1248 // Do not split it but rather signal error by returning nullptr.
1249 return nullptr;
1250 } else {
1251 return SplitBefore(split_before);
1252 }
1253}
1254
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001255HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1256 DCHECK(!cursor->IsControlFlow());
1257 DCHECK_NE(instructions_.last_instruction_, cursor);
1258 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001259
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001260 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1261 new_block->instructions_.first_instruction_ = cursor->GetNext();
1262 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1263 cursor->next_->previous_ = nullptr;
1264 cursor->next_ = nullptr;
1265 instructions_.last_instruction_ = cursor;
1266
1267 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001268 for (HBasicBlock* successor : GetSuccessors()) {
1269 new_block->successors_.push_back(successor);
1270 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001271 }
Vladimir Marko60584552015-09-03 13:35:12 +00001272 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001273
Vladimir Marko60584552015-09-03 13:35:12 +00001274 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001275 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001276 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001277 }
Vladimir Marko60584552015-09-03 13:35:12 +00001278 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001279 return new_block;
1280}
1281
David Brazdilec16f792015-08-19 15:04:01 +01001282const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001283 if (EndsWithTryBoundary()) {
1284 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1285 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001286 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001287 return try_boundary;
1288 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001289 DCHECK(IsTryBlock());
1290 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001291 return nullptr;
1292 }
David Brazdilec16f792015-08-19 15:04:01 +01001293 } else if (IsTryBlock()) {
1294 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001295 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001296 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001297 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001298}
1299
David Brazdild7558da2015-09-22 13:04:14 +01001300bool HBasicBlock::HasThrowingInstructions() const {
1301 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1302 if (it.Current()->CanThrow()) {
1303 return true;
1304 }
1305 }
1306 return false;
1307}
1308
David Brazdilfc6a86a2015-06-26 10:33:45 +00001309static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1310 return block.GetPhis().IsEmpty()
1311 && !block.GetInstructions().IsEmpty()
1312 && block.GetFirstInstruction() == block.GetLastInstruction();
1313}
1314
David Brazdil46e2a392015-03-16 17:31:52 +00001315bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001316 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1317}
1318
1319bool HBasicBlock::IsSingleTryBoundary() const {
1320 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001321}
1322
David Brazdil8d5b8b22015-03-24 10:51:52 +00001323bool HBasicBlock::EndsWithControlFlowInstruction() const {
1324 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1325}
1326
David Brazdilb2bd1c52015-03-25 11:17:37 +00001327bool HBasicBlock::EndsWithIf() const {
1328 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1329}
1330
David Brazdilffee3d32015-07-06 11:48:53 +01001331bool HBasicBlock::EndsWithTryBoundary() const {
1332 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1333}
1334
David Brazdilb2bd1c52015-03-25 11:17:37 +00001335bool HBasicBlock::HasSinglePhi() const {
1336 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1337}
1338
David Brazdild26a4112015-11-10 11:07:31 +00001339ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1340 if (EndsWithTryBoundary()) {
1341 // The normal-flow successor of HTryBoundary is always stored at index zero.
1342 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1343 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1344 } else {
1345 // All successors of blocks not ending with TryBoundary are normal.
1346 return ArrayRef<HBasicBlock* const>(successors_);
1347 }
1348}
1349
1350ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1351 if (EndsWithTryBoundary()) {
1352 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1353 } else {
1354 // Blocks not ending with TryBoundary do not have exceptional successors.
1355 return ArrayRef<HBasicBlock* const>();
1356 }
1357}
1358
David Brazdilffee3d32015-07-06 11:48:53 +01001359bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001360 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1361 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1362
1363 size_t length = handlers1.size();
1364 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001365 return false;
1366 }
1367
David Brazdilb618ade2015-07-29 10:31:29 +01001368 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001369 for (size_t i = 0; i < length; ++i) {
1370 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001371 return false;
1372 }
1373 }
1374 return true;
1375}
1376
David Brazdil2d7352b2015-04-20 14:52:42 +01001377size_t HInstructionList::CountSize() const {
1378 size_t size = 0;
1379 HInstruction* current = first_instruction_;
1380 for (; current != nullptr; current = current->GetNext()) {
1381 size++;
1382 }
1383 return size;
1384}
1385
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001386void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1387 for (HInstruction* current = first_instruction_;
1388 current != nullptr;
1389 current = current->GetNext()) {
1390 current->SetBlock(block);
1391 }
1392}
1393
1394void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1395 DCHECK(Contains(cursor));
1396 if (!instruction_list.IsEmpty()) {
1397 if (cursor == last_instruction_) {
1398 last_instruction_ = instruction_list.last_instruction_;
1399 } else {
1400 cursor->next_->previous_ = instruction_list.last_instruction_;
1401 }
1402 instruction_list.last_instruction_->next_ = cursor->next_;
1403 cursor->next_ = instruction_list.first_instruction_;
1404 instruction_list.first_instruction_->previous_ = cursor;
1405 }
1406}
1407
1408void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001409 if (IsEmpty()) {
1410 first_instruction_ = instruction_list.first_instruction_;
1411 last_instruction_ = instruction_list.last_instruction_;
1412 } else {
1413 AddAfter(last_instruction_, instruction_list);
1414 }
1415}
1416
David Brazdil2d7352b2015-04-20 14:52:42 +01001417void HBasicBlock::DisconnectAndDelete() {
1418 // Dominators must be removed after all the blocks they dominate. This way
1419 // a loop header is removed last, a requirement for correct loop information
1420 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001421 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001422
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001423 // (1) Remove the block from all loops it is included in.
David Brazdil2d7352b2015-04-20 14:52:42 +01001424 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1425 HLoopInformation* loop_info = it.Current();
1426 loop_info->Remove(this);
1427 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001428 // If this was the last back edge of the loop, we deliberately leave the
1429 // loop in an inconsistent state and will fail SSAChecker unless the
1430 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001431 loop_info->RemoveBackEdge(this);
1432 }
1433 }
1434
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001435 // (2) Disconnect the block from its predecessors and update their
1436 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001437 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001438 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001439 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1440 // This block is the only normal-flow successor of the TryBoundary which
1441 // makes `predecessor` dead. Since DCE removes blocks in post order,
1442 // exception handlers of this TryBoundary were already visited and any
1443 // remaining handlers therefore must be live. We remove `predecessor` from
1444 // their list of predecessors.
1445 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1446 while (predecessor->GetSuccessors().size() > 1) {
1447 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1448 DCHECK(handler->IsCatchBlock());
1449 predecessor->RemoveSuccessor(handler);
1450 handler->RemovePredecessor(predecessor);
1451 }
1452 }
1453
David Brazdil2d7352b2015-04-20 14:52:42 +01001454 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001455 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1456 if (num_pred_successors == 1u) {
1457 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001458 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1459 // successor. Replace those with a HGoto.
1460 DCHECK(last_instruction->IsIf() ||
1461 last_instruction->IsPackedSwitch() ||
1462 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001463 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001464 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001465 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001466 // The predecessor has no remaining successors and therefore must be dead.
1467 // We deliberately leave it without a control-flow instruction so that the
1468 // SSAChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001469 predecessor->RemoveInstruction(last_instruction);
1470 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001471 // There are multiple successors left. The removed block might be a successor
1472 // of a PackedSwitch which will be completely removed (perhaps replaced with
1473 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1474 // case, leave `last_instruction` as is for now.
1475 DCHECK(last_instruction->IsPackedSwitch() ||
1476 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001477 }
David Brazdil46e2a392015-03-16 17:31:52 +00001478 }
Vladimir Marko60584552015-09-03 13:35:12 +00001479 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001480
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001481 // (3) Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001482 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001483 // Delete this block from the list of predecessors.
1484 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001485 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001486
1487 // Check that `successor` has other predecessors, otherwise `this` is the
1488 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001489 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001490
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001491 // Remove this block's entries in the successor's phis. Skip exceptional
1492 // successors because catch phi inputs do not correspond to predecessor
1493 // blocks but throwing instructions. Their inputs will be updated in step (4).
1494 if (!successor->IsCatchBlock()) {
1495 if (successor->predecessors_.size() == 1u) {
1496 // The successor has just one predecessor left. Replace phis with the only
1497 // remaining input.
1498 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1499 HPhi* phi = phi_it.Current()->AsPhi();
1500 phi->ReplaceWith(phi->InputAt(1 - this_index));
1501 successor->RemovePhi(phi);
1502 }
1503 } else {
1504 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1505 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1506 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001507 }
1508 }
1509 }
Vladimir Marko60584552015-09-03 13:35:12 +00001510 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001511
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001512 // (4) Remove instructions and phis. Instructions should have no remaining uses
1513 // except in catch phis. If an instruction is used by a catch phi at `index`,
1514 // remove `index`-th input of all phis in the catch block since they are
1515 // guaranteed dead. Note that we may miss dead inputs this way but the
1516 // graph will always remain consistent.
1517 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1518 HInstruction* insn = it.Current();
1519 while (insn->HasUses()) {
1520 DCHECK(IsTryBlock());
1521 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1522 size_t use_index = use->GetIndex();
1523 HBasicBlock* user_block = use->GetUser()->GetBlock();
1524 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1525 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1526 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1527 }
1528 }
1529
1530 RemoveInstruction(insn);
1531 }
1532 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1533 RemovePhi(it.Current()->AsPhi());
1534 }
1535
David Brazdil2d7352b2015-04-20 14:52:42 +01001536 // Disconnect from the dominator.
1537 dominator_->RemoveDominatedBlock(this);
1538 SetDominator(nullptr);
1539
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001540 // Delete from the graph, update reverse post order.
1541 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001542 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001543}
1544
1545void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001546 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001547 DCHECK(ContainsElement(dominated_blocks_, other));
1548 DCHECK_EQ(GetSingleSuccessor(), other);
1549 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001550 DCHECK(other->GetPhis().IsEmpty());
1551
David Brazdil2d7352b2015-04-20 14:52:42 +01001552 // Move instructions from `other` to `this`.
1553 DCHECK(EndsWithControlFlowInstruction());
1554 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001555 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001556 other->instructions_.SetBlockOfInstructions(this);
1557 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001558
David Brazdil2d7352b2015-04-20 14:52:42 +01001559 // Remove `other` from the loops it is included in.
1560 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1561 HLoopInformation* loop_info = it.Current();
1562 loop_info->Remove(other);
1563 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001564 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001565 }
1566 }
1567
1568 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001569 successors_.clear();
1570 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001571 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001572 successor->ReplacePredecessor(other, this);
1573 }
1574
David Brazdil2d7352b2015-04-20 14:52:42 +01001575 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001576 RemoveDominatedBlock(other);
1577 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1578 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001579 dominated->SetDominator(this);
1580 }
Vladimir Marko60584552015-09-03 13:35:12 +00001581 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001582 other->dominator_ = nullptr;
1583
1584 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001585 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001586
1587 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001588 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001589 other->SetGraph(nullptr);
1590}
1591
1592void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1593 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001594 DCHECK(GetDominatedBlocks().empty());
1595 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001596 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001597 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001598 DCHECK(other->GetPhis().IsEmpty());
1599 DCHECK(!other->IsInLoop());
1600
1601 // Move instructions from `other` to `this`.
1602 instructions_.Add(other->GetInstructions());
1603 other->instructions_.SetBlockOfInstructions(this);
1604
1605 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001606 successors_.clear();
1607 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001608 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001609 successor->ReplacePredecessor(other, this);
1610 }
1611
1612 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001613 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1614 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001615 dominated->SetDominator(this);
1616 }
Vladimir Marko60584552015-09-03 13:35:12 +00001617 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001618 other->dominator_ = nullptr;
1619 other->graph_ = nullptr;
1620}
1621
1622void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001623 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001624 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001625 predecessor->ReplaceSuccessor(this, other);
1626 }
Vladimir Marko60584552015-09-03 13:35:12 +00001627 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001628 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001629 successor->ReplacePredecessor(this, other);
1630 }
Vladimir Marko60584552015-09-03 13:35:12 +00001631 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1632 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001633 }
1634 GetDominator()->ReplaceDominatedBlock(this, other);
1635 other->SetDominator(GetDominator());
1636 dominator_ = nullptr;
1637 graph_ = nullptr;
1638}
1639
1640// Create space in `blocks` for adding `number_of_new_blocks` entries
1641// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001642static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001643 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001644 size_t after) {
1645 DCHECK_LT(after, blocks->size());
1646 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001647 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001648 blocks->resize(new_size);
1649 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001650}
1651
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001652void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001653 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001654 DCHECK(block->GetSuccessors().empty());
1655 DCHECK(block->GetPredecessors().empty());
1656 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001657 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001658 DCHECK(block->GetInstructions().IsEmpty());
1659 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001660
David Brazdilc7af85d2015-05-26 12:05:55 +01001661 if (block->IsExitBlock()) {
1662 exit_block_ = nullptr;
1663 }
1664
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001665 RemoveElement(reverse_post_order_, block);
1666 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001667}
1668
Calin Juravle2e768302015-07-28 14:41:11 +00001669HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001670 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001671 // Update the environments in this graph to have the invoke's environment
1672 // as parent.
1673 {
1674 HReversePostOrderIterator it(*this);
1675 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1676 for (; !it.Done(); it.Advance()) {
1677 HBasicBlock* block = it.Current();
1678 for (HInstructionIterator instr_it(block->GetInstructions());
1679 !instr_it.Done();
1680 instr_it.Advance()) {
1681 HInstruction* current = instr_it.Current();
1682 if (current->NeedsEnvironment()) {
1683 current->GetEnvironment()->SetAndCopyParentChain(
1684 outer_graph->GetArena(), invoke->GetEnvironment());
1685 }
1686 }
1687 }
1688 }
1689 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1690 if (HasBoundsChecks()) {
1691 outer_graph->SetHasBoundsChecks(true);
1692 }
1693
Calin Juravle2e768302015-07-28 14:41:11 +00001694 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001695 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001696 // Simple case of an entry block, a body block, and an exit block.
1697 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001698 HBasicBlock* body = GetBlocks()[1];
1699 DCHECK(GetBlocks()[0]->IsEntryBlock());
1700 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001701 DCHECK(!body->IsExitBlock());
1702 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001703
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001704 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1705 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001706
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001707 // Replace the invoke with the return value of the inlined graph.
1708 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001709 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001710 } else {
1711 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001712 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001713
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001714 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001715 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001716 // Need to inline multiple blocks. We split `invoke`'s block
1717 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001718 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001719 // with the second half.
1720 ArenaAllocator* allocator = outer_graph->GetArena();
1721 HBasicBlock* at = invoke->GetBlock();
1722 HBasicBlock* to = at->SplitAfter(invoke);
1723
Vladimir Markoec7802a2015-10-01 20:57:57 +01001724 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001725 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001726 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001727 exit_block_->ReplaceWith(to);
1728
1729 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001730 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001731 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001732 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001733 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001734 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001735 if (!returns_void) {
1736 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001737 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001738 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001739 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001740 } else {
1741 if (!returns_void) {
1742 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001743 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001744 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001745 to->AddPhi(return_value->AsPhi());
1746 }
Vladimir Marko60584552015-09-03 13:35:12 +00001747 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001748 HInstruction* last = predecessor->GetLastInstruction();
1749 if (!returns_void) {
1750 return_value->AsPhi()->AddInput(last->InputAt(0));
1751 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001752 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001753 predecessor->RemoveInstruction(last);
1754 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001755 }
1756
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001757 // Update the meta information surrounding blocks:
1758 // (1) the graph they are now in,
1759 // (2) the reverse post order of that graph,
David Brazdil95177982015-10-30 12:56:58 -05001760 // (3) the potential loop information they are now in,
1761 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001762 // Note that we do not need to update catch phi inputs because they
1763 // correspond to the register file of the outer method which the inlinee
1764 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001765
1766 // We don't add the entry block, the exit block, and the first block, which
1767 // has been merged with `at`.
1768 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1769
1770 // We add the `to` block.
1771 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001772 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001773 + kNumberOfNewBlocksInCaller;
1774
1775 // Find the location of `at` in the outer graph's reverse post order. The new
1776 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001777 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001778 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1779
David Brazdil95177982015-10-30 12:56:58 -05001780 HLoopInformation* loop_info = at->GetLoopInformation();
1781 // Copy TryCatchInformation if `at` is a try block, not if it is a catch block.
1782 TryCatchInformation* try_catch_info = at->IsTryBlock() ? at->GetTryCatchInformation() : nullptr;
1783
1784 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1785 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001786 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1787 HBasicBlock* current = it.Current();
1788 if (current != exit_block_ && current != entry_block_ && current != first) {
1789 DCHECK(!current->IsInLoop());
David Brazdil95177982015-10-30 12:56:58 -05001790 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001791 DCHECK(current->GetGraph() == this);
1792 current->SetGraph(outer_graph);
1793 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001794 outer_graph->reverse_post_order_[++index_of_at] = current;
David Brazdil95177982015-10-30 12:56:58 -05001795 if (loop_info != nullptr) {
1796 current->SetLoopInformation(loop_info);
David Brazdil7d275372015-04-21 16:36:35 +01001797 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1798 loop_it.Current()->Add(current);
1799 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001800 }
David Brazdil95177982015-10-30 12:56:58 -05001801 current->SetTryCatchInformation(try_catch_info);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001802 }
1803 }
1804
David Brazdil95177982015-10-30 12:56:58 -05001805 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001806 to->SetGraph(outer_graph);
1807 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001808 outer_graph->reverse_post_order_[++index_of_at] = to;
David Brazdil95177982015-10-30 12:56:58 -05001809 if (loop_info != nullptr) {
1810 to->SetLoopInformation(loop_info);
David Brazdil7d275372015-04-21 16:36:35 +01001811 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1812 loop_it.Current()->Add(to);
1813 }
David Brazdil95177982015-10-30 12:56:58 -05001814 if (loop_info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001815 // Only `to` can become a back edge, as the inlined blocks
1816 // are predecessors of `to`.
David Brazdil95177982015-10-30 12:56:58 -05001817 loop_info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001818 }
1819 }
David Brazdil95177982015-10-30 12:56:58 -05001820 to->SetTryCatchInformation(try_catch_info);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001821 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001822
David Brazdil05144f42015-04-16 15:18:00 +01001823 // Update the next instruction id of the outer graph, so that instructions
1824 // added later get bigger ids than those in the inner graph.
1825 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1826
1827 // Walk over the entry block and:
1828 // - Move constants from the entry block to the outer_graph's entry block,
1829 // - Replace HParameterValue instructions with their real value.
1830 // - Remove suspend checks, that hold an environment.
1831 // We must do this after the other blocks have been inlined, otherwise ids of
1832 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001833 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001834 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1835 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01001836 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01001837 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001838 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001839 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001840 replacement = outer_graph->GetIntConstant(
1841 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001842 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001843 replacement = outer_graph->GetLongConstant(
1844 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001845 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001846 replacement = outer_graph->GetFloatConstant(
1847 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001848 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001849 replacement = outer_graph->GetDoubleConstant(
1850 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001851 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001852 if (kIsDebugBuild
1853 && invoke->IsInvokeStaticOrDirect()
1854 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1855 // Ensure we do not use the last input of `invoke`, as it
1856 // contains a clinit check which is not an actual argument.
1857 size_t last_input_index = invoke->InputCount() - 1;
1858 DCHECK(parameter_index != last_input_index);
1859 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01001860 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001861 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001862 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01001863 } else {
1864 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1865 entry_block_->RemoveInstruction(current);
1866 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01001867 if (replacement != nullptr) {
1868 current->ReplaceWith(replacement);
1869 // If the current is the return value then we need to update the latter.
1870 if (current == return_value) {
1871 DCHECK_EQ(entry_block_, return_value->GetBlock());
1872 return_value = replacement;
1873 }
1874 }
1875 }
1876
1877 if (return_value != nullptr) {
1878 invoke->ReplaceWith(return_value);
David Brazdil05144f42015-04-16 15:18:00 +01001879 }
1880
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001881 // Finally remove the invoke from the caller.
1882 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00001883
1884 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001885}
1886
Mingyao Yang3584bce2015-05-19 16:01:59 -07001887/*
1888 * Loop will be transformed to:
1889 * old_pre_header
1890 * |
1891 * if_block
1892 * / \
1893 * dummy_block deopt_block
1894 * \ /
1895 * new_pre_header
1896 * |
1897 * header
1898 */
1899void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1900 DCHECK(header->IsLoopHeader());
1901 HBasicBlock* pre_header = header->GetDominator();
1902
1903 // Need this to avoid critical edge.
1904 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1905 // Need this to avoid critical edge.
1906 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1907 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1908 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1909 AddBlock(if_block);
1910 AddBlock(dummy_block);
1911 AddBlock(deopt_block);
1912 AddBlock(new_pre_header);
1913
1914 header->ReplacePredecessor(pre_header, new_pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001915 pre_header->successors_.clear();
1916 pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07001917
1918 pre_header->AddSuccessor(if_block);
1919 if_block->AddSuccessor(dummy_block); // True successor
1920 if_block->AddSuccessor(deopt_block); // False successor
1921 dummy_block->AddSuccessor(new_pre_header);
1922 deopt_block->AddSuccessor(new_pre_header);
1923
Vladimir Marko60584552015-09-03 13:35:12 +00001924 pre_header->dominated_blocks_.push_back(if_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001925 if_block->SetDominator(pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001926 if_block->dominated_blocks_.push_back(dummy_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001927 dummy_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001928 if_block->dominated_blocks_.push_back(deopt_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001929 deopt_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001930 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001931 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001932 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001933 header->SetDominator(new_pre_header);
1934
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001935 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001936 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001937 reverse_post_order_[index_of_header++] = if_block;
1938 reverse_post_order_[index_of_header++] = dummy_block;
1939 reverse_post_order_[index_of_header++] = deopt_block;
1940 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001941
1942 HLoopInformation* info = pre_header->GetLoopInformation();
1943 if (info != nullptr) {
1944 if_block->SetLoopInformation(info);
1945 dummy_block->SetLoopInformation(info);
1946 deopt_block->SetLoopInformation(info);
1947 new_pre_header->SetLoopInformation(info);
1948 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1949 !loop_it.Done();
1950 loop_it.Advance()) {
1951 loop_it.Current()->Add(if_block);
1952 loop_it.Current()->Add(dummy_block);
1953 loop_it.Current()->Add(deopt_block);
1954 loop_it.Current()->Add(new_pre_header);
1955 }
1956 }
1957}
1958
Calin Juravle2e768302015-07-28 14:41:11 +00001959void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
1960 if (kIsDebugBuild) {
1961 DCHECK_EQ(GetType(), Primitive::kPrimNot);
1962 ScopedObjectAccess soa(Thread::Current());
1963 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
1964 if (IsBoundType()) {
1965 // Having the test here spares us from making the method virtual just for
1966 // the sake of a DCHECK.
1967 ReferenceTypeInfo upper_bound_rti = AsBoundType()->GetUpperBound();
1968 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
1969 << " upper_bound_rti: " << upper_bound_rti
1970 << " rti: " << rti;
David Brazdilbaf89b82015-09-15 11:36:54 +01001971 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00001972 }
1973 }
1974 reference_type_info_ = rti;
1975}
1976
1977ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
1978
1979ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
1980 : type_handle_(type_handle), is_exact_(is_exact) {
1981 if (kIsDebugBuild) {
1982 ScopedObjectAccess soa(Thread::Current());
1983 DCHECK(IsValidHandle(type_handle));
1984 }
1985}
1986
Calin Juravleacf735c2015-02-12 15:25:22 +00001987std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1988 ScopedObjectAccess soa(Thread::Current());
1989 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00001990 << " is_valid=" << rhs.IsValid()
1991 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00001992 << " is_exact=" << rhs.IsExact()
1993 << " ]";
1994 return os;
1995}
1996
Mark Mendellc4701932015-04-10 13:18:51 -04001997bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
1998 // For now, assume that instructions in different blocks may use the
1999 // environment.
2000 // TODO: Use the control flow to decide if this is true.
2001 if (GetBlock() != other->GetBlock()) {
2002 return true;
2003 }
2004
2005 // We know that we are in the same block. Walk from 'this' to 'other',
2006 // checking to see if there is any instruction with an environment.
2007 HInstruction* current = this;
2008 for (; current != other && current != nullptr; current = current->GetNext()) {
2009 // This is a conservative check, as the instruction result may not be in
2010 // the referenced environment.
2011 if (current->HasEnvironment()) {
2012 return true;
2013 }
2014 }
2015
2016 // We should have been called with 'this' before 'other' in the block.
2017 // Just confirm this.
2018 DCHECK(current != nullptr);
2019 return false;
2020}
2021
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002022void HInvoke::SetIntrinsic(Intrinsics intrinsic,
2023 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache) {
2024 intrinsic_ = intrinsic;
2025 IntrinsicOptimizations opt(this);
2026 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2027 opt.SetDoesNotNeedDexCache();
2028 opt.SetDoesNotNeedEnvironment();
2029 }
2030}
2031
2032bool HInvoke::NeedsEnvironment() const {
2033 if (!IsIntrinsic()) {
2034 return true;
2035 }
2036 IntrinsicOptimizations opt(*this);
2037 return !opt.GetDoesNotNeedEnvironment();
2038}
2039
Vladimir Markodc151b22015-10-15 18:02:30 +01002040bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2041 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002042 return false;
2043 }
2044 if (!IsIntrinsic()) {
2045 return true;
2046 }
2047 IntrinsicOptimizations opt(*this);
2048 return !opt.GetDoesNotNeedDexCache();
2049}
2050
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002051void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2052 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2053 input->AddUseAt(this, index);
2054 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2055 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2056 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2057 InputRecordAt(i).GetUseNode()->SetIndex(i);
2058 }
2059}
2060
Vladimir Markob554b5a2015-11-06 12:57:55 +00002061void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2062 RemoveAsUserOfInput(index);
2063 inputs_.erase(inputs_.begin() + index);
2064 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2065 for (size_t i = index, e = InputCount(); i < e; ++i) {
2066 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2067 InputRecordAt(i).GetUseNode()->SetIndex(i);
2068 }
2069}
2070
Vladimir Markofbb184a2015-11-13 14:47:00 +00002071std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2072 switch (rhs) {
2073 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2074 return os << "explicit";
2075 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2076 return os << "implicit";
2077 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2078 return os << "none";
2079 default:
2080 return os << "unknown:" << static_cast<int>(rhs);
2081 }
2082}
2083
Mark Mendellc4701932015-04-10 13:18:51 -04002084void HInstruction::RemoveEnvironmentUsers() {
2085 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2086 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2087 HEnvironment* user = user_node->GetUser();
2088 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2089 }
2090 env_uses_.Clear();
2091}
2092
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002093} // namespace art