blob: 98c3096cae451f3f9dfd4ab15114695c90edf4cf [file] [log] [blame]
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000018
Mark Mendelle82549b2015-05-06 10:55:34 -040019#include "code_generator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010020#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010021#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010022#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010023#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010024#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010025#include "mirror/class-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000026#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000027
28namespace art {
29
30void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010031 block->SetBlockId(blocks_.size());
32 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000033}
34
Nicolas Geoffray804d0932014-05-02 08:46:00 +010035void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010036 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
37 DCHECK_EQ(visited->GetHighestBitSet(), -1);
38
39 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010040 ArenaBitVector visiting(arena_, blocks_.size(), false);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010041 // Number of successors visited from a given node, indexed by block id.
42 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
43 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
44 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
45 constexpr size_t kDefaultWorklistSize = 8;
46 worklist.reserve(kDefaultWorklistSize);
47 visited->SetBit(entry_block_->GetBlockId());
48 visiting.SetBit(entry_block_->GetBlockId());
49 worklist.push_back(entry_block_);
50
51 while (!worklist.empty()) {
52 HBasicBlock* current = worklist.back();
53 uint32_t current_id = current->GetBlockId();
54 if (successors_visited[current_id] == current->GetSuccessors().size()) {
55 visiting.ClearBit(current_id);
56 worklist.pop_back();
57 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010058 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
59 uint32_t successor_id = successor->GetBlockId();
60 if (visiting.IsBitSet(successor_id)) {
61 DCHECK(ContainsElement(worklist, successor));
62 successor->AddBackEdge(current);
63 } else if (!visited->IsBitSet(successor_id)) {
64 visited->SetBit(successor_id);
65 visiting.SetBit(successor_id);
66 worklist.push_back(successor);
67 }
68 }
69 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000070}
71
Roland Levillainfc600dc2014-12-02 17:16:31 +000072static void RemoveAsUser(HInstruction* instruction) {
73 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000074 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000075 }
76
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010077 for (HEnvironment* environment = instruction->GetEnvironment();
78 environment != nullptr;
79 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000080 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000081 if (environment->GetInstructionAt(i) != nullptr) {
82 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000083 }
84 }
85 }
86}
87
88void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010089 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000090 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010091 HBasicBlock* block = blocks_[i];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010092 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000093 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
94 RemoveAsUser(it.Current());
95 }
96 }
97 }
98}
99
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100100void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100101 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000102 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100103 HBasicBlock* block = blocks_[i];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100104 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000105 for (HBasicBlock* successor : block->GetSuccessors()) {
106 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000107 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100108 // Remove the block from the list of blocks, so that further analyses
109 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100110 blocks_[i] = nullptr;
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000111 }
112 }
113}
114
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000115void HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100116 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
117 // edges. This invariant simplifies building SSA form because Phis cannot
118 // collect both normal- and exceptional-flow values at the same time.
119 SimplifyCatchBlocks();
120
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100121 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000122
David Brazdilffee3d32015-07-06 11:48:53 +0100123 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000124 FindBackEdges(&visited);
125
David Brazdilffee3d32015-07-06 11:48:53 +0100126 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000127 // the initial DFS as users from other instructions, so that
128 // users can be safely removed before uses later.
129 RemoveInstructionsAsUsersFromDeadBlocks(visited);
130
David Brazdilffee3d32015-07-06 11:48:53 +0100131 // (4) Remove blocks not visited during the initial DFS.
Roland Levillainfc600dc2014-12-02 17:16:31 +0000132 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000133 // predecessors list of live blocks.
134 RemoveDeadBlocks(visited);
135
David Brazdilffee3d32015-07-06 11:48:53 +0100136 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100137 // dominators and the reverse post order.
138 SimplifyCFG();
139
David Brazdilffee3d32015-07-06 11:48:53 +0100140 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100141 ComputeDominanceInformation();
142}
143
144void HGraph::ClearDominanceInformation() {
145 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
146 it.Current()->ClearDominanceInformation();
147 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100148 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100149}
150
151void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000152 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100153 dominator_ = nullptr;
154}
155
156void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100157 DCHECK(reverse_post_order_.empty());
158 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100159 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100160
161 // Number of visits of a given node, indexed by block id.
162 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
163 // Number of successors visited from a given node, indexed by block id.
164 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
165 // Nodes for which we need to visit successors.
166 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
167 constexpr size_t kDefaultWorklistSize = 8;
168 worklist.reserve(kDefaultWorklistSize);
169 worklist.push_back(entry_block_);
170
171 while (!worklist.empty()) {
172 HBasicBlock* current = worklist.back();
173 uint32_t current_id = current->GetBlockId();
174 if (successors_visited[current_id] == current->GetSuccessors().size()) {
175 worklist.pop_back();
176 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100177 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
178
179 if (successor->GetDominator() == nullptr) {
180 successor->SetDominator(current);
181 } else {
182 successor->SetDominator(FindCommonDominator(successor->GetDominator(), current));
183 }
184
185 // Once all the forward edges have been visited, we know the immediate
186 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100187 if (++visits[successor->GetBlockId()] ==
188 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
189 successor->GetDominator()->AddDominatedBlock(successor);
190 reverse_post_order_.push_back(successor);
191 worklist.push_back(successor);
192 }
193 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000194 }
195}
196
197HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100198 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000199 // Walk the dominator tree of the first block and mark the visited blocks.
200 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000201 visited.SetBit(first->GetBlockId());
202 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000203 }
204 // Walk the dominator tree of the second block until a marked block is found.
205 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000206 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000207 return second;
208 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000209 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000210 }
211 LOG(ERROR) << "Could not find common dominator";
212 return nullptr;
213}
214
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000215void HGraph::TransformToSsa() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100216 DCHECK(!reverse_post_order_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100217 SsaBuilder ssa_builder(this);
218 ssa_builder.BuildSsa();
219}
220
David Brazdilfc6a86a2015-06-26 10:33:45 +0000221HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000222 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
223 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000224 // Use `InsertBetween` to ensure the predecessor index and successor index of
225 // `block` and `successor` are preserved.
226 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000227 return new_block;
228}
229
230void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
231 // Insert a new node between `block` and `successor` to split the
232 // critical edge.
233 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600234 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100235 if (successor->IsLoopHeader()) {
236 // If we split at a back edge boundary, make the new block the back edge.
237 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000238 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100239 info->RemoveBackEdge(block);
240 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100241 }
242 }
243}
244
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100245void HGraph::SimplifyLoop(HBasicBlock* header) {
246 HLoopInformation* info = header->GetLoopInformation();
247
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100248 // Make sure the loop has only one pre header. This simplifies SSA building by having
249 // to just look at the pre header to know which locals are initialized at entry of the
250 // loop.
Vladimir Marko60584552015-09-03 13:35:12 +0000251 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100252 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100253 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100254 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600255 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100256
Vladimir Marko60584552015-09-03 13:35:12 +0000257 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100258 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100259 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100260 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100261 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100262 }
263 }
264 pre_header->AddSuccessor(header);
265 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100266
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100267 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100268 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
269 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000270 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100271 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100272 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000273 header->predecessors_[pred] = to_swap;
274 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100275 break;
276 }
277 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100278 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100279
280 // Place the suspend check at the beginning of the header, so that live registers
281 // will be known when allocating registers. Note that code generation can still
282 // generate the suspend check at the back edge, but needs to be careful with
283 // loop phi spill slots (which are not written to at back edge).
284 HInstruction* first_instruction = header->GetFirstInstruction();
285 if (!first_instruction->IsSuspendCheck()) {
286 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
287 header->InsertInstructionBefore(check, first_instruction);
288 first_instruction = check;
289 }
290 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100291}
292
David Brazdilffee3d32015-07-06 11:48:53 +0100293static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100294 HBasicBlock* predecessor = block.GetPredecessors()[pred_idx];
David Brazdilffee3d32015-07-06 11:48:53 +0100295 if (!predecessor->EndsWithTryBoundary()) {
296 // Only edges from HTryBoundary can be exceptional.
297 return false;
298 }
299 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
300 if (try_boundary->GetNormalFlowSuccessor() == &block) {
301 // This block is the normal-flow successor of `try_boundary`, but it could
302 // also be one of its exception handlers if catch blocks have not been
303 // simplified yet. Predecessors are unordered, so we will consider the first
304 // occurrence to be the normal edge and a possible second occurrence to be
305 // the exceptional edge.
306 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
307 } else {
308 // This is not the normal-flow successor of `try_boundary`, hence it must be
309 // one of its exception handlers.
310 DCHECK(try_boundary->HasExceptionHandler(block));
311 return true;
312 }
313}
314
315void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100316 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
317 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
318 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
319 HBasicBlock* catch_block = blocks_[block_id];
David Brazdilffee3d32015-07-06 11:48:53 +0100320 if (!catch_block->IsCatchBlock()) {
321 continue;
322 }
323
324 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000325 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100326 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
327 exceptional_predecessors_only = false;
328 break;
329 }
330 }
331
332 if (!exceptional_predecessors_only) {
333 // Catch block has normal-flow predecessors and needs to be simplified.
334 // Splitting the block before its first instruction moves all its
335 // instructions into `normal_block` and links the two blocks with a Goto.
336 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
337 // leaving `catch_block` with the exceptional edges only.
338 // Note that catch blocks with normal-flow predecessors cannot begin with
339 // a MOVE_EXCEPTION instruction, as guaranteed by the verifier.
340 DCHECK(!catch_block->GetFirstInstruction()->IsLoadException());
341 HBasicBlock* normal_block = catch_block->SplitBefore(catch_block->GetFirstInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +0000342 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100343 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100344 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
David Brazdilffee3d32015-07-06 11:48:53 +0100345 --j;
346 }
347 }
348 }
349 }
350}
351
352void HGraph::ComputeTryBlockInformation() {
353 // Iterate in reverse post order to propagate try membership information from
354 // predecessors to their successors.
355 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
356 HBasicBlock* block = it.Current();
357 if (block->IsEntryBlock() || block->IsCatchBlock()) {
358 // Catch blocks after simplification have only exceptional predecessors
359 // and hence are never in tries.
360 continue;
361 }
362
363 // Infer try membership from the first predecessor. Having simplified loops,
364 // the first predecessor can never be a back edge and therefore it must have
365 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100366 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100367 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100368 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
369 if (try_entry != nullptr) {
370 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() {
376 // Simplify the CFG for future analysis, and code generation:
377 // (1): Split critical edges.
378 // (2): Simplify loops by having only one back edge, and 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 Brazdilffee3d32015-07-06 11:48:53 +0100384 if (block->NumberOfNormalSuccessors() > 1) {
Vladimir Marko60584552015-09-03 13:35:12 +0000385 for (size_t j = 0; j < block->GetSuccessors().size(); ++j) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100386 HBasicBlock* successor = block->GetSuccessors()[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100387 DCHECK(!successor->IsCatchBlock());
Vladimir Marko60584552015-09-03 13:35:12 +0000388 if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100389 SplitCriticalEdge(block, successor);
390 --j;
391 }
392 }
393 }
394 if (block->IsLoopHeader()) {
395 SimplifyLoop(block);
396 }
397 }
398}
399
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000400bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100401 // Order does not matter.
402 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
403 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100404 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100405 if (block->IsCatchBlock()) {
406 // TODO: Dealing with exceptional back edges could be tricky because
407 // they only approximate the real control flow. Bail out for now.
408 return false;
409 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100410 HLoopInformation* info = block->GetLoopInformation();
411 if (!info->Populate()) {
412 // Abort if the loop is non natural. We currently bailout in such cases.
413 return false;
414 }
415 }
416 }
417 return true;
418}
419
David Brazdil8d5b8b22015-03-24 10:51:52 +0000420void HGraph::InsertConstant(HConstant* constant) {
421 // New constants are inserted before the final control-flow instruction
422 // of the graph, or at its end if called from the graph builder.
423 if (entry_block_->EndsWithControlFlowInstruction()) {
424 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000425 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000426 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000427 }
428}
429
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600430HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100431 // For simplicity, don't bother reviving the cached null constant if it is
432 // not null and not in a block. Otherwise, we need to clear the instruction
433 // id and/or any invariants the graph is assuming when adding new instructions.
434 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600435 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000436 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000437 }
438 return cached_null_constant_;
439}
440
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100441HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100442 // For simplicity, don't bother reviving the cached current method if it is
443 // not null and not in a block. Otherwise, we need to clear the instruction
444 // id and/or any invariants the graph is assuming when adding new instructions.
445 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700446 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600447 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
448 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100449 if (entry_block_->GetFirstInstruction() == nullptr) {
450 entry_block_->AddInstruction(cached_current_method_);
451 } else {
452 entry_block_->InsertInstructionBefore(
453 cached_current_method_, entry_block_->GetFirstInstruction());
454 }
455 }
456 return cached_current_method_;
457}
458
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600459HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000460 switch (type) {
461 case Primitive::Type::kPrimBoolean:
462 DCHECK(IsUint<1>(value));
463 FALLTHROUGH_INTENDED;
464 case Primitive::Type::kPrimByte:
465 case Primitive::Type::kPrimChar:
466 case Primitive::Type::kPrimShort:
467 case Primitive::Type::kPrimInt:
468 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600469 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000470
471 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600472 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000473
474 default:
475 LOG(FATAL) << "Unsupported constant type";
476 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000477 }
David Brazdil46e2a392015-03-16 17:31:52 +0000478}
479
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000480void HGraph::CacheFloatConstant(HFloatConstant* constant) {
481 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
482 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
483 cached_float_constants_.Overwrite(value, constant);
484}
485
486void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
487 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
488 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
489 cached_double_constants_.Overwrite(value, constant);
490}
491
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000492void HLoopInformation::Add(HBasicBlock* block) {
493 blocks_.SetBit(block->GetBlockId());
494}
495
David Brazdil46e2a392015-03-16 17:31:52 +0000496void HLoopInformation::Remove(HBasicBlock* block) {
497 blocks_.ClearBit(block->GetBlockId());
498}
499
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100500void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
501 if (blocks_.IsBitSet(block->GetBlockId())) {
502 return;
503 }
504
505 blocks_.SetBit(block->GetBlockId());
506 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000507 for (HBasicBlock* predecessor : block->GetPredecessors()) {
508 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100509 }
510}
511
512bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100513 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100514 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100515 DCHECK(back_edge->GetDominator() != nullptr);
516 if (!header_->Dominates(back_edge)) {
517 // This loop is not natural. Do not bother going further.
518 return false;
519 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100520
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100521 // Populate this loop: starting with the back edge, recursively add predecessors
522 // that are not already part of that loop. Set the header as part of the loop
523 // to end the recursion.
524 // This is a recursive implementation of the algorithm described in
525 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
526 blocks_.SetBit(header_->GetBlockId());
527 PopulateRecursive(back_edge);
528 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100529 return true;
530}
531
David Brazdila4b8c212015-05-07 09:59:30 +0100532void HLoopInformation::Update() {
533 HGraph* graph = header_->GetGraph();
534 for (uint32_t id : blocks_.Indexes()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100535 HBasicBlock* block = graph->GetBlocks()[id];
David Brazdila4b8c212015-05-07 09:59:30 +0100536 // Reset loop information of non-header blocks inside the loop, except
537 // members of inner nested loops because those should already have been
538 // updated by their own LoopInformation.
539 if (block->GetLoopInformation() == this && block != header_) {
540 block->SetLoopInformation(nullptr);
541 }
542 }
543 blocks_.ClearAllBits();
544
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100545 if (back_edges_.empty()) {
David Brazdila4b8c212015-05-07 09:59:30 +0100546 // The loop has been dismantled, delete its suspend check and remove info
547 // from the header.
548 DCHECK(HasSuspendCheck());
549 header_->RemoveInstruction(suspend_check_);
550 header_->SetLoopInformation(nullptr);
551 header_ = nullptr;
552 suspend_check_ = nullptr;
553 } else {
554 if (kIsDebugBuild) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100555 for (HBasicBlock* back_edge : back_edges_) {
556 DCHECK(header_->Dominates(back_edge));
David Brazdila4b8c212015-05-07 09:59:30 +0100557 }
558 }
559 // This loop still has reachable back edges. Repopulate the list of blocks.
560 bool populate_successful = Populate();
561 DCHECK(populate_successful);
562 }
563}
564
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100565HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100566 return header_->GetDominator();
567}
568
569bool HLoopInformation::Contains(const HBasicBlock& block) const {
570 return blocks_.IsBitSet(block.GetBlockId());
571}
572
573bool HLoopInformation::IsIn(const HLoopInformation& other) const {
574 return other.blocks_.IsBitSet(header_->GetBlockId());
575}
576
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100577size_t HLoopInformation::GetLifetimeEnd() const {
578 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100579 for (HBasicBlock* back_edge : GetBackEdges()) {
580 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100581 }
582 return last_position;
583}
584
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100585bool HBasicBlock::Dominates(HBasicBlock* other) const {
586 // Walk up the dominator tree from `other`, to find out if `this`
587 // is an ancestor.
588 HBasicBlock* current = other;
589 while (current != nullptr) {
590 if (current == this) {
591 return true;
592 }
593 current = current->GetDominator();
594 }
595 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100596}
597
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100598static void UpdateInputsUsers(HInstruction* instruction) {
599 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
600 instruction->InputAt(i)->AddUseAt(instruction, i);
601 }
602 // Environment should be created later.
603 DCHECK(!instruction->HasEnvironment());
604}
605
Roland Levillainccc07a92014-09-16 14:48:16 +0100606void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
607 HInstruction* replacement) {
608 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400609 if (initial->IsControlFlow()) {
610 // We can only replace a control flow instruction with another control flow instruction.
611 DCHECK(replacement->IsControlFlow());
612 DCHECK_EQ(replacement->GetId(), -1);
613 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
614 DCHECK_EQ(initial->GetBlock(), this);
615 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
616 DCHECK(initial->GetUses().IsEmpty());
617 DCHECK(initial->GetEnvUses().IsEmpty());
618 replacement->SetBlock(this);
619 replacement->SetId(GetGraph()->GetNextInstructionId());
620 instructions_.InsertInstructionBefore(replacement, initial);
621 UpdateInputsUsers(replacement);
622 } else {
623 InsertInstructionBefore(replacement, initial);
624 initial->ReplaceWith(replacement);
625 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100626 RemoveInstruction(initial);
627}
628
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100629static void Add(HInstructionList* instruction_list,
630 HBasicBlock* block,
631 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000632 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000633 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100634 instruction->SetBlock(block);
635 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100636 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100637 instruction_list->AddInstruction(instruction);
638}
639
640void HBasicBlock::AddInstruction(HInstruction* instruction) {
641 Add(&instructions_, this, instruction);
642}
643
644void HBasicBlock::AddPhi(HPhi* phi) {
645 Add(&phis_, this, phi);
646}
647
David Brazdilc3d743f2015-04-22 13:40:50 +0100648void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
649 DCHECK(!cursor->IsPhi());
650 DCHECK(!instruction->IsPhi());
651 DCHECK_EQ(instruction->GetId(), -1);
652 DCHECK_NE(cursor->GetId(), -1);
653 DCHECK_EQ(cursor->GetBlock(), this);
654 DCHECK(!instruction->IsControlFlow());
655 instruction->SetBlock(this);
656 instruction->SetId(GetGraph()->GetNextInstructionId());
657 UpdateInputsUsers(instruction);
658 instructions_.InsertInstructionBefore(instruction, cursor);
659}
660
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100661void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
662 DCHECK(!cursor->IsPhi());
663 DCHECK(!instruction->IsPhi());
664 DCHECK_EQ(instruction->GetId(), -1);
665 DCHECK_NE(cursor->GetId(), -1);
666 DCHECK_EQ(cursor->GetBlock(), this);
667 DCHECK(!instruction->IsControlFlow());
668 DCHECK(!cursor->IsControlFlow());
669 instruction->SetBlock(this);
670 instruction->SetId(GetGraph()->GetNextInstructionId());
671 UpdateInputsUsers(instruction);
672 instructions_.InsertInstructionAfter(instruction, cursor);
673}
674
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100675void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
676 DCHECK_EQ(phi->GetId(), -1);
677 DCHECK_NE(cursor->GetId(), -1);
678 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100679 phi->SetBlock(this);
680 phi->SetId(GetGraph()->GetNextInstructionId());
681 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100682 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100683}
684
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100685static void Remove(HInstructionList* instruction_list,
686 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000687 HInstruction* instruction,
688 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100689 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100690 instruction->SetBlock(nullptr);
691 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000692 if (ensure_safety) {
693 DCHECK(instruction->GetUses().IsEmpty());
694 DCHECK(instruction->GetEnvUses().IsEmpty());
695 RemoveAsUser(instruction);
696 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100697}
698
David Brazdil1abb4192015-02-17 18:33:36 +0000699void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100700 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000701 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100702}
703
David Brazdil1abb4192015-02-17 18:33:36 +0000704void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
705 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100706}
707
David Brazdilc7508e92015-04-27 13:28:57 +0100708void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
709 if (instruction->IsPhi()) {
710 RemovePhi(instruction->AsPhi(), ensure_safety);
711 } else {
712 RemoveInstruction(instruction, ensure_safety);
713 }
714}
715
Vladimir Marko71bf8092015-09-15 15:33:14 +0100716void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
717 for (size_t i = 0; i < locals.size(); i++) {
718 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100719 SetRawEnvAt(i, instruction);
720 if (instruction != nullptr) {
721 instruction->AddEnvUseAt(this, i);
722 }
723 }
724}
725
David Brazdiled596192015-01-23 10:39:45 +0000726void HEnvironment::CopyFrom(HEnvironment* env) {
727 for (size_t i = 0; i < env->Size(); i++) {
728 HInstruction* instruction = env->GetInstructionAt(i);
729 SetRawEnvAt(i, instruction);
730 if (instruction != nullptr) {
731 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100732 }
David Brazdiled596192015-01-23 10:39:45 +0000733 }
734}
735
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700736void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
737 HBasicBlock* loop_header) {
738 DCHECK(loop_header->IsLoopHeader());
739 for (size_t i = 0; i < env->Size(); i++) {
740 HInstruction* instruction = env->GetInstructionAt(i);
741 SetRawEnvAt(i, instruction);
742 if (instruction == nullptr) {
743 continue;
744 }
745 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
746 // At the end of the loop pre-header, the corresponding value for instruction
747 // is the first input of the phi.
748 HInstruction* initial = instruction->AsPhi()->InputAt(0);
749 DCHECK(initial->GetBlock()->Dominates(loop_header));
750 SetRawEnvAt(i, initial);
751 initial->AddEnvUseAt(this, i);
752 } else {
753 instruction->AddEnvUseAt(this, i);
754 }
755 }
756}
757
David Brazdil1abb4192015-02-17 18:33:36 +0000758void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100759 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000760 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100761}
762
Calin Juravle77520bc2015-01-12 18:45:46 +0000763HInstruction* HInstruction::GetNextDisregardingMoves() const {
764 HInstruction* next = GetNext();
765 while (next != nullptr && next->IsParallelMove()) {
766 next = next->GetNext();
767 }
768 return next;
769}
770
771HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
772 HInstruction* previous = GetPrevious();
773 while (previous != nullptr && previous->IsParallelMove()) {
774 previous = previous->GetPrevious();
775 }
776 return previous;
777}
778
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100779void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000780 if (first_instruction_ == nullptr) {
781 DCHECK(last_instruction_ == nullptr);
782 first_instruction_ = last_instruction_ = instruction;
783 } else {
784 last_instruction_->next_ = instruction;
785 instruction->previous_ = last_instruction_;
786 last_instruction_ = instruction;
787 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000788}
789
David Brazdilc3d743f2015-04-22 13:40:50 +0100790void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
791 DCHECK(Contains(cursor));
792 if (cursor == first_instruction_) {
793 cursor->previous_ = instruction;
794 instruction->next_ = cursor;
795 first_instruction_ = instruction;
796 } else {
797 instruction->previous_ = cursor->previous_;
798 instruction->next_ = cursor;
799 cursor->previous_ = instruction;
800 instruction->previous_->next_ = instruction;
801 }
802}
803
804void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
805 DCHECK(Contains(cursor));
806 if (cursor == last_instruction_) {
807 cursor->next_ = instruction;
808 instruction->previous_ = cursor;
809 last_instruction_ = instruction;
810 } else {
811 instruction->next_ = cursor->next_;
812 instruction->previous_ = cursor;
813 cursor->next_ = instruction;
814 instruction->next_->previous_ = instruction;
815 }
816}
817
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100818void HInstructionList::RemoveInstruction(HInstruction* instruction) {
819 if (instruction->previous_ != nullptr) {
820 instruction->previous_->next_ = instruction->next_;
821 }
822 if (instruction->next_ != nullptr) {
823 instruction->next_->previous_ = instruction->previous_;
824 }
825 if (instruction == first_instruction_) {
826 first_instruction_ = instruction->next_;
827 }
828 if (instruction == last_instruction_) {
829 last_instruction_ = instruction->previous_;
830 }
831}
832
Roland Levillain6b469232014-09-25 10:10:38 +0100833bool HInstructionList::Contains(HInstruction* instruction) const {
834 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
835 if (it.Current() == instruction) {
836 return true;
837 }
838 }
839 return false;
840}
841
Roland Levillainccc07a92014-09-16 14:48:16 +0100842bool HInstructionList::FoundBefore(const HInstruction* instruction1,
843 const HInstruction* instruction2) const {
844 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
845 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
846 if (it.Current() == instruction1) {
847 return true;
848 }
849 if (it.Current() == instruction2) {
850 return false;
851 }
852 }
853 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
854 return true;
855}
856
Roland Levillain6c82d402014-10-13 16:10:27 +0100857bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
858 if (other_instruction == this) {
859 // An instruction does not strictly dominate itself.
860 return false;
861 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100862 HBasicBlock* block = GetBlock();
863 HBasicBlock* other_block = other_instruction->GetBlock();
864 if (block != other_block) {
865 return GetBlock()->Dominates(other_instruction->GetBlock());
866 } else {
867 // If both instructions are in the same block, ensure this
868 // instruction comes before `other_instruction`.
869 if (IsPhi()) {
870 if (!other_instruction->IsPhi()) {
871 // Phis appear before non phi-instructions so this instruction
872 // dominates `other_instruction`.
873 return true;
874 } else {
875 // There is no order among phis.
876 LOG(FATAL) << "There is no dominance between phis of a same block.";
877 return false;
878 }
879 } else {
880 // `this` is not a phi.
881 if (other_instruction->IsPhi()) {
882 // Phis appear before non phi-instructions so this instruction
883 // does not dominate `other_instruction`.
884 return false;
885 } else {
886 // Check whether this instruction comes before
887 // `other_instruction` in the instruction list.
888 return block->GetInstructions().FoundBefore(this, other_instruction);
889 }
890 }
891 }
892}
893
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100894void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100895 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000896 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
897 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100898 HInstruction* user = current->GetUser();
899 size_t input_index = current->GetIndex();
900 user->SetRawInputAt(input_index, other);
901 other->AddUseAt(user, input_index);
902 }
903
David Brazdiled596192015-01-23 10:39:45 +0000904 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
905 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100906 HEnvironment* user = current->GetUser();
907 size_t input_index = current->GetIndex();
908 user->SetRawEnvAt(input_index, other);
909 other->AddEnvUseAt(user, input_index);
910 }
911
David Brazdiled596192015-01-23 10:39:45 +0000912 uses_.Clear();
913 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100914}
915
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100916void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000917 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100918 SetRawInputAt(index, replacement);
919 replacement->AddUseAt(this, index);
920}
921
Nicolas Geoffray39468442014-09-02 15:17:15 +0100922size_t HInstruction::EnvironmentSize() const {
923 return HasEnvironment() ? environment_->Size() : 0;
924}
925
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100926void HPhi::AddInput(HInstruction* input) {
927 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100928 inputs_.push_back(HUserRecord<HInstruction*>(input));
929 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100930}
931
David Brazdil2d7352b2015-04-20 14:52:42 +0100932void HPhi::RemoveInputAt(size_t index) {
933 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100934 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100935 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100936 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100937 InputRecordAt(i).GetUseNode()->SetIndex(i);
938 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100939}
940
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100941#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000942void H##name::Accept(HGraphVisitor* visitor) { \
943 visitor->Visit##name(this); \
944}
945
946FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
947
948#undef DEFINE_ACCEPT
949
950void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100951 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
952 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +0000953 if (block != nullptr) {
954 VisitBasicBlock(block);
955 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000956 }
957}
958
Roland Levillain633021e2014-10-01 14:12:25 +0100959void HGraphVisitor::VisitReversePostOrder() {
960 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
961 VisitBasicBlock(it.Current());
962 }
963}
964
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000965void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100966 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100967 it.Current()->Accept(this);
968 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100969 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000970 it.Current()->Accept(this);
971 }
972}
973
Mark Mendelle82549b2015-05-06 10:55:34 -0400974HConstant* HTypeConversion::TryStaticEvaluation() const {
975 HGraph* graph = GetBlock()->GetGraph();
976 if (GetInput()->IsIntConstant()) {
977 int32_t value = GetInput()->AsIntConstant()->GetValue();
978 switch (GetResultType()) {
979 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600980 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400981 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600982 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400983 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600984 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400985 default:
986 return nullptr;
987 }
988 } else if (GetInput()->IsLongConstant()) {
989 int64_t value = GetInput()->AsLongConstant()->GetValue();
990 switch (GetResultType()) {
991 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600992 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400993 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600994 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400995 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600996 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -0400997 default:
998 return nullptr;
999 }
1000 } else if (GetInput()->IsFloatConstant()) {
1001 float value = GetInput()->AsFloatConstant()->GetValue();
1002 switch (GetResultType()) {
1003 case Primitive::kPrimInt:
1004 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001005 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001006 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001007 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001008 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001009 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1010 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001011 case Primitive::kPrimLong:
1012 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001013 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001014 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001015 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001016 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001017 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1018 return graph->GetLongConstant(static_cast<int64_t>(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()->IsDoubleConstant()) {
1025 double value = GetInput()->AsDoubleConstant()->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 <= kPrimLongMin)
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::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001044 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001045 default:
1046 return nullptr;
1047 }
1048 }
1049 return nullptr;
1050}
1051
Roland Levillain9240d6a2014-10-20 16:47:04 +01001052HConstant* HUnaryOperation::TryStaticEvaluation() const {
1053 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001054 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001055 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001056 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001057 }
1058 return nullptr;
1059}
1060
1061HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001062 if (GetLeft()->IsIntConstant()) {
1063 if (GetRight()->IsIntConstant()) {
1064 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1065 } else if (GetRight()->IsLongConstant()) {
1066 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1067 }
1068 } else if (GetLeft()->IsLongConstant()) {
1069 if (GetRight()->IsIntConstant()) {
1070 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1071 } else if (GetRight()->IsLongConstant()) {
1072 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001073 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001074 }
1075 return nullptr;
1076}
Dave Allison20dfc792014-06-16 20:44:29 -07001077
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001078HConstant* HBinaryOperation::GetConstantRight() const {
1079 if (GetRight()->IsConstant()) {
1080 return GetRight()->AsConstant();
1081 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1082 return GetLeft()->AsConstant();
1083 } else {
1084 return nullptr;
1085 }
1086}
1087
1088// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001089// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001090HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1091 HInstruction* most_constant_right = GetConstantRight();
1092 if (most_constant_right == nullptr) {
1093 return nullptr;
1094 } else if (most_constant_right == GetLeft()) {
1095 return GetRight();
1096 } else {
1097 return GetLeft();
1098 }
1099}
1100
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001101bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1102 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001103}
1104
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001105bool HInstruction::Equals(HInstruction* other) const {
1106 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001107 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001108 if (!InstructionDataEquals(other)) return false;
1109 if (GetType() != other->GetType()) return false;
1110 if (InputCount() != other->InputCount()) return false;
1111
1112 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1113 if (InputAt(i) != other->InputAt(i)) return false;
1114 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001115 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001116 return true;
1117}
1118
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001119std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1120#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1121 switch (rhs) {
1122 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1123 default:
1124 os << "Unknown instruction kind " << static_cast<int>(rhs);
1125 break;
1126 }
1127#undef DECLARE_CASE
1128 return os;
1129}
1130
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001131void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001132 next_->previous_ = previous_;
1133 if (previous_ != nullptr) {
1134 previous_->next_ = next_;
1135 }
1136 if (block_->instructions_.first_instruction_ == this) {
1137 block_->instructions_.first_instruction_ = next_;
1138 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001139 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001140
1141 previous_ = cursor->previous_;
1142 if (previous_ != nullptr) {
1143 previous_->next_ = this;
1144 }
1145 next_ = cursor;
1146 cursor->previous_ = this;
1147 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001148
1149 if (block_->instructions_.first_instruction_ == cursor) {
1150 block_->instructions_.first_instruction_ = this;
1151 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001152}
1153
David Brazdilfc6a86a2015-06-26 10:33:45 +00001154HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
1155 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented";
1156 DCHECK_EQ(cursor->GetBlock(), this);
1157
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001158 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1159 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001160 new_block->instructions_.first_instruction_ = cursor;
1161 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1162 instructions_.last_instruction_ = cursor->previous_;
1163 if (cursor->previous_ == nullptr) {
1164 instructions_.first_instruction_ = nullptr;
1165 } else {
1166 cursor->previous_->next_ = nullptr;
1167 cursor->previous_ = nullptr;
1168 }
1169
1170 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001171 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001172
Vladimir Marko60584552015-09-03 13:35:12 +00001173 for (HBasicBlock* successor : GetSuccessors()) {
1174 new_block->successors_.push_back(successor);
1175 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001176 }
Vladimir Marko60584552015-09-03 13:35:12 +00001177 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001178 AddSuccessor(new_block);
1179
David Brazdil56e1acc2015-06-30 15:41:36 +01001180 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001181 return new_block;
1182}
1183
David Brazdild7558da2015-09-22 13:04:14 +01001184HBasicBlock* HBasicBlock::CreateImmediateDominator() {
1185 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented";
1186 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1187
1188 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1189
1190 for (HBasicBlock* predecessor : GetPredecessors()) {
1191 new_block->predecessors_.push_back(predecessor);
1192 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1193 }
1194 predecessors_.clear();
1195 AddPredecessor(new_block);
1196
1197 GetGraph()->AddBlock(new_block);
1198 return new_block;
1199}
1200
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001201HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1202 DCHECK(!cursor->IsControlFlow());
1203 DCHECK_NE(instructions_.last_instruction_, cursor);
1204 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001205
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001206 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1207 new_block->instructions_.first_instruction_ = cursor->GetNext();
1208 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1209 cursor->next_->previous_ = nullptr;
1210 cursor->next_ = nullptr;
1211 instructions_.last_instruction_ = cursor;
1212
1213 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001214 for (HBasicBlock* successor : GetSuccessors()) {
1215 new_block->successors_.push_back(successor);
1216 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001217 }
Vladimir Marko60584552015-09-03 13:35:12 +00001218 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001219
Vladimir Marko60584552015-09-03 13:35:12 +00001220 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001221 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001222 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001223 }
Vladimir Marko60584552015-09-03 13:35:12 +00001224 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001225 return new_block;
1226}
1227
David Brazdilec16f792015-08-19 15:04:01 +01001228const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001229 if (EndsWithTryBoundary()) {
1230 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1231 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001232 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001233 return try_boundary;
1234 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001235 DCHECK(IsTryBlock());
1236 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001237 return nullptr;
1238 }
David Brazdilec16f792015-08-19 15:04:01 +01001239 } else if (IsTryBlock()) {
1240 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001241 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001242 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001243 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001244}
1245
David Brazdild7558da2015-09-22 13:04:14 +01001246bool HBasicBlock::HasThrowingInstructions() const {
1247 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1248 if (it.Current()->CanThrow()) {
1249 return true;
1250 }
1251 }
1252 return false;
1253}
1254
David Brazdilfc6a86a2015-06-26 10:33:45 +00001255static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1256 return block.GetPhis().IsEmpty()
1257 && !block.GetInstructions().IsEmpty()
1258 && block.GetFirstInstruction() == block.GetLastInstruction();
1259}
1260
David Brazdil46e2a392015-03-16 17:31:52 +00001261bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001262 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1263}
1264
1265bool HBasicBlock::IsSingleTryBoundary() const {
1266 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001267}
1268
David Brazdil8d5b8b22015-03-24 10:51:52 +00001269bool HBasicBlock::EndsWithControlFlowInstruction() const {
1270 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1271}
1272
David Brazdilb2bd1c52015-03-25 11:17:37 +00001273bool HBasicBlock::EndsWithIf() const {
1274 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1275}
1276
David Brazdilffee3d32015-07-06 11:48:53 +01001277bool HBasicBlock::EndsWithTryBoundary() const {
1278 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1279}
1280
David Brazdilb2bd1c52015-03-25 11:17:37 +00001281bool HBasicBlock::HasSinglePhi() const {
1282 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1283}
1284
David Brazdilffee3d32015-07-06 11:48:53 +01001285bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
Vladimir Marko60584552015-09-03 13:35:12 +00001286 if (GetBlock()->GetSuccessors().size() != other.GetBlock()->GetSuccessors().size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001287 return false;
1288 }
1289
David Brazdilb618ade2015-07-29 10:31:29 +01001290 // Exception handlers need to be stored in the same order.
1291 for (HExceptionHandlerIterator it1(*this), it2(other);
1292 !it1.Done();
1293 it1.Advance(), it2.Advance()) {
1294 DCHECK(!it2.Done());
1295 if (it1.Current() != it2.Current()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001296 return false;
1297 }
1298 }
1299 return true;
1300}
1301
David Brazdil2d7352b2015-04-20 14:52:42 +01001302size_t HInstructionList::CountSize() const {
1303 size_t size = 0;
1304 HInstruction* current = first_instruction_;
1305 for (; current != nullptr; current = current->GetNext()) {
1306 size++;
1307 }
1308 return size;
1309}
1310
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001311void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1312 for (HInstruction* current = first_instruction_;
1313 current != nullptr;
1314 current = current->GetNext()) {
1315 current->SetBlock(block);
1316 }
1317}
1318
1319void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1320 DCHECK(Contains(cursor));
1321 if (!instruction_list.IsEmpty()) {
1322 if (cursor == last_instruction_) {
1323 last_instruction_ = instruction_list.last_instruction_;
1324 } else {
1325 cursor->next_->previous_ = instruction_list.last_instruction_;
1326 }
1327 instruction_list.last_instruction_->next_ = cursor->next_;
1328 cursor->next_ = instruction_list.first_instruction_;
1329 instruction_list.first_instruction_->previous_ = cursor;
1330 }
1331}
1332
1333void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001334 if (IsEmpty()) {
1335 first_instruction_ = instruction_list.first_instruction_;
1336 last_instruction_ = instruction_list.last_instruction_;
1337 } else {
1338 AddAfter(last_instruction_, instruction_list);
1339 }
1340}
1341
David Brazdil2d7352b2015-04-20 14:52:42 +01001342void HBasicBlock::DisconnectAndDelete() {
1343 // Dominators must be removed after all the blocks they dominate. This way
1344 // a loop header is removed last, a requirement for correct loop information
1345 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001346 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001347
David Brazdil2d7352b2015-04-20 14:52:42 +01001348 // Remove the block from all loops it is included in.
1349 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1350 HLoopInformation* loop_info = it.Current();
1351 loop_info->Remove(this);
1352 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001353 // If this was the last back edge of the loop, we deliberately leave the
1354 // loop in an inconsistent state and will fail SSAChecker unless the
1355 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001356 loop_info->RemoveBackEdge(this);
1357 }
1358 }
1359
1360 // Disconnect the block from its predecessors and update their control-flow
1361 // instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001362 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001363 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil2d7352b2015-04-20 14:52:42 +01001364 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001365 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1366 if (num_pred_successors == 1u) {
1367 // If we have one successor after removing one, then we must have
1368 // had an HIf or HPackedSwitch, as they have more than one successor.
1369 // Replace those with a HGoto.
1370 DCHECK(last_instruction->IsIf() || last_instruction->IsPackedSwitch());
1371 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001372 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001373 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001374 // The predecessor has no remaining successors and therefore must be dead.
1375 // We deliberately leave it without a control-flow instruction so that the
1376 // SSAChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001377 predecessor->RemoveInstruction(last_instruction);
1378 } else {
1379 // There are multiple successors left. This must come from a HPackedSwitch
1380 // and we are in the middle of removing the HPackedSwitch. Like above, leave
1381 // this alone, and the SSAChecker will fail if it is not removed as well.
1382 DCHECK(last_instruction->IsPackedSwitch());
David Brazdil2d7352b2015-04-20 14:52:42 +01001383 }
David Brazdil46e2a392015-03-16 17:31:52 +00001384 }
Vladimir Marko60584552015-09-03 13:35:12 +00001385 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001386
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +01001387 // Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001388 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001389 // Delete this block from the list of predecessors.
1390 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001391 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001392
1393 // Check that `successor` has other predecessors, otherwise `this` is the
1394 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001395 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001396
David Brazdil2d7352b2015-04-20 14:52:42 +01001397 // Remove this block's entries in the successor's phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001398 if (successor->predecessors_.size() == 1u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001399 // The successor has just one predecessor left. Replace phis with the only
1400 // remaining input.
1401 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1402 HPhi* phi = phi_it.Current()->AsPhi();
1403 phi->ReplaceWith(phi->InputAt(1 - this_index));
1404 successor->RemovePhi(phi);
1405 }
1406 } else {
1407 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1408 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1409 }
1410 }
1411 }
Vladimir Marko60584552015-09-03 13:35:12 +00001412 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001413
1414 // Disconnect from the dominator.
1415 dominator_->RemoveDominatedBlock(this);
1416 SetDominator(nullptr);
1417
1418 // Delete from the graph. The function safely deletes remaining instructions
1419 // and updates the reverse post order.
1420 graph_->DeleteDeadBlock(this);
1421 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001422}
1423
1424void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001425 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001426 DCHECK(ContainsElement(dominated_blocks_, other));
1427 DCHECK_EQ(GetSingleSuccessor(), other);
1428 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001429 DCHECK(other->GetPhis().IsEmpty());
1430
David Brazdil2d7352b2015-04-20 14:52:42 +01001431 // Move instructions from `other` to `this`.
1432 DCHECK(EndsWithControlFlowInstruction());
1433 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001434 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001435 other->instructions_.SetBlockOfInstructions(this);
1436 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001437
David Brazdil2d7352b2015-04-20 14:52:42 +01001438 // Remove `other` from the loops it is included in.
1439 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1440 HLoopInformation* loop_info = it.Current();
1441 loop_info->Remove(other);
1442 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001443 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001444 }
1445 }
1446
1447 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001448 successors_.clear();
1449 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001450 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001451 successor->ReplacePredecessor(other, this);
1452 }
1453
David Brazdil2d7352b2015-04-20 14:52:42 +01001454 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001455 RemoveDominatedBlock(other);
1456 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1457 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001458 dominated->SetDominator(this);
1459 }
Vladimir Marko60584552015-09-03 13:35:12 +00001460 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001461 other->dominator_ = nullptr;
1462
1463 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001464 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001465
1466 // Delete `other` from the graph. The function updates reverse post order.
1467 graph_->DeleteDeadBlock(other);
1468 other->SetGraph(nullptr);
1469}
1470
1471void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1472 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001473 DCHECK(GetDominatedBlocks().empty());
1474 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001475 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001476 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001477 DCHECK(other->GetPhis().IsEmpty());
1478 DCHECK(!other->IsInLoop());
1479
1480 // Move instructions from `other` to `this`.
1481 instructions_.Add(other->GetInstructions());
1482 other->instructions_.SetBlockOfInstructions(this);
1483
1484 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001485 successors_.clear();
1486 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001487 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001488 successor->ReplacePredecessor(other, this);
1489 }
1490
1491 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001492 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1493 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001494 dominated->SetDominator(this);
1495 }
Vladimir Marko60584552015-09-03 13:35:12 +00001496 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001497 other->dominator_ = nullptr;
1498 other->graph_ = nullptr;
1499}
1500
1501void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001502 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001503 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001504 predecessor->ReplaceSuccessor(this, other);
1505 }
Vladimir Marko60584552015-09-03 13:35:12 +00001506 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001507 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001508 successor->ReplacePredecessor(this, other);
1509 }
Vladimir Marko60584552015-09-03 13:35:12 +00001510 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1511 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001512 }
1513 GetDominator()->ReplaceDominatedBlock(this, other);
1514 other->SetDominator(GetDominator());
1515 dominator_ = nullptr;
1516 graph_ = nullptr;
1517}
1518
1519// Create space in `blocks` for adding `number_of_new_blocks` entries
1520// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001521static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001522 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001523 size_t after) {
1524 DCHECK_LT(after, blocks->size());
1525 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001526 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001527 blocks->resize(new_size);
1528 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001529}
1530
David Brazdil2d7352b2015-04-20 14:52:42 +01001531void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1532 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001533 DCHECK(block->GetSuccessors().empty());
1534 DCHECK(block->GetPredecessors().empty());
1535 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001536 DCHECK(block->GetDominator() == nullptr);
1537
1538 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1539 block->RemoveInstruction(it.Current());
1540 }
1541 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1542 block->RemovePhi(it.Current()->AsPhi());
1543 }
1544
David Brazdilc7af85d2015-05-26 12:05:55 +01001545 if (block->IsExitBlock()) {
1546 exit_block_ = nullptr;
1547 }
1548
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001549 RemoveElement(reverse_post_order_, block);
1550 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001551}
1552
Calin Juravle2e768302015-07-28 14:41:11 +00001553HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001554 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001555 // Update the environments in this graph to have the invoke's environment
1556 // as parent.
1557 {
1558 HReversePostOrderIterator it(*this);
1559 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1560 for (; !it.Done(); it.Advance()) {
1561 HBasicBlock* block = it.Current();
1562 for (HInstructionIterator instr_it(block->GetInstructions());
1563 !instr_it.Done();
1564 instr_it.Advance()) {
1565 HInstruction* current = instr_it.Current();
1566 if (current->NeedsEnvironment()) {
1567 current->GetEnvironment()->SetAndCopyParentChain(
1568 outer_graph->GetArena(), invoke->GetEnvironment());
1569 }
1570 }
1571 }
1572 }
1573 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1574 if (HasBoundsChecks()) {
1575 outer_graph->SetHasBoundsChecks(true);
1576 }
1577
Calin Juravle2e768302015-07-28 14:41:11 +00001578 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001579 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001580 // Simple case of an entry block, a body block, and an exit block.
1581 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001582 HBasicBlock* body = GetBlocks()[1];
1583 DCHECK(GetBlocks()[0]->IsEntryBlock());
1584 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001585 DCHECK(!body->IsExitBlock());
1586 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001587
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001588 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1589 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001590
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001591 // Replace the invoke with the return value of the inlined graph.
1592 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001593 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001594 } else {
1595 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001596 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001597
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001598 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001599 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001600 // Need to inline multiple blocks. We split `invoke`'s block
1601 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001602 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001603 // with the second half.
1604 ArenaAllocator* allocator = outer_graph->GetArena();
1605 HBasicBlock* at = invoke->GetBlock();
1606 HBasicBlock* to = at->SplitAfter(invoke);
1607
Vladimir Markoec7802a2015-10-01 20:57:57 +01001608 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001609 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001610 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001611 exit_block_->ReplaceWith(to);
1612
1613 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001614 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001615 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001616 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001617 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001618 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001619 if (!returns_void) {
1620 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001621 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001622 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001623 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001624 } else {
1625 if (!returns_void) {
1626 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001627 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001628 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001629 to->AddPhi(return_value->AsPhi());
1630 }
Vladimir Marko60584552015-09-03 13:35:12 +00001631 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001632 HInstruction* last = predecessor->GetLastInstruction();
1633 if (!returns_void) {
1634 return_value->AsPhi()->AddInput(last->InputAt(0));
1635 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001636 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001637 predecessor->RemoveInstruction(last);
1638 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001639 }
1640
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001641 // Update the meta information surrounding blocks:
1642 // (1) the graph they are now in,
1643 // (2) the reverse post order of that graph,
1644 // (3) the potential loop information they are now in.
1645
1646 // We don't add the entry block, the exit block, and the first block, which
1647 // has been merged with `at`.
1648 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1649
1650 // We add the `to` block.
1651 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001652 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001653 + kNumberOfNewBlocksInCaller;
1654
1655 // Find the location of `at` in the outer graph's reverse post order. The new
1656 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001657 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001658 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1659
1660 // Do a reverse post order of the blocks in the callee and do (1), (2),
1661 // and (3) to the blocks that apply.
1662 HLoopInformation* info = at->GetLoopInformation();
1663 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1664 HBasicBlock* current = it.Current();
1665 if (current != exit_block_ && current != entry_block_ && current != first) {
1666 DCHECK(!current->IsInLoop());
1667 DCHECK(current->GetGraph() == this);
1668 current->SetGraph(outer_graph);
1669 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001670 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001671 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001672 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001673 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1674 loop_it.Current()->Add(current);
1675 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001676 }
1677 }
1678 }
1679
1680 // Do (1), (2), and (3) to `to`.
1681 to->SetGraph(outer_graph);
1682 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001683 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001684 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001685 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001686 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1687 loop_it.Current()->Add(to);
1688 }
David Brazdil46e2a392015-03-16 17:31:52 +00001689 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001690 // Only `to` can become a back edge, as the inlined blocks
1691 // are predecessors of `to`.
1692 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001693 }
1694 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001695 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001696
David Brazdil05144f42015-04-16 15:18:00 +01001697 // Update the next instruction id of the outer graph, so that instructions
1698 // added later get bigger ids than those in the inner graph.
1699 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1700
1701 // Walk over the entry block and:
1702 // - Move constants from the entry block to the outer_graph's entry block,
1703 // - Replace HParameterValue instructions with their real value.
1704 // - Remove suspend checks, that hold an environment.
1705 // We must do this after the other blocks have been inlined, otherwise ids of
1706 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001707 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001708 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1709 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01001710 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01001711 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001712 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001713 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001714 replacement = outer_graph->GetIntConstant(
1715 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001716 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001717 replacement = outer_graph->GetLongConstant(
1718 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001719 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001720 replacement = outer_graph->GetFloatConstant(
1721 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001722 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001723 replacement = outer_graph->GetDoubleConstant(
1724 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001725 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001726 if (kIsDebugBuild
1727 && invoke->IsInvokeStaticOrDirect()
1728 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1729 // Ensure we do not use the last input of `invoke`, as it
1730 // contains a clinit check which is not an actual argument.
1731 size_t last_input_index = invoke->InputCount() - 1;
1732 DCHECK(parameter_index != last_input_index);
1733 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01001734 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001735 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001736 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01001737 } else {
1738 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1739 entry_block_->RemoveInstruction(current);
1740 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01001741 if (replacement != nullptr) {
1742 current->ReplaceWith(replacement);
1743 // If the current is the return value then we need to update the latter.
1744 if (current == return_value) {
1745 DCHECK_EQ(entry_block_, return_value->GetBlock());
1746 return_value = replacement;
1747 }
1748 }
1749 }
1750
1751 if (return_value != nullptr) {
1752 invoke->ReplaceWith(return_value);
David Brazdil05144f42015-04-16 15:18:00 +01001753 }
1754
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001755 // Finally remove the invoke from the caller.
1756 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00001757
1758 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001759}
1760
Mingyao Yang3584bce2015-05-19 16:01:59 -07001761/*
1762 * Loop will be transformed to:
1763 * old_pre_header
1764 * |
1765 * if_block
1766 * / \
1767 * dummy_block deopt_block
1768 * \ /
1769 * new_pre_header
1770 * |
1771 * header
1772 */
1773void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1774 DCHECK(header->IsLoopHeader());
1775 HBasicBlock* pre_header = header->GetDominator();
1776
1777 // Need this to avoid critical edge.
1778 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1779 // Need this to avoid critical edge.
1780 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1781 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1782 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1783 AddBlock(if_block);
1784 AddBlock(dummy_block);
1785 AddBlock(deopt_block);
1786 AddBlock(new_pre_header);
1787
1788 header->ReplacePredecessor(pre_header, new_pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001789 pre_header->successors_.clear();
1790 pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07001791
1792 pre_header->AddSuccessor(if_block);
1793 if_block->AddSuccessor(dummy_block); // True successor
1794 if_block->AddSuccessor(deopt_block); // False successor
1795 dummy_block->AddSuccessor(new_pre_header);
1796 deopt_block->AddSuccessor(new_pre_header);
1797
Vladimir Marko60584552015-09-03 13:35:12 +00001798 pre_header->dominated_blocks_.push_back(if_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001799 if_block->SetDominator(pre_header);
Vladimir Marko60584552015-09-03 13:35:12 +00001800 if_block->dominated_blocks_.push_back(dummy_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001801 dummy_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001802 if_block->dominated_blocks_.push_back(deopt_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001803 deopt_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001804 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001805 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001806 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001807 header->SetDominator(new_pre_header);
1808
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001809 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001810 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001811 reverse_post_order_[index_of_header++] = if_block;
1812 reverse_post_order_[index_of_header++] = dummy_block;
1813 reverse_post_order_[index_of_header++] = deopt_block;
1814 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001815
1816 HLoopInformation* info = pre_header->GetLoopInformation();
1817 if (info != nullptr) {
1818 if_block->SetLoopInformation(info);
1819 dummy_block->SetLoopInformation(info);
1820 deopt_block->SetLoopInformation(info);
1821 new_pre_header->SetLoopInformation(info);
1822 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1823 !loop_it.Done();
1824 loop_it.Advance()) {
1825 loop_it.Current()->Add(if_block);
1826 loop_it.Current()->Add(dummy_block);
1827 loop_it.Current()->Add(deopt_block);
1828 loop_it.Current()->Add(new_pre_header);
1829 }
1830 }
1831}
1832
Calin Juravle2e768302015-07-28 14:41:11 +00001833void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
1834 if (kIsDebugBuild) {
1835 DCHECK_EQ(GetType(), Primitive::kPrimNot);
1836 ScopedObjectAccess soa(Thread::Current());
1837 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
1838 if (IsBoundType()) {
1839 // Having the test here spares us from making the method virtual just for
1840 // the sake of a DCHECK.
1841 ReferenceTypeInfo upper_bound_rti = AsBoundType()->GetUpperBound();
1842 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
1843 << " upper_bound_rti: " << upper_bound_rti
1844 << " rti: " << rti;
David Brazdilbaf89b82015-09-15 11:36:54 +01001845 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00001846 }
1847 }
1848 reference_type_info_ = rti;
1849}
1850
1851ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
1852
1853ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
1854 : type_handle_(type_handle), is_exact_(is_exact) {
1855 if (kIsDebugBuild) {
1856 ScopedObjectAccess soa(Thread::Current());
1857 DCHECK(IsValidHandle(type_handle));
1858 }
1859}
1860
Calin Juravleacf735c2015-02-12 15:25:22 +00001861std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1862 ScopedObjectAccess soa(Thread::Current());
1863 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00001864 << " is_valid=" << rhs.IsValid()
1865 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00001866 << " is_exact=" << rhs.IsExact()
1867 << " ]";
1868 return os;
1869}
1870
Mark Mendellc4701932015-04-10 13:18:51 -04001871bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
1872 // For now, assume that instructions in different blocks may use the
1873 // environment.
1874 // TODO: Use the control flow to decide if this is true.
1875 if (GetBlock() != other->GetBlock()) {
1876 return true;
1877 }
1878
1879 // We know that we are in the same block. Walk from 'this' to 'other',
1880 // checking to see if there is any instruction with an environment.
1881 HInstruction* current = this;
1882 for (; current != other && current != nullptr; current = current->GetNext()) {
1883 // This is a conservative check, as the instruction result may not be in
1884 // the referenced environment.
1885 if (current->HasEnvironment()) {
1886 return true;
1887 }
1888 }
1889
1890 // We should have been called with 'this' before 'other' in the block.
1891 // Just confirm this.
1892 DCHECK(current != nullptr);
1893 return false;
1894}
1895
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001896void HInvoke::SetIntrinsic(Intrinsics intrinsic,
1897 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache) {
1898 intrinsic_ = intrinsic;
1899 IntrinsicOptimizations opt(this);
1900 if (needs_env_or_cache == kNoEnvironmentOrCache) {
1901 opt.SetDoesNotNeedDexCache();
1902 opt.SetDoesNotNeedEnvironment();
1903 }
1904}
1905
1906bool HInvoke::NeedsEnvironment() const {
1907 if (!IsIntrinsic()) {
1908 return true;
1909 }
1910 IntrinsicOptimizations opt(*this);
1911 return !opt.GetDoesNotNeedEnvironment();
1912}
1913
1914bool HInvokeStaticOrDirect::NeedsDexCache() const {
1915 if (IsRecursive() || IsStringInit()) {
1916 return false;
1917 }
1918 if (!IsIntrinsic()) {
1919 return true;
1920 }
1921 IntrinsicOptimizations opt(*this);
1922 return !opt.GetDoesNotNeedDexCache();
1923}
1924
Mark Mendellc4701932015-04-10 13:18:51 -04001925void HInstruction::RemoveEnvironmentUsers() {
1926 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
1927 HUseListNode<HEnvironment*>* user_node = use_it.Current();
1928 HEnvironment* user = user_node->GetUser();
1929 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
1930 }
1931 env_uses_.Clear();
1932}
1933
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001934} // namespace art