blob: 92f758d61d1273fbd59f57b83dbfe7a62069c77d [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 */
Nicolas Geoffray818f2102014-02-18 16:43:35 +000016#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000017
Mark Mendelle82549b2015-05-06 10:55:34 -040018#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000019#include "common_dominator.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 Geoffray15bd2282016-01-05 15:55:41 +000092 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010093 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000094 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
95 RemoveAsUser(it.Current());
96 }
97 }
98 }
99}
100
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100101void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100102 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000103 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100104 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000105 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100106 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000107 for (HBasicBlock* successor : block->GetSuccessors()) {
108 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000109 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100110 // Remove the block from the list of blocks, so that further analyses
111 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100112 blocks_[i] = nullptr;
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000113 }
114 }
115}
116
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000117GraphAnalysisResult HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100118 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
119 // edges. This invariant simplifies building SSA form because Phis cannot
120 // collect both normal- and exceptional-flow values at the same time.
121 SimplifyCatchBlocks();
122
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100123 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000124
David Brazdilffee3d32015-07-06 11:48:53 +0100125 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000126 FindBackEdges(&visited);
127
David Brazdilffee3d32015-07-06 11:48:53 +0100128 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000129 // the initial DFS as users from other instructions, so that
130 // users can be safely removed before uses later.
131 RemoveInstructionsAsUsersFromDeadBlocks(visited);
132
David Brazdilffee3d32015-07-06 11:48:53 +0100133 // (4) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000134 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000135 // predecessors list of live blocks.
136 RemoveDeadBlocks(visited);
137
David Brazdilffee3d32015-07-06 11:48:53 +0100138 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100139 // dominators and the reverse post order.
140 SimplifyCFG();
141
David Brazdilffee3d32015-07-06 11:48:53 +0100142 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100143 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000144
145 // (7) Analyze loops discover through back edge analysis, and
146 // set the loop information on each block.
147 GraphAnalysisResult result = AnalyzeLoops();
148 if (result != kAnalysisSuccess) {
149 return result;
150 }
151
152 // (8) Precompute per-block try membership before entering the SSA builder,
153 // which needs the information to build catch block phis from values of
154 // locals at throwing instructions inside try blocks.
155 ComputeTryBlockInformation();
156
157 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100158}
159
160void HGraph::ClearDominanceInformation() {
161 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
162 it.Current()->ClearDominanceInformation();
163 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100164 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100165}
166
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000167void HGraph::ClearLoopInformation() {
168 SetHasIrreducibleLoops(false);
169 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000170 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000171 }
172}
173
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100174void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000175 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100176 dominator_ = nullptr;
177}
178
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000179HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
180 HInstruction* instruction = GetFirstInstruction();
181 while (instruction->IsParallelMove()) {
182 instruction = instruction->GetNext();
183 }
184 return instruction;
185}
186
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100187void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100188 DCHECK(reverse_post_order_.empty());
189 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100190 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100191
192 // Number of visits of a given node, indexed by block id.
193 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
194 // Number of successors visited from a given node, indexed by block id.
195 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
196 // Nodes for which we need to visit successors.
197 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
198 constexpr size_t kDefaultWorklistSize = 8;
199 worklist.reserve(kDefaultWorklistSize);
200 worklist.push_back(entry_block_);
201
202 while (!worklist.empty()) {
203 HBasicBlock* current = worklist.back();
204 uint32_t current_id = current->GetBlockId();
205 if (successors_visited[current_id] == current->GetSuccessors().size()) {
206 worklist.pop_back();
207 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100208 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
209
210 if (successor->GetDominator() == nullptr) {
211 successor->SetDominator(current);
212 } else {
Vladimir Marko391d01f2015-11-06 11:02:08 +0000213 // The CommonDominator can work for multiple blocks as long as the
214 // domination information doesn't change. However, since we're changing
215 // that information here, we can use the finder only for pairs of blocks.
216 successor->SetDominator(CommonDominator::ForPair(successor->GetDominator(), current));
Vladimir Markod76d1392015-09-23 16:07:14 +0100217 }
218
219 // Once all the forward edges have been visited, we know the immediate
220 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100221 if (++visits[successor->GetBlockId()] ==
222 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100223 reverse_post_order_.push_back(successor);
224 worklist.push_back(successor);
225 }
226 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000227 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000228
229 // Populate `dominated_blocks_` information after computing all dominators.
230 // The potential presence of irreducible loops require to do it after.
231 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
232 HBasicBlock* block = it.Current();
233 if (!block->IsEntryBlock()) {
234 block->GetDominator()->AddDominatedBlock(block);
235 }
236 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000237}
238
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000239GraphAnalysisResult HGraph::TryBuildingSsa(StackHandleScopeCollection* handles) {
240 GraphAnalysisResult result = BuildDominatorTree();
241 if (result != kAnalysisSuccess) {
David Brazdil4833f5a2015-12-16 10:37:39 +0000242 return result;
243 }
244
David Brazdil4833f5a2015-12-16 10:37:39 +0000245 // Create the inexact Object reference type and store it in the HGraph.
246 ScopedObjectAccess soa(Thread::Current());
247 ClassLinker* linker = Runtime::Current()->GetClassLinker();
248 inexact_object_rti_ = ReferenceTypeInfo::Create(
249 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
250 /* is_exact */ false);
251
252 // Tranforms graph to SSA form.
253 result = SsaBuilder(this, handles).BuildSsa();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000254 if (result != kAnalysisSuccess) {
David Brazdil4833f5a2015-12-16 10:37:39 +0000255 return result;
256 }
257
258 in_ssa_form_ = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000259 return kAnalysisSuccess;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100260}
261
David Brazdilfc6a86a2015-06-26 10:33:45 +0000262HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000263 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
264 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000265 // Use `InsertBetween` to ensure the predecessor index and successor index of
266 // `block` and `successor` are preserved.
267 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000268 return new_block;
269}
270
271void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
272 // Insert a new node between `block` and `successor` to split the
273 // critical edge.
274 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600275 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100276 if (successor->IsLoopHeader()) {
277 // If we split at a back edge boundary, make the new block the back edge.
278 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000279 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100280 info->RemoveBackEdge(block);
281 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100282 }
283 }
284}
285
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100286void HGraph::SimplifyLoop(HBasicBlock* header) {
287 HLoopInformation* info = header->GetLoopInformation();
288
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100289 // Make sure the loop has only one pre header. This simplifies SSA building by having
290 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000291 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
292 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000293 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000294 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100295 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100296 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600297 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100298
Vladimir Marko60584552015-09-03 13:35:12 +0000299 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100300 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100301 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100302 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100303 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100304 }
305 }
306 pre_header->AddSuccessor(header);
307 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100308
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100309 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100310 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
311 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000312 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100313 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100314 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000315 header->predecessors_[pred] = to_swap;
316 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100317 break;
318 }
319 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100320 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100321
322 // Place the suspend check at the beginning of the header, so that live registers
323 // will be known when allocating registers. Note that code generation can still
324 // generate the suspend check at the back edge, but needs to be careful with
325 // loop phi spill slots (which are not written to at back edge).
326 HInstruction* first_instruction = header->GetFirstInstruction();
327 if (!first_instruction->IsSuspendCheck()) {
328 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
329 header->InsertInstructionBefore(check, first_instruction);
330 first_instruction = check;
331 }
332 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100333}
334
David Brazdilffee3d32015-07-06 11:48:53 +0100335static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100336 HBasicBlock* predecessor = block.GetPredecessors()[pred_idx];
David Brazdilffee3d32015-07-06 11:48:53 +0100337 if (!predecessor->EndsWithTryBoundary()) {
338 // Only edges from HTryBoundary can be exceptional.
339 return false;
340 }
341 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
342 if (try_boundary->GetNormalFlowSuccessor() == &block) {
343 // This block is the normal-flow successor of `try_boundary`, but it could
344 // also be one of its exception handlers if catch blocks have not been
345 // simplified yet. Predecessors are unordered, so we will consider the first
346 // occurrence to be the normal edge and a possible second occurrence to be
347 // the exceptional edge.
348 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
349 } else {
350 // This is not the normal-flow successor of `try_boundary`, hence it must be
351 // one of its exception handlers.
352 DCHECK(try_boundary->HasExceptionHandler(block));
353 return true;
354 }
355}
356
357void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100358 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
359 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
360 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
361 HBasicBlock* catch_block = blocks_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000362 if (catch_block == nullptr || !catch_block->IsCatchBlock()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100363 continue;
364 }
365
366 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000367 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100368 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
369 exceptional_predecessors_only = false;
370 break;
371 }
372 }
373
374 if (!exceptional_predecessors_only) {
375 // Catch block has normal-flow predecessors and needs to be simplified.
376 // Splitting the block before its first instruction moves all its
377 // instructions into `normal_block` and links the two blocks with a Goto.
378 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
379 // leaving `catch_block` with the exceptional edges only.
David Brazdil9bc43612015-11-05 21:25:24 +0000380 //
David Brazdilffee3d32015-07-06 11:48:53 +0100381 // Note that catch blocks with normal-flow predecessors cannot begin with
David Brazdil9bc43612015-11-05 21:25:24 +0000382 // a move-exception instruction, as guaranteed by the verifier. However,
383 // trivially dead predecessors are ignored by the verifier and such code
384 // has not been removed at this stage. We therefore ignore the assumption
385 // and rely on GraphChecker to enforce it after initial DCE is run (b/25492628).
386 HBasicBlock* normal_block = catch_block->SplitCatchBlockAfterMoveException();
387 if (normal_block == nullptr) {
388 // Catch block is either empty or only contains a move-exception. It must
389 // therefore be dead and will be removed during initial DCE. Do nothing.
390 DCHECK(!catch_block->EndsWithControlFlowInstruction());
391 } else {
392 // Catch block was split. Re-link normal-flow edges to the new block.
393 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
394 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
395 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
396 --j;
397 }
David Brazdilffee3d32015-07-06 11:48:53 +0100398 }
399 }
400 }
401 }
402}
403
404void HGraph::ComputeTryBlockInformation() {
405 // Iterate in reverse post order to propagate try membership information from
406 // predecessors to their successors.
407 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
408 HBasicBlock* block = it.Current();
409 if (block->IsEntryBlock() || block->IsCatchBlock()) {
410 // Catch blocks after simplification have only exceptional predecessors
411 // and hence are never in tries.
412 continue;
413 }
414
415 // Infer try membership from the first predecessor. Having simplified loops,
416 // the first predecessor can never be a back edge and therefore it must have
417 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100418 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100419 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100420 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000421 if (try_entry != nullptr &&
422 (block->GetTryCatchInformation() == nullptr ||
423 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
424 // We are either setting try block membership for the first time or it
425 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100426 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
427 }
David Brazdilffee3d32015-07-06 11:48:53 +0100428 }
429}
430
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100431void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000432// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100433 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000434 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100435 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
436 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
437 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
438 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100439 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000440 if (block->GetSuccessors().size() > 1) {
441 // Only split normal-flow edges. We cannot split exceptional edges as they
442 // are synthesized (approximate real control flow), and we do not need to
443 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000444 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
445 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
446 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100447 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000448 if (successor == exit_block_) {
449 // Throw->TryBoundary->Exit. Special case which we do not want to split
450 // because Goto->Exit is not allowed.
451 DCHECK(block->IsSingleTryBoundary());
452 DCHECK(block->GetSinglePredecessor()->GetLastInstruction()->IsThrow());
453 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100454 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000455 // SplitCriticalEdge could have invalidated the `normal_successors`
456 // ArrayRef. We must re-acquire it.
457 normal_successors = block->GetNormalSuccessors();
458 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
459 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100460 }
461 }
462 }
463 if (block->IsLoopHeader()) {
464 SimplifyLoop(block);
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000465 } else if (!block->IsEntryBlock() && block->GetFirstInstruction()->IsSuspendCheck()) {
466 // We are being called by the dead code elimiation pass, and what used to be
467 // a loop got dismantled. Just remove the suspend check.
468 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100469 }
470 }
471}
472
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000473GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100474 // Order does not matter.
475 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
476 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100477 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100478 if (block->IsCatchBlock()) {
479 // TODO: Dealing with exceptional back edges could be tricky because
480 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000481 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100482 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000483 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100484 }
485 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000486 return kAnalysisSuccess;
487}
488
489void HLoopInformation::Dump(std::ostream& os) {
490 os << "header: " << header_->GetBlockId() << std::endl;
491 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
492 for (HBasicBlock* block : back_edges_) {
493 os << "back edge: " << block->GetBlockId() << std::endl;
494 }
495 for (HBasicBlock* block : header_->GetPredecessors()) {
496 os << "predecessor: " << block->GetBlockId() << std::endl;
497 }
498 for (uint32_t idx : blocks_.Indexes()) {
499 os << " in loop: " << idx << std::endl;
500 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100501}
502
David Brazdil8d5b8b22015-03-24 10:51:52 +0000503void HGraph::InsertConstant(HConstant* constant) {
504 // New constants are inserted before the final control-flow instruction
505 // of the graph, or at its end if called from the graph builder.
506 if (entry_block_->EndsWithControlFlowInstruction()) {
507 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000508 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000509 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000510 }
511}
512
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600513HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100514 // For simplicity, don't bother reviving the cached null constant if it is
515 // not null and not in a block. Otherwise, we need to clear the instruction
516 // id and/or any invariants the graph is assuming when adding new instructions.
517 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600518 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000519 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000520 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000521 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000522 if (kIsDebugBuild) {
523 ScopedObjectAccess soa(Thread::Current());
524 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
525 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000526 return cached_null_constant_;
527}
528
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100529HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100530 // For simplicity, don't bother reviving the cached current method if it is
531 // not null and not in a block. Otherwise, we need to clear the instruction
532 // id and/or any invariants the graph is assuming when adding new instructions.
533 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700534 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600535 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
536 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100537 if (entry_block_->GetFirstInstruction() == nullptr) {
538 entry_block_->AddInstruction(cached_current_method_);
539 } else {
540 entry_block_->InsertInstructionBefore(
541 cached_current_method_, entry_block_->GetFirstInstruction());
542 }
543 }
544 return cached_current_method_;
545}
546
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600547HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000548 switch (type) {
549 case Primitive::Type::kPrimBoolean:
550 DCHECK(IsUint<1>(value));
551 FALLTHROUGH_INTENDED;
552 case Primitive::Type::kPrimByte:
553 case Primitive::Type::kPrimChar:
554 case Primitive::Type::kPrimShort:
555 case Primitive::Type::kPrimInt:
556 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600557 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000558
559 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600560 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000561
562 default:
563 LOG(FATAL) << "Unsupported constant type";
564 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000565 }
David Brazdil46e2a392015-03-16 17:31:52 +0000566}
567
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000568void HGraph::CacheFloatConstant(HFloatConstant* constant) {
569 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
570 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
571 cached_float_constants_.Overwrite(value, constant);
572}
573
574void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
575 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
576 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
577 cached_double_constants_.Overwrite(value, constant);
578}
579
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000580void HLoopInformation::Add(HBasicBlock* block) {
581 blocks_.SetBit(block->GetBlockId());
582}
583
David Brazdil46e2a392015-03-16 17:31:52 +0000584void HLoopInformation::Remove(HBasicBlock* block) {
585 blocks_.ClearBit(block->GetBlockId());
586}
587
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100588void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
589 if (blocks_.IsBitSet(block->GetBlockId())) {
590 return;
591 }
592
593 blocks_.SetBit(block->GetBlockId());
594 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000595 for (HBasicBlock* predecessor : block->GetPredecessors()) {
596 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100597 }
598}
599
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000600void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block) {
601 if (blocks_.IsBitSet(block->GetBlockId())) {
602 return;
603 }
604
605 if (block->IsLoopHeader()) {
606 // If we hit a loop header in an irreducible loop, we first check if the
607 // pre header of that loop belongs to the currently analyzed loop. If it does,
608 // then we visit the back edges.
609 // Note that we cannot use GetPreHeader, as the loop may have not been populated
610 // yet.
611 HBasicBlock* pre_header = block->GetPredecessors()[0];
612 PopulateIrreducibleRecursive(pre_header);
613 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
614 blocks_.SetBit(block->GetBlockId());
615 block->SetInLoop(this);
616 HLoopInformation* info = block->GetLoopInformation();
617 for (HBasicBlock* back_edge : info->GetBackEdges()) {
618 PopulateIrreducibleRecursive(back_edge);
619 }
620 }
621 } else {
622 // Visit all predecessors. If one predecessor is part of the loop, this
623 // block is also part of this loop.
624 for (HBasicBlock* predecessor : block->GetPredecessors()) {
625 PopulateIrreducibleRecursive(predecessor);
626 if (blocks_.IsBitSet(predecessor->GetBlockId())) {
627 blocks_.SetBit(block->GetBlockId());
628 block->SetInLoop(this);
629 }
630 }
631 }
632}
633
634void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100635 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000636 // Populate this loop: starting with the back edge, recursively add predecessors
637 // that are not already part of that loop. Set the header as part of the loop
638 // to end the recursion.
639 // This is a recursive implementation of the algorithm described in
640 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
641 blocks_.SetBit(header_->GetBlockId());
642 header_->SetInLoop(this);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100643 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100644 DCHECK(back_edge->GetDominator() != nullptr);
645 if (!header_->Dominates(back_edge)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000646 irreducible_ = true;
647 header_->GetGraph()->SetHasIrreducibleLoops(true);
648 PopulateIrreducibleRecursive(back_edge);
649 } else {
650 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100651 }
David Brazdila4b8c212015-05-07 09:59:30 +0100652 }
653}
654
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100655HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000656 HBasicBlock* block = header_->GetPredecessors()[0];
657 DCHECK(irreducible_ || (block == header_->GetDominator()));
658 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100659}
660
661bool HLoopInformation::Contains(const HBasicBlock& block) const {
662 return blocks_.IsBitSet(block.GetBlockId());
663}
664
665bool HLoopInformation::IsIn(const HLoopInformation& other) const {
666 return other.blocks_.IsBitSet(header_->GetBlockId());
667}
668
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800669bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
670 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700671}
672
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100673size_t HLoopInformation::GetLifetimeEnd() const {
674 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100675 for (HBasicBlock* back_edge : GetBackEdges()) {
676 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100677 }
678 return last_position;
679}
680
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100681bool HBasicBlock::Dominates(HBasicBlock* other) const {
682 // Walk up the dominator tree from `other`, to find out if `this`
683 // is an ancestor.
684 HBasicBlock* current = other;
685 while (current != nullptr) {
686 if (current == this) {
687 return true;
688 }
689 current = current->GetDominator();
690 }
691 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100692}
693
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100694static void UpdateInputsUsers(HInstruction* instruction) {
695 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
696 instruction->InputAt(i)->AddUseAt(instruction, i);
697 }
698 // Environment should be created later.
699 DCHECK(!instruction->HasEnvironment());
700}
701
Roland Levillainccc07a92014-09-16 14:48:16 +0100702void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
703 HInstruction* replacement) {
704 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400705 if (initial->IsControlFlow()) {
706 // We can only replace a control flow instruction with another control flow instruction.
707 DCHECK(replacement->IsControlFlow());
708 DCHECK_EQ(replacement->GetId(), -1);
709 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
710 DCHECK_EQ(initial->GetBlock(), this);
711 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
712 DCHECK(initial->GetUses().IsEmpty());
713 DCHECK(initial->GetEnvUses().IsEmpty());
714 replacement->SetBlock(this);
715 replacement->SetId(GetGraph()->GetNextInstructionId());
716 instructions_.InsertInstructionBefore(replacement, initial);
717 UpdateInputsUsers(replacement);
718 } else {
719 InsertInstructionBefore(replacement, initial);
720 initial->ReplaceWith(replacement);
721 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100722 RemoveInstruction(initial);
723}
724
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100725static void Add(HInstructionList* instruction_list,
726 HBasicBlock* block,
727 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000728 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000729 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100730 instruction->SetBlock(block);
731 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100732 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100733 instruction_list->AddInstruction(instruction);
734}
735
736void HBasicBlock::AddInstruction(HInstruction* instruction) {
737 Add(&instructions_, this, instruction);
738}
739
740void HBasicBlock::AddPhi(HPhi* phi) {
741 Add(&phis_, this, phi);
742}
743
David Brazdilc3d743f2015-04-22 13:40:50 +0100744void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
745 DCHECK(!cursor->IsPhi());
746 DCHECK(!instruction->IsPhi());
747 DCHECK_EQ(instruction->GetId(), -1);
748 DCHECK_NE(cursor->GetId(), -1);
749 DCHECK_EQ(cursor->GetBlock(), this);
750 DCHECK(!instruction->IsControlFlow());
751 instruction->SetBlock(this);
752 instruction->SetId(GetGraph()->GetNextInstructionId());
753 UpdateInputsUsers(instruction);
754 instructions_.InsertInstructionBefore(instruction, cursor);
755}
756
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100757void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
758 DCHECK(!cursor->IsPhi());
759 DCHECK(!instruction->IsPhi());
760 DCHECK_EQ(instruction->GetId(), -1);
761 DCHECK_NE(cursor->GetId(), -1);
762 DCHECK_EQ(cursor->GetBlock(), this);
763 DCHECK(!instruction->IsControlFlow());
764 DCHECK(!cursor->IsControlFlow());
765 instruction->SetBlock(this);
766 instruction->SetId(GetGraph()->GetNextInstructionId());
767 UpdateInputsUsers(instruction);
768 instructions_.InsertInstructionAfter(instruction, cursor);
769}
770
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100771void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
772 DCHECK_EQ(phi->GetId(), -1);
773 DCHECK_NE(cursor->GetId(), -1);
774 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100775 phi->SetBlock(this);
776 phi->SetId(GetGraph()->GetNextInstructionId());
777 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100778 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100779}
780
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100781static void Remove(HInstructionList* instruction_list,
782 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000783 HInstruction* instruction,
784 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100785 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100786 instruction->SetBlock(nullptr);
787 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000788 if (ensure_safety) {
789 DCHECK(instruction->GetUses().IsEmpty());
790 DCHECK(instruction->GetEnvUses().IsEmpty());
791 RemoveAsUser(instruction);
792 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100793}
794
David Brazdil1abb4192015-02-17 18:33:36 +0000795void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100796 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000797 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100798}
799
David Brazdil1abb4192015-02-17 18:33:36 +0000800void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
801 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100802}
803
David Brazdilc7508e92015-04-27 13:28:57 +0100804void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
805 if (instruction->IsPhi()) {
806 RemovePhi(instruction->AsPhi(), ensure_safety);
807 } else {
808 RemoveInstruction(instruction, ensure_safety);
809 }
810}
811
Vladimir Marko71bf8092015-09-15 15:33:14 +0100812void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
813 for (size_t i = 0; i < locals.size(); i++) {
814 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100815 SetRawEnvAt(i, instruction);
816 if (instruction != nullptr) {
817 instruction->AddEnvUseAt(this, i);
818 }
819 }
820}
821
David Brazdiled596192015-01-23 10:39:45 +0000822void HEnvironment::CopyFrom(HEnvironment* env) {
823 for (size_t i = 0; i < env->Size(); i++) {
824 HInstruction* instruction = env->GetInstructionAt(i);
825 SetRawEnvAt(i, instruction);
826 if (instruction != nullptr) {
827 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100828 }
David Brazdiled596192015-01-23 10:39:45 +0000829 }
830}
831
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700832void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
833 HBasicBlock* loop_header) {
834 DCHECK(loop_header->IsLoopHeader());
835 for (size_t i = 0; i < env->Size(); i++) {
836 HInstruction* instruction = env->GetInstructionAt(i);
837 SetRawEnvAt(i, instruction);
838 if (instruction == nullptr) {
839 continue;
840 }
841 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
842 // At the end of the loop pre-header, the corresponding value for instruction
843 // is the first input of the phi.
844 HInstruction* initial = instruction->AsPhi()->InputAt(0);
845 DCHECK(initial->GetBlock()->Dominates(loop_header));
846 SetRawEnvAt(i, initial);
847 initial->AddEnvUseAt(this, i);
848 } else {
849 instruction->AddEnvUseAt(this, i);
850 }
851 }
852}
853
David Brazdil1abb4192015-02-17 18:33:36 +0000854void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100855 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000856 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100857}
858
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000859HInstruction::InstructionKind HInstruction::GetKind() const {
860 return GetKindInternal();
861}
862
Calin Juravle77520bc2015-01-12 18:45:46 +0000863HInstruction* HInstruction::GetNextDisregardingMoves() const {
864 HInstruction* next = GetNext();
865 while (next != nullptr && next->IsParallelMove()) {
866 next = next->GetNext();
867 }
868 return next;
869}
870
871HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
872 HInstruction* previous = GetPrevious();
873 while (previous != nullptr && previous->IsParallelMove()) {
874 previous = previous->GetPrevious();
875 }
876 return previous;
877}
878
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100879void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000880 if (first_instruction_ == nullptr) {
881 DCHECK(last_instruction_ == nullptr);
882 first_instruction_ = last_instruction_ = instruction;
883 } else {
884 last_instruction_->next_ = instruction;
885 instruction->previous_ = last_instruction_;
886 last_instruction_ = instruction;
887 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000888}
889
David Brazdilc3d743f2015-04-22 13:40:50 +0100890void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
891 DCHECK(Contains(cursor));
892 if (cursor == first_instruction_) {
893 cursor->previous_ = instruction;
894 instruction->next_ = cursor;
895 first_instruction_ = instruction;
896 } else {
897 instruction->previous_ = cursor->previous_;
898 instruction->next_ = cursor;
899 cursor->previous_ = instruction;
900 instruction->previous_->next_ = instruction;
901 }
902}
903
904void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
905 DCHECK(Contains(cursor));
906 if (cursor == last_instruction_) {
907 cursor->next_ = instruction;
908 instruction->previous_ = cursor;
909 last_instruction_ = instruction;
910 } else {
911 instruction->next_ = cursor->next_;
912 instruction->previous_ = cursor;
913 cursor->next_ = instruction;
914 instruction->next_->previous_ = instruction;
915 }
916}
917
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100918void HInstructionList::RemoveInstruction(HInstruction* instruction) {
919 if (instruction->previous_ != nullptr) {
920 instruction->previous_->next_ = instruction->next_;
921 }
922 if (instruction->next_ != nullptr) {
923 instruction->next_->previous_ = instruction->previous_;
924 }
925 if (instruction == first_instruction_) {
926 first_instruction_ = instruction->next_;
927 }
928 if (instruction == last_instruction_) {
929 last_instruction_ = instruction->previous_;
930 }
931}
932
Roland Levillain6b469232014-09-25 10:10:38 +0100933bool HInstructionList::Contains(HInstruction* instruction) const {
934 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
935 if (it.Current() == instruction) {
936 return true;
937 }
938 }
939 return false;
940}
941
Roland Levillainccc07a92014-09-16 14:48:16 +0100942bool HInstructionList::FoundBefore(const HInstruction* instruction1,
943 const HInstruction* instruction2) const {
944 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
945 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
946 if (it.Current() == instruction1) {
947 return true;
948 }
949 if (it.Current() == instruction2) {
950 return false;
951 }
952 }
953 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
954 return true;
955}
956
Roland Levillain6c82d402014-10-13 16:10:27 +0100957bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
958 if (other_instruction == this) {
959 // An instruction does not strictly dominate itself.
960 return false;
961 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100962 HBasicBlock* block = GetBlock();
963 HBasicBlock* other_block = other_instruction->GetBlock();
964 if (block != other_block) {
965 return GetBlock()->Dominates(other_instruction->GetBlock());
966 } else {
967 // If both instructions are in the same block, ensure this
968 // instruction comes before `other_instruction`.
969 if (IsPhi()) {
970 if (!other_instruction->IsPhi()) {
971 // Phis appear before non phi-instructions so this instruction
972 // dominates `other_instruction`.
973 return true;
974 } else {
975 // There is no order among phis.
976 LOG(FATAL) << "There is no dominance between phis of a same block.";
977 return false;
978 }
979 } else {
980 // `this` is not a phi.
981 if (other_instruction->IsPhi()) {
982 // Phis appear before non phi-instructions so this instruction
983 // does not dominate `other_instruction`.
984 return false;
985 } else {
986 // Check whether this instruction comes before
987 // `other_instruction` in the instruction list.
988 return block->GetInstructions().FoundBefore(this, other_instruction);
989 }
990 }
991 }
992}
993
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100994void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100995 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000996 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
997 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100998 HInstruction* user = current->GetUser();
999 size_t input_index = current->GetIndex();
1000 user->SetRawInputAt(input_index, other);
1001 other->AddUseAt(user, input_index);
1002 }
1003
David Brazdiled596192015-01-23 10:39:45 +00001004 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
1005 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001006 HEnvironment* user = current->GetUser();
1007 size_t input_index = current->GetIndex();
1008 user->SetRawEnvAt(input_index, other);
1009 other->AddEnvUseAt(user, input_index);
1010 }
1011
David Brazdiled596192015-01-23 10:39:45 +00001012 uses_.Clear();
1013 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001014}
1015
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001016void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +00001017 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001018 SetRawInputAt(index, replacement);
1019 replacement->AddUseAt(this, index);
1020}
1021
Nicolas Geoffray39468442014-09-02 15:17:15 +01001022size_t HInstruction::EnvironmentSize() const {
1023 return HasEnvironment() ? environment_->Size() : 0;
1024}
1025
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001026void HPhi::AddInput(HInstruction* input) {
1027 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001028 inputs_.push_back(HUserRecord<HInstruction*>(input));
1029 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001030}
1031
David Brazdil2d7352b2015-04-20 14:52:42 +01001032void HPhi::RemoveInputAt(size_t index) {
1033 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001034 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001035 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001036 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001037 InputRecordAt(i).GetUseNode()->SetIndex(i);
1038 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001039}
1040
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001041#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001042void H##name::Accept(HGraphVisitor* visitor) { \
1043 visitor->Visit##name(this); \
1044}
1045
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001046FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001047
1048#undef DEFINE_ACCEPT
1049
1050void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001051 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1052 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001053 if (block != nullptr) {
1054 VisitBasicBlock(block);
1055 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001056 }
1057}
1058
Roland Levillain633021e2014-10-01 14:12:25 +01001059void HGraphVisitor::VisitReversePostOrder() {
1060 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1061 VisitBasicBlock(it.Current());
1062 }
1063}
1064
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001065void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001066 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001067 it.Current()->Accept(this);
1068 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001069 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001070 it.Current()->Accept(this);
1071 }
1072}
1073
Mark Mendelle82549b2015-05-06 10:55:34 -04001074HConstant* HTypeConversion::TryStaticEvaluation() const {
1075 HGraph* graph = GetBlock()->GetGraph();
1076 if (GetInput()->IsIntConstant()) {
1077 int32_t value = GetInput()->AsIntConstant()->GetValue();
1078 switch (GetResultType()) {
1079 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001080 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001081 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001082 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001083 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001084 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001085 default:
1086 return nullptr;
1087 }
1088 } else if (GetInput()->IsLongConstant()) {
1089 int64_t value = GetInput()->AsLongConstant()->GetValue();
1090 switch (GetResultType()) {
1091 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001092 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001093 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001094 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001095 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001096 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001097 default:
1098 return nullptr;
1099 }
1100 } else if (GetInput()->IsFloatConstant()) {
1101 float value = GetInput()->AsFloatConstant()->GetValue();
1102 switch (GetResultType()) {
1103 case Primitive::kPrimInt:
1104 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001105 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001106 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001107 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001108 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001109 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1110 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001111 case Primitive::kPrimLong:
1112 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001113 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001114 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001115 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001116 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001117 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1118 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001119 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001120 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001121 default:
1122 return nullptr;
1123 }
1124 } else if (GetInput()->IsDoubleConstant()) {
1125 double value = GetInput()->AsDoubleConstant()->GetValue();
1126 switch (GetResultType()) {
1127 case Primitive::kPrimInt:
1128 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001129 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001130 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001131 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001132 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001133 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1134 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001135 case Primitive::kPrimLong:
1136 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001137 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001138 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001139 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001140 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001141 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1142 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001143 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001144 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001145 default:
1146 return nullptr;
1147 }
1148 }
1149 return nullptr;
1150}
1151
Roland Levillain9240d6a2014-10-20 16:47:04 +01001152HConstant* HUnaryOperation::TryStaticEvaluation() const {
1153 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001154 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001155 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001156 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001157 }
1158 return nullptr;
1159}
1160
1161HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001162 if (GetLeft()->IsIntConstant()) {
1163 if (GetRight()->IsIntConstant()) {
1164 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1165 } else if (GetRight()->IsLongConstant()) {
1166 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1167 }
1168 } else if (GetLeft()->IsLongConstant()) {
1169 if (GetRight()->IsIntConstant()) {
1170 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1171 } else if (GetRight()->IsLongConstant()) {
1172 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001173 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001174 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
1175 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain556c3d12014-09-18 15:25:07 +01001176 }
1177 return nullptr;
1178}
Dave Allison20dfc792014-06-16 20:44:29 -07001179
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001180HConstant* HBinaryOperation::GetConstantRight() const {
1181 if (GetRight()->IsConstant()) {
1182 return GetRight()->AsConstant();
1183 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1184 return GetLeft()->AsConstant();
1185 } else {
1186 return nullptr;
1187 }
1188}
1189
1190// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001191// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001192HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1193 HInstruction* most_constant_right = GetConstantRight();
1194 if (most_constant_right == nullptr) {
1195 return nullptr;
1196 } else if (most_constant_right == GetLeft()) {
1197 return GetRight();
1198 } else {
1199 return GetLeft();
1200 }
1201}
1202
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001203bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1204 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001205}
1206
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001207bool HInstruction::Equals(HInstruction* other) const {
1208 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001209 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001210 if (!InstructionDataEquals(other)) return false;
1211 if (GetType() != other->GetType()) return false;
1212 if (InputCount() != other->InputCount()) return false;
1213
1214 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1215 if (InputAt(i) != other->InputAt(i)) return false;
1216 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001217 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001218 return true;
1219}
1220
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001221std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1222#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1223 switch (rhs) {
1224 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1225 default:
1226 os << "Unknown instruction kind " << static_cast<int>(rhs);
1227 break;
1228 }
1229#undef DECLARE_CASE
1230 return os;
1231}
1232
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001233void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001234 next_->previous_ = previous_;
1235 if (previous_ != nullptr) {
1236 previous_->next_ = next_;
1237 }
1238 if (block_->instructions_.first_instruction_ == this) {
1239 block_->instructions_.first_instruction_ = next_;
1240 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001241 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001242
1243 previous_ = cursor->previous_;
1244 if (previous_ != nullptr) {
1245 previous_->next_ = this;
1246 }
1247 next_ = cursor;
1248 cursor->previous_ = this;
1249 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001250
1251 if (block_->instructions_.first_instruction_ == cursor) {
1252 block_->instructions_.first_instruction_ = this;
1253 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001254}
1255
Vladimir Markofb337ea2015-11-25 15:25:10 +00001256void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1257 DCHECK(!CanThrow());
1258 DCHECK(!HasSideEffects());
1259 DCHECK(!HasEnvironmentUses());
1260 DCHECK(HasNonEnvironmentUses());
1261 DCHECK(!IsPhi()); // Makes no sense for Phi.
1262 DCHECK_EQ(InputCount(), 0u);
1263
1264 // Find the target block.
1265 HUseIterator<HInstruction*> uses_it(GetUses());
1266 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1267 uses_it.Advance();
1268 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1269 uses_it.Advance();
1270 }
1271 if (!uses_it.Done()) {
1272 // This instruction has uses in two or more blocks. Find the common dominator.
1273 CommonDominator finder(target_block);
1274 for (; !uses_it.Done(); uses_it.Advance()) {
1275 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1276 }
1277 target_block = finder.Get();
1278 DCHECK(target_block != nullptr);
1279 }
1280 // Move to the first dominator not in a loop.
1281 while (target_block->IsInLoop()) {
1282 target_block = target_block->GetDominator();
1283 DCHECK(target_block != nullptr);
1284 }
1285
1286 // Find insertion position.
1287 HInstruction* insert_pos = nullptr;
1288 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1289 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1290 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1291 insert_pos = uses_it2.Current()->GetUser();
1292 }
1293 }
1294 if (insert_pos == nullptr) {
1295 // No user in `target_block`, insert before the control flow instruction.
1296 insert_pos = target_block->GetLastInstruction();
1297 DCHECK(insert_pos->IsControlFlow());
1298 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1299 if (insert_pos->IsIf()) {
1300 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1301 if (if_input == insert_pos->GetPrevious()) {
1302 insert_pos = if_input;
1303 }
1304 }
1305 }
1306 MoveBefore(insert_pos);
1307}
1308
David Brazdilfc6a86a2015-06-26 10:33:45 +00001309HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001310 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001311 DCHECK_EQ(cursor->GetBlock(), this);
1312
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001313 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1314 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001315 new_block->instructions_.first_instruction_ = cursor;
1316 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1317 instructions_.last_instruction_ = cursor->previous_;
1318 if (cursor->previous_ == nullptr) {
1319 instructions_.first_instruction_ = nullptr;
1320 } else {
1321 cursor->previous_->next_ = nullptr;
1322 cursor->previous_ = nullptr;
1323 }
1324
1325 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001326 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001327
Vladimir Marko60584552015-09-03 13:35:12 +00001328 for (HBasicBlock* successor : GetSuccessors()) {
1329 new_block->successors_.push_back(successor);
1330 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001331 }
Vladimir Marko60584552015-09-03 13:35:12 +00001332 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001333 AddSuccessor(new_block);
1334
David Brazdil56e1acc2015-06-30 15:41:36 +01001335 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001336 return new_block;
1337}
1338
David Brazdild7558da2015-09-22 13:04:14 +01001339HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001340 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001341 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1342
1343 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1344
1345 for (HBasicBlock* predecessor : GetPredecessors()) {
1346 new_block->predecessors_.push_back(predecessor);
1347 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1348 }
1349 predecessors_.clear();
1350 AddPredecessor(new_block);
1351
1352 GetGraph()->AddBlock(new_block);
1353 return new_block;
1354}
1355
David Brazdil9bc43612015-11-05 21:25:24 +00001356HBasicBlock* HBasicBlock::SplitCatchBlockAfterMoveException() {
1357 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
1358 DCHECK(IsCatchBlock()) << "This method is intended for catch blocks only.";
1359
1360 HInstruction* first_insn = GetFirstInstruction();
1361 HInstruction* split_before = nullptr;
1362
1363 if (first_insn != nullptr && first_insn->IsLoadException()) {
1364 // Catch block starts with a LoadException. Split the block after
1365 // the StoreLocal and ClearException which must come after the load.
1366 DCHECK(first_insn->GetNext()->IsStoreLocal());
1367 DCHECK(first_insn->GetNext()->GetNext()->IsClearException());
1368 split_before = first_insn->GetNext()->GetNext()->GetNext();
1369 } else {
1370 // Catch block does not load the exception. Split at the beginning
1371 // to create an empty catch block.
1372 split_before = first_insn;
1373 }
1374
1375 if (split_before == nullptr) {
1376 // Catch block has no instructions after the split point (must be dead).
1377 // Do not split it but rather signal error by returning nullptr.
1378 return nullptr;
1379 } else {
1380 return SplitBefore(split_before);
1381 }
1382}
1383
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001384HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1385 DCHECK(!cursor->IsControlFlow());
1386 DCHECK_NE(instructions_.last_instruction_, cursor);
1387 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001388
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001389 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1390 new_block->instructions_.first_instruction_ = cursor->GetNext();
1391 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1392 cursor->next_->previous_ = nullptr;
1393 cursor->next_ = nullptr;
1394 instructions_.last_instruction_ = cursor;
1395
1396 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001397 for (HBasicBlock* successor : GetSuccessors()) {
1398 new_block->successors_.push_back(successor);
1399 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001400 }
Vladimir Marko60584552015-09-03 13:35:12 +00001401 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001402
Vladimir Marko60584552015-09-03 13:35:12 +00001403 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001404 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001405 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001406 }
Vladimir Marko60584552015-09-03 13:35:12 +00001407 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001408 return new_block;
1409}
1410
David Brazdilec16f792015-08-19 15:04:01 +01001411const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001412 if (EndsWithTryBoundary()) {
1413 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1414 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001415 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001416 return try_boundary;
1417 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001418 DCHECK(IsTryBlock());
1419 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001420 return nullptr;
1421 }
David Brazdilec16f792015-08-19 15:04:01 +01001422 } else if (IsTryBlock()) {
1423 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001424 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001425 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001426 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001427}
1428
David Brazdild7558da2015-09-22 13:04:14 +01001429bool HBasicBlock::HasThrowingInstructions() const {
1430 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1431 if (it.Current()->CanThrow()) {
1432 return true;
1433 }
1434 }
1435 return false;
1436}
1437
David Brazdilfc6a86a2015-06-26 10:33:45 +00001438static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1439 return block.GetPhis().IsEmpty()
1440 && !block.GetInstructions().IsEmpty()
1441 && block.GetFirstInstruction() == block.GetLastInstruction();
1442}
1443
David Brazdil46e2a392015-03-16 17:31:52 +00001444bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001445 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1446}
1447
1448bool HBasicBlock::IsSingleTryBoundary() const {
1449 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001450}
1451
David Brazdil8d5b8b22015-03-24 10:51:52 +00001452bool HBasicBlock::EndsWithControlFlowInstruction() const {
1453 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1454}
1455
David Brazdilb2bd1c52015-03-25 11:17:37 +00001456bool HBasicBlock::EndsWithIf() const {
1457 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1458}
1459
David Brazdilffee3d32015-07-06 11:48:53 +01001460bool HBasicBlock::EndsWithTryBoundary() const {
1461 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1462}
1463
David Brazdilb2bd1c52015-03-25 11:17:37 +00001464bool HBasicBlock::HasSinglePhi() const {
1465 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1466}
1467
David Brazdild26a4112015-11-10 11:07:31 +00001468ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1469 if (EndsWithTryBoundary()) {
1470 // The normal-flow successor of HTryBoundary is always stored at index zero.
1471 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1472 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1473 } else {
1474 // All successors of blocks not ending with TryBoundary are normal.
1475 return ArrayRef<HBasicBlock* const>(successors_);
1476 }
1477}
1478
1479ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1480 if (EndsWithTryBoundary()) {
1481 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1482 } else {
1483 // Blocks not ending with TryBoundary do not have exceptional successors.
1484 return ArrayRef<HBasicBlock* const>();
1485 }
1486}
1487
David Brazdilffee3d32015-07-06 11:48:53 +01001488bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001489 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1490 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1491
1492 size_t length = handlers1.size();
1493 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001494 return false;
1495 }
1496
David Brazdilb618ade2015-07-29 10:31:29 +01001497 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001498 for (size_t i = 0; i < length; ++i) {
1499 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001500 return false;
1501 }
1502 }
1503 return true;
1504}
1505
David Brazdil2d7352b2015-04-20 14:52:42 +01001506size_t HInstructionList::CountSize() const {
1507 size_t size = 0;
1508 HInstruction* current = first_instruction_;
1509 for (; current != nullptr; current = current->GetNext()) {
1510 size++;
1511 }
1512 return size;
1513}
1514
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001515void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1516 for (HInstruction* current = first_instruction_;
1517 current != nullptr;
1518 current = current->GetNext()) {
1519 current->SetBlock(block);
1520 }
1521}
1522
1523void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1524 DCHECK(Contains(cursor));
1525 if (!instruction_list.IsEmpty()) {
1526 if (cursor == last_instruction_) {
1527 last_instruction_ = instruction_list.last_instruction_;
1528 } else {
1529 cursor->next_->previous_ = instruction_list.last_instruction_;
1530 }
1531 instruction_list.last_instruction_->next_ = cursor->next_;
1532 cursor->next_ = instruction_list.first_instruction_;
1533 instruction_list.first_instruction_->previous_ = cursor;
1534 }
1535}
1536
1537void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001538 if (IsEmpty()) {
1539 first_instruction_ = instruction_list.first_instruction_;
1540 last_instruction_ = instruction_list.last_instruction_;
1541 } else {
1542 AddAfter(last_instruction_, instruction_list);
1543 }
1544}
1545
David Brazdil04ff4e82015-12-10 13:54:52 +00001546// Should be called on instructions in a dead block in post order. This method
1547// assumes `insn` has been removed from all users with the exception of catch
1548// phis because of missing exceptional edges in the graph. It removes the
1549// instruction from catch phi uses, together with inputs of other catch phis in
1550// the catch block at the same index, as these must be dead too.
1551static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1552 DCHECK(!insn->HasEnvironmentUses());
1553 while (insn->HasNonEnvironmentUses()) {
1554 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1555 size_t use_index = use->GetIndex();
1556 HBasicBlock* user_block = use->GetUser()->GetBlock();
1557 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1558 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1559 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1560 }
1561 }
1562}
1563
David Brazdil2d7352b2015-04-20 14:52:42 +01001564void HBasicBlock::DisconnectAndDelete() {
1565 // Dominators must be removed after all the blocks they dominate. This way
1566 // a loop header is removed last, a requirement for correct loop information
1567 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001568 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001569
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001570 // (1) Remove the block from all loops it is included in.
David Brazdil2d7352b2015-04-20 14:52:42 +01001571 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1572 HLoopInformation* loop_info = it.Current();
1573 loop_info->Remove(this);
1574 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001575 // If this was the last back edge of the loop, we deliberately leave the
1576 // loop in an inconsistent state and will fail SSAChecker unless the
1577 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001578 loop_info->RemoveBackEdge(this);
1579 }
1580 }
1581
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001582 // (2) Disconnect the block from its predecessors and update their
1583 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001584 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001585 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001586 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1587 // This block is the only normal-flow successor of the TryBoundary which
1588 // makes `predecessor` dead. Since DCE removes blocks in post order,
1589 // exception handlers of this TryBoundary were already visited and any
1590 // remaining handlers therefore must be live. We remove `predecessor` from
1591 // their list of predecessors.
1592 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1593 while (predecessor->GetSuccessors().size() > 1) {
1594 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1595 DCHECK(handler->IsCatchBlock());
1596 predecessor->RemoveSuccessor(handler);
1597 handler->RemovePredecessor(predecessor);
1598 }
1599 }
1600
David Brazdil2d7352b2015-04-20 14:52:42 +01001601 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001602 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1603 if (num_pred_successors == 1u) {
1604 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001605 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1606 // successor. Replace those with a HGoto.
1607 DCHECK(last_instruction->IsIf() ||
1608 last_instruction->IsPackedSwitch() ||
1609 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001610 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001611 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001612 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001613 // The predecessor has no remaining successors and therefore must be dead.
1614 // We deliberately leave it without a control-flow instruction so that the
1615 // SSAChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001616 predecessor->RemoveInstruction(last_instruction);
1617 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001618 // There are multiple successors left. The removed block might be a successor
1619 // of a PackedSwitch which will be completely removed (perhaps replaced with
1620 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1621 // case, leave `last_instruction` as is for now.
1622 DCHECK(last_instruction->IsPackedSwitch() ||
1623 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001624 }
David Brazdil46e2a392015-03-16 17:31:52 +00001625 }
Vladimir Marko60584552015-09-03 13:35:12 +00001626 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001627
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001628 // (3) Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001629 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001630 // Delete this block from the list of predecessors.
1631 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001632 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001633
1634 // Check that `successor` has other predecessors, otherwise `this` is the
1635 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001636 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001637
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001638 // Remove this block's entries in the successor's phis. Skip exceptional
1639 // successors because catch phi inputs do not correspond to predecessor
1640 // blocks but throwing instructions. Their inputs will be updated in step (4).
1641 if (!successor->IsCatchBlock()) {
1642 if (successor->predecessors_.size() == 1u) {
1643 // The successor has just one predecessor left. Replace phis with the only
1644 // remaining input.
1645 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1646 HPhi* phi = phi_it.Current()->AsPhi();
1647 phi->ReplaceWith(phi->InputAt(1 - this_index));
1648 successor->RemovePhi(phi);
1649 }
1650 } else {
1651 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1652 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1653 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001654 }
1655 }
1656 }
Vladimir Marko60584552015-09-03 13:35:12 +00001657 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001658
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001659 // (4) Remove instructions and phis. Instructions should have no remaining uses
1660 // except in catch phis. If an instruction is used by a catch phi at `index`,
1661 // remove `index`-th input of all phis in the catch block since they are
1662 // guaranteed dead. Note that we may miss dead inputs this way but the
1663 // graph will always remain consistent.
1664 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1665 HInstruction* insn = it.Current();
David Brazdil04ff4e82015-12-10 13:54:52 +00001666 RemoveUsesOfDeadInstruction(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001667 RemoveInstruction(insn);
1668 }
1669 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
David Brazdil04ff4e82015-12-10 13:54:52 +00001670 HPhi* insn = it.Current()->AsPhi();
1671 RemoveUsesOfDeadInstruction(insn);
1672 RemovePhi(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001673 }
1674
David Brazdil2d7352b2015-04-20 14:52:42 +01001675 // Disconnect from the dominator.
1676 dominator_->RemoveDominatedBlock(this);
1677 SetDominator(nullptr);
1678
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001679 // Delete from the graph, update reverse post order.
1680 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001681 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001682}
1683
1684void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001685 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001686 DCHECK(ContainsElement(dominated_blocks_, other));
1687 DCHECK_EQ(GetSingleSuccessor(), other);
1688 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001689 DCHECK(other->GetPhis().IsEmpty());
1690
David Brazdil2d7352b2015-04-20 14:52:42 +01001691 // Move instructions from `other` to `this`.
1692 DCHECK(EndsWithControlFlowInstruction());
1693 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001694 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001695 other->instructions_.SetBlockOfInstructions(this);
1696 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001697
David Brazdil2d7352b2015-04-20 14:52:42 +01001698 // Remove `other` from the loops it is included in.
1699 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1700 HLoopInformation* loop_info = it.Current();
1701 loop_info->Remove(other);
1702 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001703 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001704 }
1705 }
1706
1707 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001708 successors_.clear();
1709 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001710 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001711 successor->ReplacePredecessor(other, this);
1712 }
1713
David Brazdil2d7352b2015-04-20 14:52:42 +01001714 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001715 RemoveDominatedBlock(other);
1716 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1717 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001718 dominated->SetDominator(this);
1719 }
Vladimir Marko60584552015-09-03 13:35:12 +00001720 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001721 other->dominator_ = nullptr;
1722
1723 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001724 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001725
1726 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001727 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001728 other->SetGraph(nullptr);
1729}
1730
1731void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1732 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001733 DCHECK(GetDominatedBlocks().empty());
1734 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001735 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001736 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001737 DCHECK(other->GetPhis().IsEmpty());
1738 DCHECK(!other->IsInLoop());
1739
1740 // Move instructions from `other` to `this`.
1741 instructions_.Add(other->GetInstructions());
1742 other->instructions_.SetBlockOfInstructions(this);
1743
1744 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001745 successors_.clear();
1746 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001747 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001748 successor->ReplacePredecessor(other, this);
1749 }
1750
1751 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001752 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1753 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001754 dominated->SetDominator(this);
1755 }
Vladimir Marko60584552015-09-03 13:35:12 +00001756 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001757 other->dominator_ = nullptr;
1758 other->graph_ = nullptr;
1759}
1760
1761void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001762 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001763 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001764 predecessor->ReplaceSuccessor(this, other);
1765 }
Vladimir Marko60584552015-09-03 13:35:12 +00001766 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001767 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001768 successor->ReplacePredecessor(this, other);
1769 }
Vladimir Marko60584552015-09-03 13:35:12 +00001770 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1771 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001772 }
1773 GetDominator()->ReplaceDominatedBlock(this, other);
1774 other->SetDominator(GetDominator());
1775 dominator_ = nullptr;
1776 graph_ = nullptr;
1777}
1778
1779// Create space in `blocks` for adding `number_of_new_blocks` entries
1780// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001781static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001782 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001783 size_t after) {
1784 DCHECK_LT(after, blocks->size());
1785 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001786 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001787 blocks->resize(new_size);
1788 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001789}
1790
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001791void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001792 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001793 DCHECK(block->GetSuccessors().empty());
1794 DCHECK(block->GetPredecessors().empty());
1795 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001796 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001797 DCHECK(block->GetInstructions().IsEmpty());
1798 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001799
David Brazdilc7af85d2015-05-26 12:05:55 +01001800 if (block->IsExitBlock()) {
1801 exit_block_ = nullptr;
1802 }
1803
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001804 RemoveElement(reverse_post_order_, block);
1805 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001806}
1807
Calin Juravle2e768302015-07-28 14:41:11 +00001808HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001809 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001810 // Update the environments in this graph to have the invoke's environment
1811 // as parent.
1812 {
1813 HReversePostOrderIterator it(*this);
1814 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1815 for (; !it.Done(); it.Advance()) {
1816 HBasicBlock* block = it.Current();
1817 for (HInstructionIterator instr_it(block->GetInstructions());
1818 !instr_it.Done();
1819 instr_it.Advance()) {
1820 HInstruction* current = instr_it.Current();
1821 if (current->NeedsEnvironment()) {
1822 current->GetEnvironment()->SetAndCopyParentChain(
1823 outer_graph->GetArena(), invoke->GetEnvironment());
1824 }
1825 }
1826 }
1827 }
1828 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1829 if (HasBoundsChecks()) {
1830 outer_graph->SetHasBoundsChecks(true);
1831 }
1832
Calin Juravle2e768302015-07-28 14:41:11 +00001833 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001834 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001835 // Simple case of an entry block, a body block, and an exit block.
1836 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001837 HBasicBlock* body = GetBlocks()[1];
1838 DCHECK(GetBlocks()[0]->IsEntryBlock());
1839 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001840 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001841 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001842 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001843
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001844 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1845 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001846
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001847 // Replace the invoke with the return value of the inlined graph.
1848 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001849 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001850 } else {
1851 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001852 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001853
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001854 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001855 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001856 // Need to inline multiple blocks. We split `invoke`'s block
1857 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001858 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001859 // with the second half.
1860 ArenaAllocator* allocator = outer_graph->GetArena();
1861 HBasicBlock* at = invoke->GetBlock();
1862 HBasicBlock* to = at->SplitAfter(invoke);
1863
Vladimir Markoec7802a2015-10-01 20:57:57 +01001864 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001865 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001866 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001867 exit_block_->ReplaceWith(to);
1868
1869 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001870 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001871 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001872 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001873 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001874 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001875 if (!returns_void) {
1876 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001877 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001878 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001879 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001880 } else {
1881 if (!returns_void) {
1882 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001883 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001884 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001885 to->AddPhi(return_value->AsPhi());
1886 }
Vladimir Marko60584552015-09-03 13:35:12 +00001887 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001888 HInstruction* last = predecessor->GetLastInstruction();
1889 if (!returns_void) {
1890 return_value->AsPhi()->AddInput(last->InputAt(0));
1891 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001892 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001893 predecessor->RemoveInstruction(last);
1894 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001895 }
1896
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001897 // Update the meta information surrounding blocks:
1898 // (1) the graph they are now in,
1899 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001900 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05001901 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001902 // Note that we do not need to update catch phi inputs because they
1903 // correspond to the register file of the outer method which the inlinee
1904 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001905
1906 // We don't add the entry block, the exit block, and the first block, which
1907 // has been merged with `at`.
1908 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1909
1910 // We add the `to` block.
1911 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001912 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001913 + kNumberOfNewBlocksInCaller;
1914
1915 // Find the location of `at` in the outer graph's reverse post order. The new
1916 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001917 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001918 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1919
David Brazdil95177982015-10-30 12:56:58 -05001920 HLoopInformation* loop_info = at->GetLoopInformation();
1921 // Copy TryCatchInformation if `at` is a try block, not if it is a catch block.
1922 TryCatchInformation* try_catch_info = at->IsTryBlock() ? at->GetTryCatchInformation() : nullptr;
1923
1924 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1925 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001926 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1927 HBasicBlock* current = it.Current();
1928 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05001929 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001930 DCHECK(current->GetGraph() == this);
1931 current->SetGraph(outer_graph);
1932 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001933 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001934 if (!current->IsInLoop()) {
David Brazdil95177982015-10-30 12:56:58 -05001935 current->SetLoopInformation(loop_info);
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001936 } else if (current->IsLoopHeader()) {
1937 // Clear the information of which blocks are contained in that loop. Since the
1938 // information is stored as a bit vector based on block ids, we have to update
1939 // it, as those block ids were specific to the callee graph and we are now adding
1940 // these blocks to the caller graph.
1941 current->GetLoopInformation()->ClearAllBlocks();
1942 }
1943 if (current->IsInLoop()) {
1944 for (HLoopInformationOutwardIterator loop_it(*current);
1945 !loop_it.Done();
1946 loop_it.Advance()) {
David Brazdil7d275372015-04-21 16:36:35 +01001947 loop_it.Current()->Add(current);
1948 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001949 }
David Brazdil95177982015-10-30 12:56:58 -05001950 current->SetTryCatchInformation(try_catch_info);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001951 }
1952 }
1953
David Brazdil95177982015-10-30 12:56:58 -05001954 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001955 to->SetGraph(outer_graph);
1956 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001957 outer_graph->reverse_post_order_[++index_of_at] = to;
David Brazdil95177982015-10-30 12:56:58 -05001958 if (loop_info != nullptr) {
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001959 if (!to->IsInLoop()) {
1960 to->SetLoopInformation(loop_info);
1961 }
David Brazdil7d275372015-04-21 16:36:35 +01001962 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1963 loop_it.Current()->Add(to);
1964 }
David Brazdil95177982015-10-30 12:56:58 -05001965 if (loop_info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001966 // Only `to` can become a back edge, as the inlined blocks
1967 // are predecessors of `to`.
David Brazdil95177982015-10-30 12:56:58 -05001968 loop_info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001969 }
1970 }
David Brazdil95177982015-10-30 12:56:58 -05001971 to->SetTryCatchInformation(try_catch_info);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001972 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001973
David Brazdil05144f42015-04-16 15:18:00 +01001974 // Update the next instruction id of the outer graph, so that instructions
1975 // added later get bigger ids than those in the inner graph.
1976 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1977
1978 // Walk over the entry block and:
1979 // - Move constants from the entry block to the outer_graph's entry block,
1980 // - Replace HParameterValue instructions with their real value.
1981 // - Remove suspend checks, that hold an environment.
1982 // We must do this after the other blocks have been inlined, otherwise ids of
1983 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001984 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001985 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1986 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01001987 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01001988 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001989 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001990 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001991 replacement = outer_graph->GetIntConstant(
1992 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001993 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001994 replacement = outer_graph->GetLongConstant(
1995 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001996 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001997 replacement = outer_graph->GetFloatConstant(
1998 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001999 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002000 replacement = outer_graph->GetDoubleConstant(
2001 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002002 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002003 if (kIsDebugBuild
2004 && invoke->IsInvokeStaticOrDirect()
2005 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2006 // Ensure we do not use the last input of `invoke`, as it
2007 // contains a clinit check which is not an actual argument.
2008 size_t last_input_index = invoke->InputCount() - 1;
2009 DCHECK(parameter_index != last_input_index);
2010 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002011 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002012 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002013 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002014 } else {
2015 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2016 entry_block_->RemoveInstruction(current);
2017 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002018 if (replacement != nullptr) {
2019 current->ReplaceWith(replacement);
2020 // If the current is the return value then we need to update the latter.
2021 if (current == return_value) {
2022 DCHECK_EQ(entry_block_, return_value->GetBlock());
2023 return_value = replacement;
2024 }
2025 }
2026 }
2027
2028 if (return_value != nullptr) {
2029 invoke->ReplaceWith(return_value);
David Brazdil05144f42015-04-16 15:18:00 +01002030 }
2031
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002032 // Finally remove the invoke from the caller.
2033 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00002034
2035 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002036}
2037
Mingyao Yang3584bce2015-05-19 16:01:59 -07002038/*
2039 * Loop will be transformed to:
2040 * old_pre_header
2041 * |
2042 * if_block
2043 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002044 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002045 * \ /
2046 * new_pre_header
2047 * |
2048 * header
2049 */
2050void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2051 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002052 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002053
Aart Bik3fc7f352015-11-20 22:03:03 -08002054 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002055 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002056 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2057 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002058 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2059 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002060 AddBlock(true_block);
2061 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002062 AddBlock(new_pre_header);
2063
Aart Bik3fc7f352015-11-20 22:03:03 -08002064 header->ReplacePredecessor(old_pre_header, new_pre_header);
2065 old_pre_header->successors_.clear();
2066 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002067
Aart Bik3fc7f352015-11-20 22:03:03 -08002068 old_pre_header->AddSuccessor(if_block);
2069 if_block->AddSuccessor(true_block); // True successor
2070 if_block->AddSuccessor(false_block); // False successor
2071 true_block->AddSuccessor(new_pre_header);
2072 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002073
Aart Bik3fc7f352015-11-20 22:03:03 -08002074 old_pre_header->dominated_blocks_.push_back(if_block);
2075 if_block->SetDominator(old_pre_header);
2076 if_block->dominated_blocks_.push_back(true_block);
2077 true_block->SetDominator(if_block);
2078 if_block->dominated_blocks_.push_back(false_block);
2079 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002080 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002081 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002082 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002083 header->SetDominator(new_pre_header);
2084
Aart Bik3fc7f352015-11-20 22:03:03 -08002085 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002086 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002087 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002088 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002089 reverse_post_order_[index_of_header++] = true_block;
2090 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002091 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002092
Aart Bik3fc7f352015-11-20 22:03:03 -08002093 // Fix loop information.
2094 HLoopInformation* loop_info = old_pre_header->GetLoopInformation();
2095 if (loop_info != nullptr) {
2096 if_block->SetLoopInformation(loop_info);
2097 true_block->SetLoopInformation(loop_info);
2098 false_block->SetLoopInformation(loop_info);
2099 new_pre_header->SetLoopInformation(loop_info);
2100 // Add blocks to all enveloping loops.
2101 for (HLoopInformationOutwardIterator loop_it(*old_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002102 !loop_it.Done();
2103 loop_it.Advance()) {
2104 loop_it.Current()->Add(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002105 loop_it.Current()->Add(true_block);
2106 loop_it.Current()->Add(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002107 loop_it.Current()->Add(new_pre_header);
2108 }
2109 }
Aart Bik3fc7f352015-11-20 22:03:03 -08002110
2111 // Fix try/catch information.
2112 TryCatchInformation* try_catch_info = old_pre_header->IsTryBlock()
2113 ? old_pre_header->GetTryCatchInformation()
2114 : nullptr;
2115 if_block->SetTryCatchInformation(try_catch_info);
2116 true_block->SetTryCatchInformation(try_catch_info);
2117 false_block->SetTryCatchInformation(try_catch_info);
2118 new_pre_header->SetTryCatchInformation(try_catch_info);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002119}
2120
David Brazdilf5552582015-12-27 13:36:12 +00002121static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2122 SHARED_REQUIRES(Locks::mutator_lock_) {
2123 if (rti.IsValid()) {
2124 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2125 << " upper_bound_rti: " << upper_bound_rti
2126 << " rti: " << rti;
2127 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
2128 }
2129}
2130
Calin Juravle2e768302015-07-28 14:41:11 +00002131void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2132 if (kIsDebugBuild) {
2133 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2134 ScopedObjectAccess soa(Thread::Current());
2135 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2136 if (IsBoundType()) {
2137 // Having the test here spares us from making the method virtual just for
2138 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002139 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002140 }
2141 }
2142 reference_type_info_ = rti;
2143}
2144
David Brazdilf5552582015-12-27 13:36:12 +00002145void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2146 if (kIsDebugBuild) {
2147 ScopedObjectAccess soa(Thread::Current());
2148 DCHECK(upper_bound.IsValid());
2149 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2150 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2151 }
2152 upper_bound_ = upper_bound;
2153 upper_can_be_null_ = can_be_null;
2154}
2155
Calin Juravle2e768302015-07-28 14:41:11 +00002156ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
2157
2158ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
2159 : type_handle_(type_handle), is_exact_(is_exact) {
2160 if (kIsDebugBuild) {
2161 ScopedObjectAccess soa(Thread::Current());
2162 DCHECK(IsValidHandle(type_handle));
2163 }
2164}
2165
Calin Juravleacf735c2015-02-12 15:25:22 +00002166std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2167 ScopedObjectAccess soa(Thread::Current());
2168 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002169 << " is_valid=" << rhs.IsValid()
2170 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002171 << " is_exact=" << rhs.IsExact()
2172 << " ]";
2173 return os;
2174}
2175
Mark Mendellc4701932015-04-10 13:18:51 -04002176bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2177 // For now, assume that instructions in different blocks may use the
2178 // environment.
2179 // TODO: Use the control flow to decide if this is true.
2180 if (GetBlock() != other->GetBlock()) {
2181 return true;
2182 }
2183
2184 // We know that we are in the same block. Walk from 'this' to 'other',
2185 // checking to see if there is any instruction with an environment.
2186 HInstruction* current = this;
2187 for (; current != other && current != nullptr; current = current->GetNext()) {
2188 // This is a conservative check, as the instruction result may not be in
2189 // the referenced environment.
2190 if (current->HasEnvironment()) {
2191 return true;
2192 }
2193 }
2194
2195 // We should have been called with 'this' before 'other' in the block.
2196 // Just confirm this.
2197 DCHECK(current != nullptr);
2198 return false;
2199}
2200
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002201void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002202 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2203 IntrinsicSideEffects side_effects,
2204 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002205 intrinsic_ = intrinsic;
2206 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002207
Aart Bik5d75afe2015-12-14 11:57:01 -08002208 // Adjust method's side effects from intrinsic table.
2209 switch (side_effects) {
2210 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2211 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2212 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2213 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2214 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002215
2216 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2217 opt.SetDoesNotNeedDexCache();
2218 opt.SetDoesNotNeedEnvironment();
2219 } else {
2220 // If we need an environment, that means there will be a call, which can trigger GC.
2221 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2222 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002223 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002224 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002225}
2226
David Brazdil6de19382016-01-08 17:37:10 +00002227bool HNewInstance::IsStringAlloc() const {
2228 ScopedObjectAccess soa(Thread::Current());
2229 return GetReferenceTypeInfo().IsStringClass();
2230}
2231
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002232bool HInvoke::NeedsEnvironment() const {
2233 if (!IsIntrinsic()) {
2234 return true;
2235 }
2236 IntrinsicOptimizations opt(*this);
2237 return !opt.GetDoesNotNeedEnvironment();
2238}
2239
Vladimir Markodc151b22015-10-15 18:02:30 +01002240bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2241 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002242 return false;
2243 }
2244 if (!IsIntrinsic()) {
2245 return true;
2246 }
2247 IntrinsicOptimizations opt(*this);
2248 return !opt.GetDoesNotNeedDexCache();
2249}
2250
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002251void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2252 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2253 input->AddUseAt(this, index);
2254 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2255 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2256 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2257 InputRecordAt(i).GetUseNode()->SetIndex(i);
2258 }
2259}
2260
Vladimir Markob554b5a2015-11-06 12:57:55 +00002261void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2262 RemoveAsUserOfInput(index);
2263 inputs_.erase(inputs_.begin() + index);
2264 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2265 for (size_t i = index, e = InputCount(); i < e; ++i) {
2266 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2267 InputRecordAt(i).GetUseNode()->SetIndex(i);
2268 }
2269}
2270
Vladimir Markof64242a2015-12-01 14:58:23 +00002271std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2272 switch (rhs) {
2273 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2274 return os << "string_init";
2275 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2276 return os << "recursive";
2277 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2278 return os << "direct";
2279 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2280 return os << "direct_fixup";
2281 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2282 return os << "dex_cache_pc_relative";
2283 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2284 return os << "dex_cache_via_method";
2285 default:
2286 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2287 UNREACHABLE();
2288 }
2289}
2290
Vladimir Markofbb184a2015-11-13 14:47:00 +00002291std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2292 switch (rhs) {
2293 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2294 return os << "explicit";
2295 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2296 return os << "implicit";
2297 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2298 return os << "none";
2299 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002300 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2301 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002302 }
2303}
2304
Mark Mendellc4701932015-04-10 13:18:51 -04002305void HInstruction::RemoveEnvironmentUsers() {
2306 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2307 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2308 HEnvironment* user = user_node->GetUser();
2309 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2310 }
2311 env_uses_.Clear();
2312}
2313
Mark Mendellf6529172015-11-17 11:16:56 -05002314// Returns an instruction with the opposite boolean value from 'cond'.
2315HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2316 ArenaAllocator* allocator = GetArena();
2317
2318 if (cond->IsCondition() &&
2319 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2320 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2321 HInstruction* lhs = cond->InputAt(0);
2322 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002323 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002324 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2325 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2326 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2327 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2328 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2329 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2330 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2331 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2332 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2333 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2334 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002335 default:
2336 LOG(FATAL) << "Unexpected condition";
2337 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002338 }
2339 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2340 return replacement;
2341 } else if (cond->IsIntConstant()) {
2342 HIntConstant* int_const = cond->AsIntConstant();
2343 if (int_const->IsZero()) {
2344 return GetIntConstant(1);
2345 } else {
2346 DCHECK(int_const->IsOne());
2347 return GetIntConstant(0);
2348 }
2349 } else {
2350 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2351 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2352 return replacement;
2353 }
2354}
2355
Roland Levillainc9285912015-12-18 10:38:42 +00002356std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2357 os << "["
2358 << " source=" << rhs.GetSource()
2359 << " destination=" << rhs.GetDestination()
2360 << " type=" << rhs.GetType()
2361 << " instruction=";
2362 if (rhs.GetInstruction() != nullptr) {
2363 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2364 } else {
2365 os << "null";
2366 }
2367 os << " ]";
2368 return os;
2369}
2370
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002371} // namespace art