blob: 854d92a4096789a2caddf47546fa48d0445bd296 [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()) {
170 HBasicBlock* current = it.Current();
171 if (current->IsLoopHeader()) {
172 current->RemoveInstruction(current->GetLoopInformation()->GetSuspendCheck());
173 }
174 current->SetLoopInformation(nullptr);
175 }
176}
177
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100178void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000179 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100180 dominator_ = nullptr;
181}
182
183void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100184 DCHECK(reverse_post_order_.empty());
185 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100186 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100187
188 // Number of visits of a given node, indexed by block id.
189 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
190 // Number of successors visited from a given node, indexed by block id.
191 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
192 // Nodes for which we need to visit successors.
193 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
194 constexpr size_t kDefaultWorklistSize = 8;
195 worklist.reserve(kDefaultWorklistSize);
196 worklist.push_back(entry_block_);
197
198 while (!worklist.empty()) {
199 HBasicBlock* current = worklist.back();
200 uint32_t current_id = current->GetBlockId();
201 if (successors_visited[current_id] == current->GetSuccessors().size()) {
202 worklist.pop_back();
203 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100204 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
205
206 if (successor->GetDominator() == nullptr) {
207 successor->SetDominator(current);
208 } else {
Vladimir Marko391d01f2015-11-06 11:02:08 +0000209 // The CommonDominator can work for multiple blocks as long as the
210 // domination information doesn't change. However, since we're changing
211 // that information here, we can use the finder only for pairs of blocks.
212 successor->SetDominator(CommonDominator::ForPair(successor->GetDominator(), current));
Vladimir Markod76d1392015-09-23 16:07:14 +0100213 }
214
215 // Once all the forward edges have been visited, we know the immediate
216 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100217 if (++visits[successor->GetBlockId()] ==
218 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100219 reverse_post_order_.push_back(successor);
220 worklist.push_back(successor);
221 }
222 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000223 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000224
225 // Populate `dominated_blocks_` information after computing all dominators.
226 // The potential presence of irreducible loops require to do it after.
227 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
228 HBasicBlock* block = it.Current();
229 if (!block->IsEntryBlock()) {
230 block->GetDominator()->AddDominatedBlock(block);
231 }
232 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000233}
234
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000235GraphAnalysisResult HGraph::TryBuildingSsa(StackHandleScopeCollection* handles) {
236 GraphAnalysisResult result = BuildDominatorTree();
237 if (result != kAnalysisSuccess) {
David Brazdil4833f5a2015-12-16 10:37:39 +0000238 return result;
239 }
240
David Brazdil4833f5a2015-12-16 10:37:39 +0000241 // Create the inexact Object reference type and store it in the HGraph.
242 ScopedObjectAccess soa(Thread::Current());
243 ClassLinker* linker = Runtime::Current()->GetClassLinker();
244 inexact_object_rti_ = ReferenceTypeInfo::Create(
245 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
246 /* is_exact */ false);
247
248 // Tranforms graph to SSA form.
249 result = SsaBuilder(this, handles).BuildSsa();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000250 if (result != kAnalysisSuccess) {
David Brazdil4833f5a2015-12-16 10:37:39 +0000251 return result;
252 }
253
254 in_ssa_form_ = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000255 return kAnalysisSuccess;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100256}
257
David Brazdilfc6a86a2015-06-26 10:33:45 +0000258HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000259 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
260 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000261 // Use `InsertBetween` to ensure the predecessor index and successor index of
262 // `block` and `successor` are preserved.
263 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000264 return new_block;
265}
266
267void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
268 // Insert a new node between `block` and `successor` to split the
269 // critical edge.
270 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600271 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100272 if (successor->IsLoopHeader()) {
273 // If we split at a back edge boundary, make the new block the back edge.
274 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000275 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100276 info->RemoveBackEdge(block);
277 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100278 }
279 }
280}
281
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100282void HGraph::SimplifyLoop(HBasicBlock* header) {
283 HLoopInformation* info = header->GetLoopInformation();
284
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100285 // Make sure the loop has only one pre header. This simplifies SSA building by having
286 // to just look at the pre header to know which locals are initialized at entry of the
287 // loop.
Vladimir Marko60584552015-09-03 13:35:12 +0000288 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100289 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100290 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100291 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600292 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100293
Vladimir Marko60584552015-09-03 13:35:12 +0000294 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100295 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100296 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100297 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100298 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100299 }
300 }
301 pre_header->AddSuccessor(header);
302 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100303
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100304 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100305 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
306 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000307 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100308 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100309 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000310 header->predecessors_[pred] = to_swap;
311 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100312 break;
313 }
314 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100315 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100316
317 // Place the suspend check at the beginning of the header, so that live registers
318 // will be known when allocating registers. Note that code generation can still
319 // generate the suspend check at the back edge, but needs to be careful with
320 // loop phi spill slots (which are not written to at back edge).
321 HInstruction* first_instruction = header->GetFirstInstruction();
322 if (!first_instruction->IsSuspendCheck()) {
323 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
324 header->InsertInstructionBefore(check, first_instruction);
325 first_instruction = check;
326 }
327 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100328}
329
David Brazdilffee3d32015-07-06 11:48:53 +0100330static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100331 HBasicBlock* predecessor = block.GetPredecessors()[pred_idx];
David Brazdilffee3d32015-07-06 11:48:53 +0100332 if (!predecessor->EndsWithTryBoundary()) {
333 // Only edges from HTryBoundary can be exceptional.
334 return false;
335 }
336 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
337 if (try_boundary->GetNormalFlowSuccessor() == &block) {
338 // This block is the normal-flow successor of `try_boundary`, but it could
339 // also be one of its exception handlers if catch blocks have not been
340 // simplified yet. Predecessors are unordered, so we will consider the first
341 // occurrence to be the normal edge and a possible second occurrence to be
342 // the exceptional edge.
343 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
344 } else {
345 // This is not the normal-flow successor of `try_boundary`, hence it must be
346 // one of its exception handlers.
347 DCHECK(try_boundary->HasExceptionHandler(block));
348 return true;
349 }
350}
351
352void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100353 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
354 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
355 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
356 HBasicBlock* catch_block = blocks_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000357 if (catch_block == nullptr || !catch_block->IsCatchBlock()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100358 continue;
359 }
360
361 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000362 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100363 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
364 exceptional_predecessors_only = false;
365 break;
366 }
367 }
368
369 if (!exceptional_predecessors_only) {
370 // Catch block has normal-flow predecessors and needs to be simplified.
371 // Splitting the block before its first instruction moves all its
372 // instructions into `normal_block` and links the two blocks with a Goto.
373 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
374 // leaving `catch_block` with the exceptional edges only.
David Brazdil9bc43612015-11-05 21:25:24 +0000375 //
David Brazdilffee3d32015-07-06 11:48:53 +0100376 // Note that catch blocks with normal-flow predecessors cannot begin with
David Brazdil9bc43612015-11-05 21:25:24 +0000377 // a move-exception instruction, as guaranteed by the verifier. However,
378 // trivially dead predecessors are ignored by the verifier and such code
379 // has not been removed at this stage. We therefore ignore the assumption
380 // and rely on GraphChecker to enforce it after initial DCE is run (b/25492628).
381 HBasicBlock* normal_block = catch_block->SplitCatchBlockAfterMoveException();
382 if (normal_block == nullptr) {
383 // Catch block is either empty or only contains a move-exception. It must
384 // therefore be dead and will be removed during initial DCE. Do nothing.
385 DCHECK(!catch_block->EndsWithControlFlowInstruction());
386 } else {
387 // Catch block was split. Re-link normal-flow edges to the new block.
388 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
389 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
390 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
391 --j;
392 }
David Brazdilffee3d32015-07-06 11:48:53 +0100393 }
394 }
395 }
396 }
397}
398
399void HGraph::ComputeTryBlockInformation() {
400 // Iterate in reverse post order to propagate try membership information from
401 // predecessors to their successors.
402 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
403 HBasicBlock* block = it.Current();
404 if (block->IsEntryBlock() || block->IsCatchBlock()) {
405 // Catch blocks after simplification have only exceptional predecessors
406 // and hence are never in tries.
407 continue;
408 }
409
410 // Infer try membership from the first predecessor. Having simplified loops,
411 // the first predecessor can never be a back edge and therefore it must have
412 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100413 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100414 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100415 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000416 if (try_entry != nullptr &&
417 (block->GetTryCatchInformation() == nullptr ||
418 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
419 // We are either setting try block membership for the first time or it
420 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100421 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
422 }
David Brazdilffee3d32015-07-06 11:48:53 +0100423 }
424}
425
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100426void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000427// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100428 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000429 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100430 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
431 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
432 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
433 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100434 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000435 if (block->GetSuccessors().size() > 1) {
436 // Only split normal-flow edges. We cannot split exceptional edges as they
437 // are synthesized (approximate real control flow), and we do not need to
438 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000439 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
440 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
441 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100442 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000443 if (successor == exit_block_) {
444 // Throw->TryBoundary->Exit. Special case which we do not want to split
445 // because Goto->Exit is not allowed.
446 DCHECK(block->IsSingleTryBoundary());
447 DCHECK(block->GetSinglePredecessor()->GetLastInstruction()->IsThrow());
448 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100449 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000450 // SplitCriticalEdge could have invalidated the `normal_successors`
451 // ArrayRef. We must re-acquire it.
452 normal_successors = block->GetNormalSuccessors();
453 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
454 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100455 }
456 }
457 }
458 if (block->IsLoopHeader()) {
459 SimplifyLoop(block);
460 }
461 }
462}
463
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000464GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100465 // Order does not matter.
466 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
467 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100468 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100469 if (block->IsCatchBlock()) {
470 // TODO: Dealing with exceptional back edges could be tricky because
471 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000472 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100473 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000474 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100475 }
476 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000477 return kAnalysisSuccess;
478}
479
480void HLoopInformation::Dump(std::ostream& os) {
481 os << "header: " << header_->GetBlockId() << std::endl;
482 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
483 for (HBasicBlock* block : back_edges_) {
484 os << "back edge: " << block->GetBlockId() << std::endl;
485 }
486 for (HBasicBlock* block : header_->GetPredecessors()) {
487 os << "predecessor: " << block->GetBlockId() << std::endl;
488 }
489 for (uint32_t idx : blocks_.Indexes()) {
490 os << " in loop: " << idx << std::endl;
491 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100492}
493
David Brazdil8d5b8b22015-03-24 10:51:52 +0000494void HGraph::InsertConstant(HConstant* constant) {
495 // New constants are inserted before the final control-flow instruction
496 // of the graph, or at its end if called from the graph builder.
497 if (entry_block_->EndsWithControlFlowInstruction()) {
498 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000499 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000500 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000501 }
502}
503
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600504HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100505 // For simplicity, don't bother reviving the cached null constant if it is
506 // not null and not in a block. Otherwise, we need to clear the instruction
507 // id and/or any invariants the graph is assuming when adding new instructions.
508 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600509 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000510 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000511 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000512 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000513 if (kIsDebugBuild) {
514 ScopedObjectAccess soa(Thread::Current());
515 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
516 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000517 return cached_null_constant_;
518}
519
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100520HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100521 // For simplicity, don't bother reviving the cached current method if it is
522 // not null and not in a block. Otherwise, we need to clear the instruction
523 // id and/or any invariants the graph is assuming when adding new instructions.
524 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700525 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600526 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
527 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100528 if (entry_block_->GetFirstInstruction() == nullptr) {
529 entry_block_->AddInstruction(cached_current_method_);
530 } else {
531 entry_block_->InsertInstructionBefore(
532 cached_current_method_, entry_block_->GetFirstInstruction());
533 }
534 }
535 return cached_current_method_;
536}
537
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600538HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000539 switch (type) {
540 case Primitive::Type::kPrimBoolean:
541 DCHECK(IsUint<1>(value));
542 FALLTHROUGH_INTENDED;
543 case Primitive::Type::kPrimByte:
544 case Primitive::Type::kPrimChar:
545 case Primitive::Type::kPrimShort:
546 case Primitive::Type::kPrimInt:
547 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600548 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000549
550 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600551 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000552
553 default:
554 LOG(FATAL) << "Unsupported constant type";
555 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000556 }
David Brazdil46e2a392015-03-16 17:31:52 +0000557}
558
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000559void HGraph::CacheFloatConstant(HFloatConstant* constant) {
560 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
561 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
562 cached_float_constants_.Overwrite(value, constant);
563}
564
565void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
566 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
567 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
568 cached_double_constants_.Overwrite(value, constant);
569}
570
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000571void HLoopInformation::Add(HBasicBlock* block) {
572 blocks_.SetBit(block->GetBlockId());
573}
574
David Brazdil46e2a392015-03-16 17:31:52 +0000575void HLoopInformation::Remove(HBasicBlock* block) {
576 blocks_.ClearBit(block->GetBlockId());
577}
578
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100579void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
580 if (blocks_.IsBitSet(block->GetBlockId())) {
581 return;
582 }
583
584 blocks_.SetBit(block->GetBlockId());
585 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000586 for (HBasicBlock* predecessor : block->GetPredecessors()) {
587 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100588 }
589}
590
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000591void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block) {
592 if (blocks_.IsBitSet(block->GetBlockId())) {
593 return;
594 }
595
596 if (block->IsLoopHeader()) {
597 // If we hit a loop header in an irreducible loop, we first check if the
598 // pre header of that loop belongs to the currently analyzed loop. If it does,
599 // then we visit the back edges.
600 // Note that we cannot use GetPreHeader, as the loop may have not been populated
601 // yet.
602 HBasicBlock* pre_header = block->GetPredecessors()[0];
603 PopulateIrreducibleRecursive(pre_header);
604 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
605 blocks_.SetBit(block->GetBlockId());
606 block->SetInLoop(this);
607 HLoopInformation* info = block->GetLoopInformation();
608 for (HBasicBlock* back_edge : info->GetBackEdges()) {
609 PopulateIrreducibleRecursive(back_edge);
610 }
611 }
612 } else {
613 // Visit all predecessors. If one predecessor is part of the loop, this
614 // block is also part of this loop.
615 for (HBasicBlock* predecessor : block->GetPredecessors()) {
616 PopulateIrreducibleRecursive(predecessor);
617 if (blocks_.IsBitSet(predecessor->GetBlockId())) {
618 blocks_.SetBit(block->GetBlockId());
619 block->SetInLoop(this);
620 }
621 }
622 }
623}
624
625void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100626 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000627 // Populate this loop: starting with the back edge, recursively add predecessors
628 // that are not already part of that loop. Set the header as part of the loop
629 // to end the recursion.
630 // This is a recursive implementation of the algorithm described in
631 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
632 blocks_.SetBit(header_->GetBlockId());
633 header_->SetInLoop(this);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100634 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100635 DCHECK(back_edge->GetDominator() != nullptr);
636 if (!header_->Dominates(back_edge)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000637 irreducible_ = true;
638 header_->GetGraph()->SetHasIrreducibleLoops(true);
639 PopulateIrreducibleRecursive(back_edge);
640 } else {
641 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100642 }
David Brazdila4b8c212015-05-07 09:59:30 +0100643 }
644}
645
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100646HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000647 HBasicBlock* block = header_->GetPredecessors()[0];
648 DCHECK(irreducible_ || (block == header_->GetDominator()));
649 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100650}
651
652bool HLoopInformation::Contains(const HBasicBlock& block) const {
653 return blocks_.IsBitSet(block.GetBlockId());
654}
655
656bool HLoopInformation::IsIn(const HLoopInformation& other) const {
657 return other.blocks_.IsBitSet(header_->GetBlockId());
658}
659
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800660bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
661 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700662}
663
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100664size_t HLoopInformation::GetLifetimeEnd() const {
665 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100666 for (HBasicBlock* back_edge : GetBackEdges()) {
667 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100668 }
669 return last_position;
670}
671
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100672bool HBasicBlock::Dominates(HBasicBlock* other) const {
673 // Walk up the dominator tree from `other`, to find out if `this`
674 // is an ancestor.
675 HBasicBlock* current = other;
676 while (current != nullptr) {
677 if (current == this) {
678 return true;
679 }
680 current = current->GetDominator();
681 }
682 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100683}
684
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100685static void UpdateInputsUsers(HInstruction* instruction) {
686 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
687 instruction->InputAt(i)->AddUseAt(instruction, i);
688 }
689 // Environment should be created later.
690 DCHECK(!instruction->HasEnvironment());
691}
692
Roland Levillainccc07a92014-09-16 14:48:16 +0100693void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
694 HInstruction* replacement) {
695 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400696 if (initial->IsControlFlow()) {
697 // We can only replace a control flow instruction with another control flow instruction.
698 DCHECK(replacement->IsControlFlow());
699 DCHECK_EQ(replacement->GetId(), -1);
700 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
701 DCHECK_EQ(initial->GetBlock(), this);
702 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
703 DCHECK(initial->GetUses().IsEmpty());
704 DCHECK(initial->GetEnvUses().IsEmpty());
705 replacement->SetBlock(this);
706 replacement->SetId(GetGraph()->GetNextInstructionId());
707 instructions_.InsertInstructionBefore(replacement, initial);
708 UpdateInputsUsers(replacement);
709 } else {
710 InsertInstructionBefore(replacement, initial);
711 initial->ReplaceWith(replacement);
712 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100713 RemoveInstruction(initial);
714}
715
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100716static void Add(HInstructionList* instruction_list,
717 HBasicBlock* block,
718 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000719 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000720 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100721 instruction->SetBlock(block);
722 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100723 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100724 instruction_list->AddInstruction(instruction);
725}
726
727void HBasicBlock::AddInstruction(HInstruction* instruction) {
728 Add(&instructions_, this, instruction);
729}
730
731void HBasicBlock::AddPhi(HPhi* phi) {
732 Add(&phis_, this, phi);
733}
734
David Brazdilc3d743f2015-04-22 13:40:50 +0100735void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
736 DCHECK(!cursor->IsPhi());
737 DCHECK(!instruction->IsPhi());
738 DCHECK_EQ(instruction->GetId(), -1);
739 DCHECK_NE(cursor->GetId(), -1);
740 DCHECK_EQ(cursor->GetBlock(), this);
741 DCHECK(!instruction->IsControlFlow());
742 instruction->SetBlock(this);
743 instruction->SetId(GetGraph()->GetNextInstructionId());
744 UpdateInputsUsers(instruction);
745 instructions_.InsertInstructionBefore(instruction, cursor);
746}
747
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100748void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
749 DCHECK(!cursor->IsPhi());
750 DCHECK(!instruction->IsPhi());
751 DCHECK_EQ(instruction->GetId(), -1);
752 DCHECK_NE(cursor->GetId(), -1);
753 DCHECK_EQ(cursor->GetBlock(), this);
754 DCHECK(!instruction->IsControlFlow());
755 DCHECK(!cursor->IsControlFlow());
756 instruction->SetBlock(this);
757 instruction->SetId(GetGraph()->GetNextInstructionId());
758 UpdateInputsUsers(instruction);
759 instructions_.InsertInstructionAfter(instruction, cursor);
760}
761
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100762void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
763 DCHECK_EQ(phi->GetId(), -1);
764 DCHECK_NE(cursor->GetId(), -1);
765 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100766 phi->SetBlock(this);
767 phi->SetId(GetGraph()->GetNextInstructionId());
768 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100769 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100770}
771
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100772static void Remove(HInstructionList* instruction_list,
773 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000774 HInstruction* instruction,
775 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100776 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100777 instruction->SetBlock(nullptr);
778 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000779 if (ensure_safety) {
780 DCHECK(instruction->GetUses().IsEmpty());
781 DCHECK(instruction->GetEnvUses().IsEmpty());
782 RemoveAsUser(instruction);
783 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100784}
785
David Brazdil1abb4192015-02-17 18:33:36 +0000786void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100787 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000788 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100789}
790
David Brazdil1abb4192015-02-17 18:33:36 +0000791void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
792 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100793}
794
David Brazdilc7508e92015-04-27 13:28:57 +0100795void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
796 if (instruction->IsPhi()) {
797 RemovePhi(instruction->AsPhi(), ensure_safety);
798 } else {
799 RemoveInstruction(instruction, ensure_safety);
800 }
801}
802
Vladimir Marko71bf8092015-09-15 15:33:14 +0100803void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
804 for (size_t i = 0; i < locals.size(); i++) {
805 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100806 SetRawEnvAt(i, instruction);
807 if (instruction != nullptr) {
808 instruction->AddEnvUseAt(this, i);
809 }
810 }
811}
812
David Brazdiled596192015-01-23 10:39:45 +0000813void HEnvironment::CopyFrom(HEnvironment* env) {
814 for (size_t i = 0; i < env->Size(); i++) {
815 HInstruction* instruction = env->GetInstructionAt(i);
816 SetRawEnvAt(i, instruction);
817 if (instruction != nullptr) {
818 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100819 }
David Brazdiled596192015-01-23 10:39:45 +0000820 }
821}
822
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700823void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
824 HBasicBlock* loop_header) {
825 DCHECK(loop_header->IsLoopHeader());
826 for (size_t i = 0; i < env->Size(); i++) {
827 HInstruction* instruction = env->GetInstructionAt(i);
828 SetRawEnvAt(i, instruction);
829 if (instruction == nullptr) {
830 continue;
831 }
832 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
833 // At the end of the loop pre-header, the corresponding value for instruction
834 // is the first input of the phi.
835 HInstruction* initial = instruction->AsPhi()->InputAt(0);
836 DCHECK(initial->GetBlock()->Dominates(loop_header));
837 SetRawEnvAt(i, initial);
838 initial->AddEnvUseAt(this, i);
839 } else {
840 instruction->AddEnvUseAt(this, i);
841 }
842 }
843}
844
David Brazdil1abb4192015-02-17 18:33:36 +0000845void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100846 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000847 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100848}
849
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000850HInstruction::InstructionKind HInstruction::GetKind() const {
851 return GetKindInternal();
852}
853
Calin Juravle77520bc2015-01-12 18:45:46 +0000854HInstruction* HInstruction::GetNextDisregardingMoves() const {
855 HInstruction* next = GetNext();
856 while (next != nullptr && next->IsParallelMove()) {
857 next = next->GetNext();
858 }
859 return next;
860}
861
862HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
863 HInstruction* previous = GetPrevious();
864 while (previous != nullptr && previous->IsParallelMove()) {
865 previous = previous->GetPrevious();
866 }
867 return previous;
868}
869
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100870void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000871 if (first_instruction_ == nullptr) {
872 DCHECK(last_instruction_ == nullptr);
873 first_instruction_ = last_instruction_ = instruction;
874 } else {
875 last_instruction_->next_ = instruction;
876 instruction->previous_ = last_instruction_;
877 last_instruction_ = instruction;
878 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000879}
880
David Brazdilc3d743f2015-04-22 13:40:50 +0100881void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
882 DCHECK(Contains(cursor));
883 if (cursor == first_instruction_) {
884 cursor->previous_ = instruction;
885 instruction->next_ = cursor;
886 first_instruction_ = instruction;
887 } else {
888 instruction->previous_ = cursor->previous_;
889 instruction->next_ = cursor;
890 cursor->previous_ = instruction;
891 instruction->previous_->next_ = instruction;
892 }
893}
894
895void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
896 DCHECK(Contains(cursor));
897 if (cursor == last_instruction_) {
898 cursor->next_ = instruction;
899 instruction->previous_ = cursor;
900 last_instruction_ = instruction;
901 } else {
902 instruction->next_ = cursor->next_;
903 instruction->previous_ = cursor;
904 cursor->next_ = instruction;
905 instruction->next_->previous_ = instruction;
906 }
907}
908
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100909void HInstructionList::RemoveInstruction(HInstruction* instruction) {
910 if (instruction->previous_ != nullptr) {
911 instruction->previous_->next_ = instruction->next_;
912 }
913 if (instruction->next_ != nullptr) {
914 instruction->next_->previous_ = instruction->previous_;
915 }
916 if (instruction == first_instruction_) {
917 first_instruction_ = instruction->next_;
918 }
919 if (instruction == last_instruction_) {
920 last_instruction_ = instruction->previous_;
921 }
922}
923
Roland Levillain6b469232014-09-25 10:10:38 +0100924bool HInstructionList::Contains(HInstruction* instruction) const {
925 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
926 if (it.Current() == instruction) {
927 return true;
928 }
929 }
930 return false;
931}
932
Roland Levillainccc07a92014-09-16 14:48:16 +0100933bool HInstructionList::FoundBefore(const HInstruction* instruction1,
934 const HInstruction* instruction2) const {
935 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
936 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
937 if (it.Current() == instruction1) {
938 return true;
939 }
940 if (it.Current() == instruction2) {
941 return false;
942 }
943 }
944 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
945 return true;
946}
947
Roland Levillain6c82d402014-10-13 16:10:27 +0100948bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
949 if (other_instruction == this) {
950 // An instruction does not strictly dominate itself.
951 return false;
952 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100953 HBasicBlock* block = GetBlock();
954 HBasicBlock* other_block = other_instruction->GetBlock();
955 if (block != other_block) {
956 return GetBlock()->Dominates(other_instruction->GetBlock());
957 } else {
958 // If both instructions are in the same block, ensure this
959 // instruction comes before `other_instruction`.
960 if (IsPhi()) {
961 if (!other_instruction->IsPhi()) {
962 // Phis appear before non phi-instructions so this instruction
963 // dominates `other_instruction`.
964 return true;
965 } else {
966 // There is no order among phis.
967 LOG(FATAL) << "There is no dominance between phis of a same block.";
968 return false;
969 }
970 } else {
971 // `this` is not a phi.
972 if (other_instruction->IsPhi()) {
973 // Phis appear before non phi-instructions so this instruction
974 // does not dominate `other_instruction`.
975 return false;
976 } else {
977 // Check whether this instruction comes before
978 // `other_instruction` in the instruction list.
979 return block->GetInstructions().FoundBefore(this, other_instruction);
980 }
981 }
982 }
983}
984
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100985void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100986 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000987 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
988 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100989 HInstruction* user = current->GetUser();
990 size_t input_index = current->GetIndex();
991 user->SetRawInputAt(input_index, other);
992 other->AddUseAt(user, input_index);
993 }
994
David Brazdiled596192015-01-23 10:39:45 +0000995 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
996 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100997 HEnvironment* user = current->GetUser();
998 size_t input_index = current->GetIndex();
999 user->SetRawEnvAt(input_index, other);
1000 other->AddEnvUseAt(user, input_index);
1001 }
1002
David Brazdiled596192015-01-23 10:39:45 +00001003 uses_.Clear();
1004 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001005}
1006
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001007void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +00001008 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001009 SetRawInputAt(index, replacement);
1010 replacement->AddUseAt(this, index);
1011}
1012
Nicolas Geoffray39468442014-09-02 15:17:15 +01001013size_t HInstruction::EnvironmentSize() const {
1014 return HasEnvironment() ? environment_->Size() : 0;
1015}
1016
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001017void HPhi::AddInput(HInstruction* input) {
1018 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001019 inputs_.push_back(HUserRecord<HInstruction*>(input));
1020 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001021}
1022
David Brazdil2d7352b2015-04-20 14:52:42 +01001023void HPhi::RemoveInputAt(size_t index) {
1024 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001025 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001026 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001027 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001028 InputRecordAt(i).GetUseNode()->SetIndex(i);
1029 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001030}
1031
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001032#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001033void H##name::Accept(HGraphVisitor* visitor) { \
1034 visitor->Visit##name(this); \
1035}
1036
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001037FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001038
1039#undef DEFINE_ACCEPT
1040
1041void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001042 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1043 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001044 if (block != nullptr) {
1045 VisitBasicBlock(block);
1046 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001047 }
1048}
1049
Roland Levillain633021e2014-10-01 14:12:25 +01001050void HGraphVisitor::VisitReversePostOrder() {
1051 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1052 VisitBasicBlock(it.Current());
1053 }
1054}
1055
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001056void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001057 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001058 it.Current()->Accept(this);
1059 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001060 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001061 it.Current()->Accept(this);
1062 }
1063}
1064
Mark Mendelle82549b2015-05-06 10:55:34 -04001065HConstant* HTypeConversion::TryStaticEvaluation() const {
1066 HGraph* graph = GetBlock()->GetGraph();
1067 if (GetInput()->IsIntConstant()) {
1068 int32_t value = GetInput()->AsIntConstant()->GetValue();
1069 switch (GetResultType()) {
1070 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001071 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001072 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001073 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001074 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001075 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001076 default:
1077 return nullptr;
1078 }
1079 } else if (GetInput()->IsLongConstant()) {
1080 int64_t value = GetInput()->AsLongConstant()->GetValue();
1081 switch (GetResultType()) {
1082 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001083 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001084 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001085 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001086 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001087 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001088 default:
1089 return nullptr;
1090 }
1091 } else if (GetInput()->IsFloatConstant()) {
1092 float value = GetInput()->AsFloatConstant()->GetValue();
1093 switch (GetResultType()) {
1094 case Primitive::kPrimInt:
1095 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001096 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001097 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001098 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001099 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001100 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1101 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001102 case Primitive::kPrimLong:
1103 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001104 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001105 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001106 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001107 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001108 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1109 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001110 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001111 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001112 default:
1113 return nullptr;
1114 }
1115 } else if (GetInput()->IsDoubleConstant()) {
1116 double value = GetInput()->AsDoubleConstant()->GetValue();
1117 switch (GetResultType()) {
1118 case Primitive::kPrimInt:
1119 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001120 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001121 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001122 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001123 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001124 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1125 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001126 case Primitive::kPrimLong:
1127 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001128 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001129 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001130 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001131 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001132 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1133 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001134 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001135 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001136 default:
1137 return nullptr;
1138 }
1139 }
1140 return nullptr;
1141}
1142
Roland Levillain9240d6a2014-10-20 16:47:04 +01001143HConstant* HUnaryOperation::TryStaticEvaluation() const {
1144 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001145 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001146 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001147 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001148 }
1149 return nullptr;
1150}
1151
1152HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001153 if (GetLeft()->IsIntConstant()) {
1154 if (GetRight()->IsIntConstant()) {
1155 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1156 } else if (GetRight()->IsLongConstant()) {
1157 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1158 }
1159 } else if (GetLeft()->IsLongConstant()) {
1160 if (GetRight()->IsIntConstant()) {
1161 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1162 } else if (GetRight()->IsLongConstant()) {
1163 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001164 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001165 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
1166 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain556c3d12014-09-18 15:25:07 +01001167 }
1168 return nullptr;
1169}
Dave Allison20dfc792014-06-16 20:44:29 -07001170
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001171HConstant* HBinaryOperation::GetConstantRight() const {
1172 if (GetRight()->IsConstant()) {
1173 return GetRight()->AsConstant();
1174 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1175 return GetLeft()->AsConstant();
1176 } else {
1177 return nullptr;
1178 }
1179}
1180
1181// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001182// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001183HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1184 HInstruction* most_constant_right = GetConstantRight();
1185 if (most_constant_right == nullptr) {
1186 return nullptr;
1187 } else if (most_constant_right == GetLeft()) {
1188 return GetRight();
1189 } else {
1190 return GetLeft();
1191 }
1192}
1193
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001194bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1195 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001196}
1197
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001198bool HInstruction::Equals(HInstruction* other) const {
1199 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001200 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001201 if (!InstructionDataEquals(other)) return false;
1202 if (GetType() != other->GetType()) return false;
1203 if (InputCount() != other->InputCount()) return false;
1204
1205 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1206 if (InputAt(i) != other->InputAt(i)) return false;
1207 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001208 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001209 return true;
1210}
1211
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001212std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1213#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1214 switch (rhs) {
1215 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1216 default:
1217 os << "Unknown instruction kind " << static_cast<int>(rhs);
1218 break;
1219 }
1220#undef DECLARE_CASE
1221 return os;
1222}
1223
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001224void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001225 next_->previous_ = previous_;
1226 if (previous_ != nullptr) {
1227 previous_->next_ = next_;
1228 }
1229 if (block_->instructions_.first_instruction_ == this) {
1230 block_->instructions_.first_instruction_ = next_;
1231 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001232 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001233
1234 previous_ = cursor->previous_;
1235 if (previous_ != nullptr) {
1236 previous_->next_ = this;
1237 }
1238 next_ = cursor;
1239 cursor->previous_ = this;
1240 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001241
1242 if (block_->instructions_.first_instruction_ == cursor) {
1243 block_->instructions_.first_instruction_ = this;
1244 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001245}
1246
Vladimir Markofb337ea2015-11-25 15:25:10 +00001247void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1248 DCHECK(!CanThrow());
1249 DCHECK(!HasSideEffects());
1250 DCHECK(!HasEnvironmentUses());
1251 DCHECK(HasNonEnvironmentUses());
1252 DCHECK(!IsPhi()); // Makes no sense for Phi.
1253 DCHECK_EQ(InputCount(), 0u);
1254
1255 // Find the target block.
1256 HUseIterator<HInstruction*> uses_it(GetUses());
1257 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1258 uses_it.Advance();
1259 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1260 uses_it.Advance();
1261 }
1262 if (!uses_it.Done()) {
1263 // This instruction has uses in two or more blocks. Find the common dominator.
1264 CommonDominator finder(target_block);
1265 for (; !uses_it.Done(); uses_it.Advance()) {
1266 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1267 }
1268 target_block = finder.Get();
1269 DCHECK(target_block != nullptr);
1270 }
1271 // Move to the first dominator not in a loop.
1272 while (target_block->IsInLoop()) {
1273 target_block = target_block->GetDominator();
1274 DCHECK(target_block != nullptr);
1275 }
1276
1277 // Find insertion position.
1278 HInstruction* insert_pos = nullptr;
1279 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1280 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1281 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1282 insert_pos = uses_it2.Current()->GetUser();
1283 }
1284 }
1285 if (insert_pos == nullptr) {
1286 // No user in `target_block`, insert before the control flow instruction.
1287 insert_pos = target_block->GetLastInstruction();
1288 DCHECK(insert_pos->IsControlFlow());
1289 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1290 if (insert_pos->IsIf()) {
1291 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1292 if (if_input == insert_pos->GetPrevious()) {
1293 insert_pos = if_input;
1294 }
1295 }
1296 }
1297 MoveBefore(insert_pos);
1298}
1299
David Brazdilfc6a86a2015-06-26 10:33:45 +00001300HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001301 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001302 DCHECK_EQ(cursor->GetBlock(), this);
1303
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001304 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1305 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001306 new_block->instructions_.first_instruction_ = cursor;
1307 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1308 instructions_.last_instruction_ = cursor->previous_;
1309 if (cursor->previous_ == nullptr) {
1310 instructions_.first_instruction_ = nullptr;
1311 } else {
1312 cursor->previous_->next_ = nullptr;
1313 cursor->previous_ = nullptr;
1314 }
1315
1316 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001317 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001318
Vladimir Marko60584552015-09-03 13:35:12 +00001319 for (HBasicBlock* successor : GetSuccessors()) {
1320 new_block->successors_.push_back(successor);
1321 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001322 }
Vladimir Marko60584552015-09-03 13:35:12 +00001323 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001324 AddSuccessor(new_block);
1325
David Brazdil56e1acc2015-06-30 15:41:36 +01001326 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001327 return new_block;
1328}
1329
David Brazdild7558da2015-09-22 13:04:14 +01001330HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001331 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001332 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1333
1334 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1335
1336 for (HBasicBlock* predecessor : GetPredecessors()) {
1337 new_block->predecessors_.push_back(predecessor);
1338 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1339 }
1340 predecessors_.clear();
1341 AddPredecessor(new_block);
1342
1343 GetGraph()->AddBlock(new_block);
1344 return new_block;
1345}
1346
David Brazdil9bc43612015-11-05 21:25:24 +00001347HBasicBlock* HBasicBlock::SplitCatchBlockAfterMoveException() {
1348 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
1349 DCHECK(IsCatchBlock()) << "This method is intended for catch blocks only.";
1350
1351 HInstruction* first_insn = GetFirstInstruction();
1352 HInstruction* split_before = nullptr;
1353
1354 if (first_insn != nullptr && first_insn->IsLoadException()) {
1355 // Catch block starts with a LoadException. Split the block after
1356 // the StoreLocal and ClearException which must come after the load.
1357 DCHECK(first_insn->GetNext()->IsStoreLocal());
1358 DCHECK(first_insn->GetNext()->GetNext()->IsClearException());
1359 split_before = first_insn->GetNext()->GetNext()->GetNext();
1360 } else {
1361 // Catch block does not load the exception. Split at the beginning
1362 // to create an empty catch block.
1363 split_before = first_insn;
1364 }
1365
1366 if (split_before == nullptr) {
1367 // Catch block has no instructions after the split point (must be dead).
1368 // Do not split it but rather signal error by returning nullptr.
1369 return nullptr;
1370 } else {
1371 return SplitBefore(split_before);
1372 }
1373}
1374
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001375HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1376 DCHECK(!cursor->IsControlFlow());
1377 DCHECK_NE(instructions_.last_instruction_, cursor);
1378 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001379
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001380 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1381 new_block->instructions_.first_instruction_ = cursor->GetNext();
1382 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1383 cursor->next_->previous_ = nullptr;
1384 cursor->next_ = nullptr;
1385 instructions_.last_instruction_ = cursor;
1386
1387 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001388 for (HBasicBlock* successor : GetSuccessors()) {
1389 new_block->successors_.push_back(successor);
1390 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001391 }
Vladimir Marko60584552015-09-03 13:35:12 +00001392 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001393
Vladimir Marko60584552015-09-03 13:35:12 +00001394 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001395 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001396 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001397 }
Vladimir Marko60584552015-09-03 13:35:12 +00001398 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001399 return new_block;
1400}
1401
David Brazdilec16f792015-08-19 15:04:01 +01001402const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001403 if (EndsWithTryBoundary()) {
1404 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1405 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001406 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001407 return try_boundary;
1408 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001409 DCHECK(IsTryBlock());
1410 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001411 return nullptr;
1412 }
David Brazdilec16f792015-08-19 15:04:01 +01001413 } else if (IsTryBlock()) {
1414 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001415 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001416 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001417 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001418}
1419
David Brazdild7558da2015-09-22 13:04:14 +01001420bool HBasicBlock::HasThrowingInstructions() const {
1421 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1422 if (it.Current()->CanThrow()) {
1423 return true;
1424 }
1425 }
1426 return false;
1427}
1428
David Brazdilfc6a86a2015-06-26 10:33:45 +00001429static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1430 return block.GetPhis().IsEmpty()
1431 && !block.GetInstructions().IsEmpty()
1432 && block.GetFirstInstruction() == block.GetLastInstruction();
1433}
1434
David Brazdil46e2a392015-03-16 17:31:52 +00001435bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001436 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1437}
1438
1439bool HBasicBlock::IsSingleTryBoundary() const {
1440 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001441}
1442
David Brazdil8d5b8b22015-03-24 10:51:52 +00001443bool HBasicBlock::EndsWithControlFlowInstruction() const {
1444 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1445}
1446
David Brazdilb2bd1c52015-03-25 11:17:37 +00001447bool HBasicBlock::EndsWithIf() const {
1448 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1449}
1450
David Brazdilffee3d32015-07-06 11:48:53 +01001451bool HBasicBlock::EndsWithTryBoundary() const {
1452 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1453}
1454
David Brazdilb2bd1c52015-03-25 11:17:37 +00001455bool HBasicBlock::HasSinglePhi() const {
1456 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1457}
1458
David Brazdild26a4112015-11-10 11:07:31 +00001459ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1460 if (EndsWithTryBoundary()) {
1461 // The normal-flow successor of HTryBoundary is always stored at index zero.
1462 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1463 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1464 } else {
1465 // All successors of blocks not ending with TryBoundary are normal.
1466 return ArrayRef<HBasicBlock* const>(successors_);
1467 }
1468}
1469
1470ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1471 if (EndsWithTryBoundary()) {
1472 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1473 } else {
1474 // Blocks not ending with TryBoundary do not have exceptional successors.
1475 return ArrayRef<HBasicBlock* const>();
1476 }
1477}
1478
David Brazdilffee3d32015-07-06 11:48:53 +01001479bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001480 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1481 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1482
1483 size_t length = handlers1.size();
1484 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001485 return false;
1486 }
1487
David Brazdilb618ade2015-07-29 10:31:29 +01001488 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001489 for (size_t i = 0; i < length; ++i) {
1490 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001491 return false;
1492 }
1493 }
1494 return true;
1495}
1496
David Brazdil2d7352b2015-04-20 14:52:42 +01001497size_t HInstructionList::CountSize() const {
1498 size_t size = 0;
1499 HInstruction* current = first_instruction_;
1500 for (; current != nullptr; current = current->GetNext()) {
1501 size++;
1502 }
1503 return size;
1504}
1505
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001506void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1507 for (HInstruction* current = first_instruction_;
1508 current != nullptr;
1509 current = current->GetNext()) {
1510 current->SetBlock(block);
1511 }
1512}
1513
1514void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1515 DCHECK(Contains(cursor));
1516 if (!instruction_list.IsEmpty()) {
1517 if (cursor == last_instruction_) {
1518 last_instruction_ = instruction_list.last_instruction_;
1519 } else {
1520 cursor->next_->previous_ = instruction_list.last_instruction_;
1521 }
1522 instruction_list.last_instruction_->next_ = cursor->next_;
1523 cursor->next_ = instruction_list.first_instruction_;
1524 instruction_list.first_instruction_->previous_ = cursor;
1525 }
1526}
1527
1528void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001529 if (IsEmpty()) {
1530 first_instruction_ = instruction_list.first_instruction_;
1531 last_instruction_ = instruction_list.last_instruction_;
1532 } else {
1533 AddAfter(last_instruction_, instruction_list);
1534 }
1535}
1536
David Brazdil04ff4e82015-12-10 13:54:52 +00001537// Should be called on instructions in a dead block in post order. This method
1538// assumes `insn` has been removed from all users with the exception of catch
1539// phis because of missing exceptional edges in the graph. It removes the
1540// instruction from catch phi uses, together with inputs of other catch phis in
1541// the catch block at the same index, as these must be dead too.
1542static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1543 DCHECK(!insn->HasEnvironmentUses());
1544 while (insn->HasNonEnvironmentUses()) {
1545 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1546 size_t use_index = use->GetIndex();
1547 HBasicBlock* user_block = use->GetUser()->GetBlock();
1548 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1549 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1550 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1551 }
1552 }
1553}
1554
David Brazdil2d7352b2015-04-20 14:52:42 +01001555void HBasicBlock::DisconnectAndDelete() {
1556 // Dominators must be removed after all the blocks they dominate. This way
1557 // a loop header is removed last, a requirement for correct loop information
1558 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001559 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001560
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001561 // (1) Remove the block from all loops it is included in.
David Brazdil2d7352b2015-04-20 14:52:42 +01001562 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1563 HLoopInformation* loop_info = it.Current();
1564 loop_info->Remove(this);
1565 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001566 // If this was the last back edge of the loop, we deliberately leave the
1567 // loop in an inconsistent state and will fail SSAChecker unless the
1568 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001569 loop_info->RemoveBackEdge(this);
1570 }
1571 }
1572
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001573 // (2) Disconnect the block from its predecessors and update their
1574 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001575 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001576 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001577 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1578 // This block is the only normal-flow successor of the TryBoundary which
1579 // makes `predecessor` dead. Since DCE removes blocks in post order,
1580 // exception handlers of this TryBoundary were already visited and any
1581 // remaining handlers therefore must be live. We remove `predecessor` from
1582 // their list of predecessors.
1583 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1584 while (predecessor->GetSuccessors().size() > 1) {
1585 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1586 DCHECK(handler->IsCatchBlock());
1587 predecessor->RemoveSuccessor(handler);
1588 handler->RemovePredecessor(predecessor);
1589 }
1590 }
1591
David Brazdil2d7352b2015-04-20 14:52:42 +01001592 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001593 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1594 if (num_pred_successors == 1u) {
1595 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001596 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1597 // successor. Replace those with a HGoto.
1598 DCHECK(last_instruction->IsIf() ||
1599 last_instruction->IsPackedSwitch() ||
1600 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001601 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001602 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001603 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001604 // The predecessor has no remaining successors and therefore must be dead.
1605 // We deliberately leave it without a control-flow instruction so that the
1606 // SSAChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001607 predecessor->RemoveInstruction(last_instruction);
1608 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001609 // There are multiple successors left. The removed block might be a successor
1610 // of a PackedSwitch which will be completely removed (perhaps replaced with
1611 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1612 // case, leave `last_instruction` as is for now.
1613 DCHECK(last_instruction->IsPackedSwitch() ||
1614 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001615 }
David Brazdil46e2a392015-03-16 17:31:52 +00001616 }
Vladimir Marko60584552015-09-03 13:35:12 +00001617 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001618
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001619 // (3) Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001620 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001621 // Delete this block from the list of predecessors.
1622 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001623 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001624
1625 // Check that `successor` has other predecessors, otherwise `this` is the
1626 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001627 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001628
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001629 // Remove this block's entries in the successor's phis. Skip exceptional
1630 // successors because catch phi inputs do not correspond to predecessor
1631 // blocks but throwing instructions. Their inputs will be updated in step (4).
1632 if (!successor->IsCatchBlock()) {
1633 if (successor->predecessors_.size() == 1u) {
1634 // The successor has just one predecessor left. Replace phis with the only
1635 // remaining input.
1636 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1637 HPhi* phi = phi_it.Current()->AsPhi();
1638 phi->ReplaceWith(phi->InputAt(1 - this_index));
1639 successor->RemovePhi(phi);
1640 }
1641 } else {
1642 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1643 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1644 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001645 }
1646 }
1647 }
Vladimir Marko60584552015-09-03 13:35:12 +00001648 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001649
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001650 // (4) Remove instructions and phis. Instructions should have no remaining uses
1651 // except in catch phis. If an instruction is used by a catch phi at `index`,
1652 // remove `index`-th input of all phis in the catch block since they are
1653 // guaranteed dead. Note that we may miss dead inputs this way but the
1654 // graph will always remain consistent.
1655 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1656 HInstruction* insn = it.Current();
David Brazdil04ff4e82015-12-10 13:54:52 +00001657 RemoveUsesOfDeadInstruction(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001658 RemoveInstruction(insn);
1659 }
1660 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
David Brazdil04ff4e82015-12-10 13:54:52 +00001661 HPhi* insn = it.Current()->AsPhi();
1662 RemoveUsesOfDeadInstruction(insn);
1663 RemovePhi(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001664 }
1665
David Brazdil2d7352b2015-04-20 14:52:42 +01001666 // Disconnect from the dominator.
1667 dominator_->RemoveDominatedBlock(this);
1668 SetDominator(nullptr);
1669
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001670 // Delete from the graph, update reverse post order.
1671 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001672 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001673}
1674
1675void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001676 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001677 DCHECK(ContainsElement(dominated_blocks_, other));
1678 DCHECK_EQ(GetSingleSuccessor(), other);
1679 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001680 DCHECK(other->GetPhis().IsEmpty());
1681
David Brazdil2d7352b2015-04-20 14:52:42 +01001682 // Move instructions from `other` to `this`.
1683 DCHECK(EndsWithControlFlowInstruction());
1684 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001685 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001686 other->instructions_.SetBlockOfInstructions(this);
1687 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001688
David Brazdil2d7352b2015-04-20 14:52:42 +01001689 // Remove `other` from the loops it is included in.
1690 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1691 HLoopInformation* loop_info = it.Current();
1692 loop_info->Remove(other);
1693 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001694 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001695 }
1696 }
1697
1698 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001699 successors_.clear();
1700 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001701 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001702 successor->ReplacePredecessor(other, this);
1703 }
1704
David Brazdil2d7352b2015-04-20 14:52:42 +01001705 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001706 RemoveDominatedBlock(other);
1707 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1708 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001709 dominated->SetDominator(this);
1710 }
Vladimir Marko60584552015-09-03 13:35:12 +00001711 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001712 other->dominator_ = nullptr;
1713
1714 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001715 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001716
1717 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001718 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001719 other->SetGraph(nullptr);
1720}
1721
1722void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1723 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001724 DCHECK(GetDominatedBlocks().empty());
1725 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001726 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001727 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001728 DCHECK(other->GetPhis().IsEmpty());
1729 DCHECK(!other->IsInLoop());
1730
1731 // Move instructions from `other` to `this`.
1732 instructions_.Add(other->GetInstructions());
1733 other->instructions_.SetBlockOfInstructions(this);
1734
1735 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001736 successors_.clear();
1737 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001738 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001739 successor->ReplacePredecessor(other, this);
1740 }
1741
1742 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001743 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1744 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001745 dominated->SetDominator(this);
1746 }
Vladimir Marko60584552015-09-03 13:35:12 +00001747 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001748 other->dominator_ = nullptr;
1749 other->graph_ = nullptr;
1750}
1751
1752void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001753 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001754 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001755 predecessor->ReplaceSuccessor(this, other);
1756 }
Vladimir Marko60584552015-09-03 13:35:12 +00001757 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001758 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001759 successor->ReplacePredecessor(this, other);
1760 }
Vladimir Marko60584552015-09-03 13:35:12 +00001761 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1762 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001763 }
1764 GetDominator()->ReplaceDominatedBlock(this, other);
1765 other->SetDominator(GetDominator());
1766 dominator_ = nullptr;
1767 graph_ = nullptr;
1768}
1769
1770// Create space in `blocks` for adding `number_of_new_blocks` entries
1771// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001772static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001773 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001774 size_t after) {
1775 DCHECK_LT(after, blocks->size());
1776 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001777 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001778 blocks->resize(new_size);
1779 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001780}
1781
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001782void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001783 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001784 DCHECK(block->GetSuccessors().empty());
1785 DCHECK(block->GetPredecessors().empty());
1786 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001787 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001788 DCHECK(block->GetInstructions().IsEmpty());
1789 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001790
David Brazdilc7af85d2015-05-26 12:05:55 +01001791 if (block->IsExitBlock()) {
1792 exit_block_ = nullptr;
1793 }
1794
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001795 RemoveElement(reverse_post_order_, block);
1796 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001797}
1798
Calin Juravle2e768302015-07-28 14:41:11 +00001799HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001800 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001801 // Update the environments in this graph to have the invoke's environment
1802 // as parent.
1803 {
1804 HReversePostOrderIterator it(*this);
1805 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1806 for (; !it.Done(); it.Advance()) {
1807 HBasicBlock* block = it.Current();
1808 for (HInstructionIterator instr_it(block->GetInstructions());
1809 !instr_it.Done();
1810 instr_it.Advance()) {
1811 HInstruction* current = instr_it.Current();
1812 if (current->NeedsEnvironment()) {
1813 current->GetEnvironment()->SetAndCopyParentChain(
1814 outer_graph->GetArena(), invoke->GetEnvironment());
1815 }
1816 }
1817 }
1818 }
1819 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1820 if (HasBoundsChecks()) {
1821 outer_graph->SetHasBoundsChecks(true);
1822 }
1823
Calin Juravle2e768302015-07-28 14:41:11 +00001824 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001825 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001826 // Simple case of an entry block, a body block, and an exit block.
1827 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001828 HBasicBlock* body = GetBlocks()[1];
1829 DCHECK(GetBlocks()[0]->IsEntryBlock());
1830 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001831 DCHECK(!body->IsExitBlock());
1832 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001833
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001834 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1835 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001836
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001837 // Replace the invoke with the return value of the inlined graph.
1838 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001839 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001840 } else {
1841 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001842 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001843
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001844 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001845 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001846 // Need to inline multiple blocks. We split `invoke`'s block
1847 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001848 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001849 // with the second half.
1850 ArenaAllocator* allocator = outer_graph->GetArena();
1851 HBasicBlock* at = invoke->GetBlock();
1852 HBasicBlock* to = at->SplitAfter(invoke);
1853
Vladimir Markoec7802a2015-10-01 20:57:57 +01001854 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001855 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001856 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001857 exit_block_->ReplaceWith(to);
1858
1859 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001860 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001861 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001862 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001863 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001864 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001865 if (!returns_void) {
1866 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001867 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001868 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001869 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001870 } else {
1871 if (!returns_void) {
1872 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001873 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001874 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001875 to->AddPhi(return_value->AsPhi());
1876 }
Vladimir Marko60584552015-09-03 13:35:12 +00001877 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001878 HInstruction* last = predecessor->GetLastInstruction();
1879 if (!returns_void) {
1880 return_value->AsPhi()->AddInput(last->InputAt(0));
1881 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001882 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001883 predecessor->RemoveInstruction(last);
1884 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001885 }
1886
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001887 // Update the meta information surrounding blocks:
1888 // (1) the graph they are now in,
1889 // (2) the reverse post order of that graph,
David Brazdil95177982015-10-30 12:56:58 -05001890 // (3) the potential loop information they are now in,
1891 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001892 // Note that we do not need to update catch phi inputs because they
1893 // correspond to the register file of the outer method which the inlinee
1894 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001895
1896 // We don't add the entry block, the exit block, and the first block, which
1897 // has been merged with `at`.
1898 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1899
1900 // We add the `to` block.
1901 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001902 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001903 + kNumberOfNewBlocksInCaller;
1904
1905 // Find the location of `at` in the outer graph's reverse post order. The new
1906 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001907 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001908 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1909
David Brazdil95177982015-10-30 12:56:58 -05001910 HLoopInformation* loop_info = at->GetLoopInformation();
1911 // Copy TryCatchInformation if `at` is a try block, not if it is a catch block.
1912 TryCatchInformation* try_catch_info = at->IsTryBlock() ? at->GetTryCatchInformation() : nullptr;
1913
1914 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1915 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001916 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1917 HBasicBlock* current = it.Current();
1918 if (current != exit_block_ && current != entry_block_ && current != first) {
1919 DCHECK(!current->IsInLoop());
David Brazdil95177982015-10-30 12:56:58 -05001920 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001921 DCHECK(current->GetGraph() == this);
1922 current->SetGraph(outer_graph);
1923 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001924 outer_graph->reverse_post_order_[++index_of_at] = current;
David Brazdil95177982015-10-30 12:56:58 -05001925 if (loop_info != nullptr) {
1926 current->SetLoopInformation(loop_info);
David Brazdil7d275372015-04-21 16:36:35 +01001927 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1928 loop_it.Current()->Add(current);
1929 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001930 }
David Brazdil95177982015-10-30 12:56:58 -05001931 current->SetTryCatchInformation(try_catch_info);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001932 }
1933 }
1934
David Brazdil95177982015-10-30 12:56:58 -05001935 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001936 to->SetGraph(outer_graph);
1937 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001938 outer_graph->reverse_post_order_[++index_of_at] = to;
David Brazdil95177982015-10-30 12:56:58 -05001939 if (loop_info != nullptr) {
1940 to->SetLoopInformation(loop_info);
David Brazdil7d275372015-04-21 16:36:35 +01001941 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1942 loop_it.Current()->Add(to);
1943 }
David Brazdil95177982015-10-30 12:56:58 -05001944 if (loop_info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001945 // Only `to` can become a back edge, as the inlined blocks
1946 // are predecessors of `to`.
David Brazdil95177982015-10-30 12:56:58 -05001947 loop_info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001948 }
1949 }
David Brazdil95177982015-10-30 12:56:58 -05001950 to->SetTryCatchInformation(try_catch_info);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001951 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001952
David Brazdil05144f42015-04-16 15:18:00 +01001953 // Update the next instruction id of the outer graph, so that instructions
1954 // added later get bigger ids than those in the inner graph.
1955 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1956
1957 // Walk over the entry block and:
1958 // - Move constants from the entry block to the outer_graph's entry block,
1959 // - Replace HParameterValue instructions with their real value.
1960 // - Remove suspend checks, that hold an environment.
1961 // We must do this after the other blocks have been inlined, otherwise ids of
1962 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001963 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001964 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1965 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01001966 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01001967 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001968 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001969 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001970 replacement = outer_graph->GetIntConstant(
1971 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001972 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001973 replacement = outer_graph->GetLongConstant(
1974 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001975 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001976 replacement = outer_graph->GetFloatConstant(
1977 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001978 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001979 replacement = outer_graph->GetDoubleConstant(
1980 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01001981 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001982 if (kIsDebugBuild
1983 && invoke->IsInvokeStaticOrDirect()
1984 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1985 // Ensure we do not use the last input of `invoke`, as it
1986 // contains a clinit check which is not an actual argument.
1987 size_t last_input_index = invoke->InputCount() - 1;
1988 DCHECK(parameter_index != last_input_index);
1989 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01001990 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001991 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01001992 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01001993 } else {
1994 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1995 entry_block_->RemoveInstruction(current);
1996 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01001997 if (replacement != nullptr) {
1998 current->ReplaceWith(replacement);
1999 // If the current is the return value then we need to update the latter.
2000 if (current == return_value) {
2001 DCHECK_EQ(entry_block_, return_value->GetBlock());
2002 return_value = replacement;
2003 }
2004 }
2005 }
2006
2007 if (return_value != nullptr) {
2008 invoke->ReplaceWith(return_value);
David Brazdil05144f42015-04-16 15:18:00 +01002009 }
2010
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002011 // Finally remove the invoke from the caller.
2012 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00002013
2014 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002015}
2016
Mingyao Yang3584bce2015-05-19 16:01:59 -07002017/*
2018 * Loop will be transformed to:
2019 * old_pre_header
2020 * |
2021 * if_block
2022 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002023 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002024 * \ /
2025 * new_pre_header
2026 * |
2027 * header
2028 */
2029void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2030 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002031 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002032
Aart Bik3fc7f352015-11-20 22:03:03 -08002033 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002034 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002035 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2036 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002037 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2038 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002039 AddBlock(true_block);
2040 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002041 AddBlock(new_pre_header);
2042
Aart Bik3fc7f352015-11-20 22:03:03 -08002043 header->ReplacePredecessor(old_pre_header, new_pre_header);
2044 old_pre_header->successors_.clear();
2045 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002046
Aart Bik3fc7f352015-11-20 22:03:03 -08002047 old_pre_header->AddSuccessor(if_block);
2048 if_block->AddSuccessor(true_block); // True successor
2049 if_block->AddSuccessor(false_block); // False successor
2050 true_block->AddSuccessor(new_pre_header);
2051 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002052
Aart Bik3fc7f352015-11-20 22:03:03 -08002053 old_pre_header->dominated_blocks_.push_back(if_block);
2054 if_block->SetDominator(old_pre_header);
2055 if_block->dominated_blocks_.push_back(true_block);
2056 true_block->SetDominator(if_block);
2057 if_block->dominated_blocks_.push_back(false_block);
2058 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002059 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002060 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002061 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002062 header->SetDominator(new_pre_header);
2063
Aart Bik3fc7f352015-11-20 22:03:03 -08002064 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002065 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002066 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002067 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002068 reverse_post_order_[index_of_header++] = true_block;
2069 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002070 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002071
Aart Bik3fc7f352015-11-20 22:03:03 -08002072 // Fix loop information.
2073 HLoopInformation* loop_info = old_pre_header->GetLoopInformation();
2074 if (loop_info != nullptr) {
2075 if_block->SetLoopInformation(loop_info);
2076 true_block->SetLoopInformation(loop_info);
2077 false_block->SetLoopInformation(loop_info);
2078 new_pre_header->SetLoopInformation(loop_info);
2079 // Add blocks to all enveloping loops.
2080 for (HLoopInformationOutwardIterator loop_it(*old_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002081 !loop_it.Done();
2082 loop_it.Advance()) {
2083 loop_it.Current()->Add(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002084 loop_it.Current()->Add(true_block);
2085 loop_it.Current()->Add(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002086 loop_it.Current()->Add(new_pre_header);
2087 }
2088 }
Aart Bik3fc7f352015-11-20 22:03:03 -08002089
2090 // Fix try/catch information.
2091 TryCatchInformation* try_catch_info = old_pre_header->IsTryBlock()
2092 ? old_pre_header->GetTryCatchInformation()
2093 : nullptr;
2094 if_block->SetTryCatchInformation(try_catch_info);
2095 true_block->SetTryCatchInformation(try_catch_info);
2096 false_block->SetTryCatchInformation(try_catch_info);
2097 new_pre_header->SetTryCatchInformation(try_catch_info);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002098}
2099
David Brazdilf5552582015-12-27 13:36:12 +00002100static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2101 SHARED_REQUIRES(Locks::mutator_lock_) {
2102 if (rti.IsValid()) {
2103 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2104 << " upper_bound_rti: " << upper_bound_rti
2105 << " rti: " << rti;
2106 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
2107 }
2108}
2109
Calin Juravle2e768302015-07-28 14:41:11 +00002110void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2111 if (kIsDebugBuild) {
2112 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2113 ScopedObjectAccess soa(Thread::Current());
2114 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2115 if (IsBoundType()) {
2116 // Having the test here spares us from making the method virtual just for
2117 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002118 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002119 }
2120 }
2121 reference_type_info_ = rti;
2122}
2123
David Brazdilf5552582015-12-27 13:36:12 +00002124void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2125 if (kIsDebugBuild) {
2126 ScopedObjectAccess soa(Thread::Current());
2127 DCHECK(upper_bound.IsValid());
2128 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2129 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2130 }
2131 upper_bound_ = upper_bound;
2132 upper_can_be_null_ = can_be_null;
2133}
2134
Calin Juravle2e768302015-07-28 14:41:11 +00002135ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
2136
2137ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
2138 : type_handle_(type_handle), is_exact_(is_exact) {
2139 if (kIsDebugBuild) {
2140 ScopedObjectAccess soa(Thread::Current());
2141 DCHECK(IsValidHandle(type_handle));
2142 }
2143}
2144
Calin Juravleacf735c2015-02-12 15:25:22 +00002145std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2146 ScopedObjectAccess soa(Thread::Current());
2147 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002148 << " is_valid=" << rhs.IsValid()
2149 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002150 << " is_exact=" << rhs.IsExact()
2151 << " ]";
2152 return os;
2153}
2154
Mark Mendellc4701932015-04-10 13:18:51 -04002155bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2156 // For now, assume that instructions in different blocks may use the
2157 // environment.
2158 // TODO: Use the control flow to decide if this is true.
2159 if (GetBlock() != other->GetBlock()) {
2160 return true;
2161 }
2162
2163 // We know that we are in the same block. Walk from 'this' to 'other',
2164 // checking to see if there is any instruction with an environment.
2165 HInstruction* current = this;
2166 for (; current != other && current != nullptr; current = current->GetNext()) {
2167 // This is a conservative check, as the instruction result may not be in
2168 // the referenced environment.
2169 if (current->HasEnvironment()) {
2170 return true;
2171 }
2172 }
2173
2174 // We should have been called with 'this' before 'other' in the block.
2175 // Just confirm this.
2176 DCHECK(current != nullptr);
2177 return false;
2178}
2179
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002180void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002181 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2182 IntrinsicSideEffects side_effects,
2183 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002184 intrinsic_ = intrinsic;
2185 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002186
Aart Bik5d75afe2015-12-14 11:57:01 -08002187 // Adjust method's side effects from intrinsic table.
2188 switch (side_effects) {
2189 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2190 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2191 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2192 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2193 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002194
2195 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2196 opt.SetDoesNotNeedDexCache();
2197 opt.SetDoesNotNeedEnvironment();
2198 } else {
2199 // If we need an environment, that means there will be a call, which can trigger GC.
2200 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2201 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002202 // Adjust method's exception status from intrinsic table.
2203 switch (exceptions) {
2204 case kNoThrow: SetCanThrow(false); break;
2205 case kCanThrow: SetCanThrow(true); break;
2206 }
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002207}
2208
David Brazdil6de19382016-01-08 17:37:10 +00002209bool HNewInstance::IsStringAlloc() const {
2210 ScopedObjectAccess soa(Thread::Current());
2211 return GetReferenceTypeInfo().IsStringClass();
2212}
2213
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002214bool HInvoke::NeedsEnvironment() const {
2215 if (!IsIntrinsic()) {
2216 return true;
2217 }
2218 IntrinsicOptimizations opt(*this);
2219 return !opt.GetDoesNotNeedEnvironment();
2220}
2221
Vladimir Markodc151b22015-10-15 18:02:30 +01002222bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2223 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002224 return false;
2225 }
2226 if (!IsIntrinsic()) {
2227 return true;
2228 }
2229 IntrinsicOptimizations opt(*this);
2230 return !opt.GetDoesNotNeedDexCache();
2231}
2232
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002233void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2234 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2235 input->AddUseAt(this, index);
2236 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2237 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2238 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2239 InputRecordAt(i).GetUseNode()->SetIndex(i);
2240 }
2241}
2242
Vladimir Markob554b5a2015-11-06 12:57:55 +00002243void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2244 RemoveAsUserOfInput(index);
2245 inputs_.erase(inputs_.begin() + index);
2246 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2247 for (size_t i = index, e = InputCount(); i < e; ++i) {
2248 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2249 InputRecordAt(i).GetUseNode()->SetIndex(i);
2250 }
2251}
2252
Vladimir Markof64242a2015-12-01 14:58:23 +00002253std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2254 switch (rhs) {
2255 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2256 return os << "string_init";
2257 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2258 return os << "recursive";
2259 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2260 return os << "direct";
2261 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2262 return os << "direct_fixup";
2263 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2264 return os << "dex_cache_pc_relative";
2265 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2266 return os << "dex_cache_via_method";
2267 default:
2268 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2269 UNREACHABLE();
2270 }
2271}
2272
Vladimir Markofbb184a2015-11-13 14:47:00 +00002273std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2274 switch (rhs) {
2275 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2276 return os << "explicit";
2277 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2278 return os << "implicit";
2279 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2280 return os << "none";
2281 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002282 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2283 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002284 }
2285}
2286
Mark Mendellc4701932015-04-10 13:18:51 -04002287void HInstruction::RemoveEnvironmentUsers() {
2288 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2289 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2290 HEnvironment* user = user_node->GetUser();
2291 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2292 }
2293 env_uses_.Clear();
2294}
2295
Mark Mendellf6529172015-11-17 11:16:56 -05002296// Returns an instruction with the opposite boolean value from 'cond'.
2297HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2298 ArenaAllocator* allocator = GetArena();
2299
2300 if (cond->IsCondition() &&
2301 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2302 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2303 HInstruction* lhs = cond->InputAt(0);
2304 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002305 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002306 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2307 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2308 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2309 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2310 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2311 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2312 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2313 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2314 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2315 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2316 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002317 default:
2318 LOG(FATAL) << "Unexpected condition";
2319 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002320 }
2321 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2322 return replacement;
2323 } else if (cond->IsIntConstant()) {
2324 HIntConstant* int_const = cond->AsIntConstant();
2325 if (int_const->IsZero()) {
2326 return GetIntConstant(1);
2327 } else {
2328 DCHECK(int_const->IsOne());
2329 return GetIntConstant(0);
2330 }
2331 } else {
2332 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2333 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2334 return replacement;
2335 }
2336}
2337
Roland Levillainc9285912015-12-18 10:38:42 +00002338std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2339 os << "["
2340 << " source=" << rhs.GetSource()
2341 << " destination=" << rhs.GetDestination()
2342 << " type=" << rhs.GetType()
2343 << " instruction=";
2344 if (rhs.GetInstruction() != nullptr) {
2345 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2346 } else {
2347 os << "null";
2348 }
2349 os << " ]";
2350 return os;
2351}
2352
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002353} // namespace art