blob: 3dda8501d297f144120de69480b44f2ba409dc7a [file] [log] [blame]
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Nicolas Geoffray818f2102014-02-18 16:43:35 +000016#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000017
Mark Mendelle82549b2015-05-06 10:55:34 -040018#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000019#include "common_dominator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010020#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010021#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010022#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010023#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010024#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010025#include "mirror/class-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000026#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000027
28namespace art {
29
30void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010031 block->SetBlockId(blocks_.size());
32 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000033}
34
Nicolas Geoffray804d0932014-05-02 08:46:00 +010035void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010036 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
37 DCHECK_EQ(visited->GetHighestBitSet(), -1);
38
39 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markofa6b93c2015-09-15 10:15:55 +010040 ArenaBitVector visiting(arena_, blocks_.size(), false);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010041 // Number of successors visited from a given node, indexed by block id.
42 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
43 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
44 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
45 constexpr size_t kDefaultWorklistSize = 8;
46 worklist.reserve(kDefaultWorklistSize);
47 visited->SetBit(entry_block_->GetBlockId());
48 visiting.SetBit(entry_block_->GetBlockId());
49 worklist.push_back(entry_block_);
50
51 while (!worklist.empty()) {
52 HBasicBlock* current = worklist.back();
53 uint32_t current_id = current->GetBlockId();
54 if (successors_visited[current_id] == current->GetSuccessors().size()) {
55 visiting.ClearBit(current_id);
56 worklist.pop_back();
57 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010058 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
59 uint32_t successor_id = successor->GetBlockId();
60 if (visiting.IsBitSet(successor_id)) {
61 DCHECK(ContainsElement(worklist, successor));
62 successor->AddBackEdge(current);
63 } else if (!visited->IsBitSet(successor_id)) {
64 visited->SetBit(successor_id);
65 visiting.SetBit(successor_id);
66 worklist.push_back(successor);
67 }
68 }
69 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000070}
71
Roland Levillainfc600dc2014-12-02 17:16:31 +000072static void RemoveAsUser(HInstruction* instruction) {
73 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000074 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000075 }
76
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010077 for (HEnvironment* environment = instruction->GetEnvironment();
78 environment != nullptr;
79 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000080 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000081 if (environment->GetInstructionAt(i) != nullptr) {
82 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000083 }
84 }
85 }
86}
87
88void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010089 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000090 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010091 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +000092 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010093 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000094 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
95 RemoveAsUser(it.Current());
96 }
97 }
98 }
99}
100
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100101void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100102 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000103 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100104 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000105 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100106 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000107 for (HBasicBlock* successor : block->GetSuccessors()) {
108 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000109 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100110 // Remove the block from the list of blocks, so that further analyses
111 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100112 blocks_[i] = nullptr;
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000113 }
114 }
115}
116
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000117GraphAnalysisResult HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100118 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
119 // edges. This invariant simplifies building SSA form because Phis cannot
120 // collect both normal- and exceptional-flow values at the same time.
121 SimplifyCatchBlocks();
122
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100123 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000124
David Brazdilffee3d32015-07-06 11:48:53 +0100125 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000126 FindBackEdges(&visited);
127
David Brazdilffee3d32015-07-06 11:48:53 +0100128 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000129 // the initial DFS as users from other instructions, so that
130 // users can be safely removed before uses later.
131 RemoveInstructionsAsUsersFromDeadBlocks(visited);
132
David Brazdilffee3d32015-07-06 11:48:53 +0100133 // (4) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000134 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000135 // predecessors list of live blocks.
136 RemoveDeadBlocks(visited);
137
David Brazdilffee3d32015-07-06 11:48:53 +0100138 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100139 // dominators and the reverse post order.
140 SimplifyCFG();
141
David Brazdilffee3d32015-07-06 11:48:53 +0100142 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100143 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000144
145 // (7) Analyze loops discover through back edge analysis, and
146 // set the loop information on each block.
147 GraphAnalysisResult result = AnalyzeLoops();
148 if (result != kAnalysisSuccess) {
149 return result;
150 }
151
152 // (8) Precompute per-block try membership before entering the SSA builder,
153 // which needs the information to build catch block phis from values of
154 // locals at throwing instructions inside try blocks.
155 ComputeTryBlockInformation();
156
157 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100158}
159
160void HGraph::ClearDominanceInformation() {
161 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
162 it.Current()->ClearDominanceInformation();
163 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100164 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100165}
166
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000167void HGraph::ClearLoopInformation() {
168 SetHasIrreducibleLoops(false);
169 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000170 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000171 }
172}
173
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100174void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000175 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100176 dominator_ = nullptr;
177}
178
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000179HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
180 HInstruction* instruction = GetFirstInstruction();
181 while (instruction->IsParallelMove()) {
182 instruction = instruction->GetNext();
183 }
184 return instruction;
185}
186
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100187void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100188 DCHECK(reverse_post_order_.empty());
189 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100190 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100191
192 // Number of visits of a given node, indexed by block id.
193 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
194 // Number of successors visited from a given node, indexed by block id.
195 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
196 // Nodes for which we need to visit successors.
197 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
198 constexpr size_t kDefaultWorklistSize = 8;
199 worklist.reserve(kDefaultWorklistSize);
200 worklist.push_back(entry_block_);
201
202 while (!worklist.empty()) {
203 HBasicBlock* current = worklist.back();
204 uint32_t current_id = current->GetBlockId();
205 if (successors_visited[current_id] == current->GetSuccessors().size()) {
206 worklist.pop_back();
207 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100208 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
209
210 if (successor->GetDominator() == nullptr) {
211 successor->SetDominator(current);
212 } else {
Vladimir Marko391d01f2015-11-06 11:02:08 +0000213 // The CommonDominator can work for multiple blocks as long as the
214 // domination information doesn't change. However, since we're changing
215 // that information here, we can use the finder only for pairs of blocks.
216 successor->SetDominator(CommonDominator::ForPair(successor->GetDominator(), current));
Vladimir Markod76d1392015-09-23 16:07:14 +0100217 }
218
219 // Once all the forward edges have been visited, we know the immediate
220 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100221 if (++visits[successor->GetBlockId()] ==
222 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100223 reverse_post_order_.push_back(successor);
224 worklist.push_back(successor);
225 }
226 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000227 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000228
229 // Populate `dominated_blocks_` information after computing all dominators.
230 // The potential presence of irreducible loops require to do it after.
231 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
232 HBasicBlock* block = it.Current();
233 if (!block->IsEntryBlock()) {
234 block->GetDominator()->AddDominatedBlock(block);
235 }
236 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000237}
238
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000239GraphAnalysisResult HGraph::TryBuildingSsa(StackHandleScopeCollection* handles) {
240 GraphAnalysisResult result = BuildDominatorTree();
241 if (result != kAnalysisSuccess) {
David Brazdil4833f5a2015-12-16 10:37:39 +0000242 return result;
243 }
244
David Brazdil4833f5a2015-12-16 10:37:39 +0000245 // Create the inexact Object reference type and store it in the HGraph.
246 ScopedObjectAccess soa(Thread::Current());
247 ClassLinker* linker = Runtime::Current()->GetClassLinker();
248 inexact_object_rti_ = ReferenceTypeInfo::Create(
249 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
250 /* is_exact */ false);
251
252 // Tranforms graph to SSA form.
253 result = SsaBuilder(this, handles).BuildSsa();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000254 if (result != kAnalysisSuccess) {
David Brazdil4833f5a2015-12-16 10:37:39 +0000255 return result;
256 }
257
258 in_ssa_form_ = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000259 return kAnalysisSuccess;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100260}
261
David Brazdilfc6a86a2015-06-26 10:33:45 +0000262HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000263 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
264 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000265 // Use `InsertBetween` to ensure the predecessor index and successor index of
266 // `block` and `successor` are preserved.
267 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000268 return new_block;
269}
270
271void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
272 // Insert a new node between `block` and `successor` to split the
273 // critical edge.
274 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600275 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100276 if (successor->IsLoopHeader()) {
277 // If we split at a back edge boundary, make the new block the back edge.
278 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000279 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100280 info->RemoveBackEdge(block);
281 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100282 }
283 }
284}
285
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100286void HGraph::SimplifyLoop(HBasicBlock* header) {
287 HLoopInformation* info = header->GetLoopInformation();
288
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100289 // Make sure the loop has only one pre header. This simplifies SSA building by having
290 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000291 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
292 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000293 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000294 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100295 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100296 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600297 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100298
Vladimir Marko60584552015-09-03 13:35:12 +0000299 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100300 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100301 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100302 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100303 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100304 }
305 }
306 pre_header->AddSuccessor(header);
307 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100308
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100309 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100310 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
311 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000312 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100313 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100314 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000315 header->predecessors_[pred] = to_swap;
316 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100317 break;
318 }
319 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100320 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100321
322 // Place the suspend check at the beginning of the header, so that live registers
323 // will be known when allocating registers. Note that code generation can still
324 // generate the suspend check at the back edge, but needs to be careful with
325 // loop phi spill slots (which are not written to at back edge).
326 HInstruction* first_instruction = header->GetFirstInstruction();
327 if (!first_instruction->IsSuspendCheck()) {
328 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
329 header->InsertInstructionBefore(check, first_instruction);
330 first_instruction = check;
331 }
332 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100333}
334
David Brazdilffee3d32015-07-06 11:48:53 +0100335static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100336 HBasicBlock* predecessor = block.GetPredecessors()[pred_idx];
David Brazdilffee3d32015-07-06 11:48:53 +0100337 if (!predecessor->EndsWithTryBoundary()) {
338 // Only edges from HTryBoundary can be exceptional.
339 return false;
340 }
341 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
342 if (try_boundary->GetNormalFlowSuccessor() == &block) {
343 // This block is the normal-flow successor of `try_boundary`, but it could
344 // also be one of its exception handlers if catch blocks have not been
345 // simplified yet. Predecessors are unordered, so we will consider the first
346 // occurrence to be the normal edge and a possible second occurrence to be
347 // the exceptional edge.
348 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
349 } else {
350 // This is not the normal-flow successor of `try_boundary`, hence it must be
351 // one of its exception handlers.
352 DCHECK(try_boundary->HasExceptionHandler(block));
353 return true;
354 }
355}
356
357void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100358 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
359 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
360 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
361 HBasicBlock* catch_block = blocks_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000362 if (catch_block == nullptr || !catch_block->IsCatchBlock()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100363 continue;
364 }
365
366 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000367 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100368 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
369 exceptional_predecessors_only = false;
370 break;
371 }
372 }
373
374 if (!exceptional_predecessors_only) {
375 // Catch block has normal-flow predecessors and needs to be simplified.
376 // Splitting the block before its first instruction moves all its
377 // instructions into `normal_block` and links the two blocks with a Goto.
378 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
379 // leaving `catch_block` with the exceptional edges only.
David Brazdil9bc43612015-11-05 21:25:24 +0000380 //
David Brazdilffee3d32015-07-06 11:48:53 +0100381 // Note that catch blocks with normal-flow predecessors cannot begin with
David Brazdil9bc43612015-11-05 21:25:24 +0000382 // a move-exception instruction, as guaranteed by the verifier. However,
383 // trivially dead predecessors are ignored by the verifier and such code
384 // has not been removed at this stage. We therefore ignore the assumption
385 // and rely on GraphChecker to enforce it after initial DCE is run (b/25492628).
386 HBasicBlock* normal_block = catch_block->SplitCatchBlockAfterMoveException();
387 if (normal_block == nullptr) {
388 // Catch block is either empty or only contains a move-exception. It must
389 // therefore be dead and will be removed during initial DCE. Do nothing.
390 DCHECK(!catch_block->EndsWithControlFlowInstruction());
391 } else {
392 // Catch block was split. Re-link normal-flow edges to the new block.
393 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
394 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
395 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
396 --j;
397 }
David Brazdilffee3d32015-07-06 11:48:53 +0100398 }
399 }
400 }
401 }
402}
403
404void HGraph::ComputeTryBlockInformation() {
405 // Iterate in reverse post order to propagate try membership information from
406 // predecessors to their successors.
407 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
408 HBasicBlock* block = it.Current();
409 if (block->IsEntryBlock() || block->IsCatchBlock()) {
410 // Catch blocks after simplification have only exceptional predecessors
411 // and hence are never in tries.
412 continue;
413 }
414
415 // Infer try membership from the first predecessor. Having simplified loops,
416 // the first predecessor can never be a back edge and therefore it must have
417 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100418 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100419 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100420 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000421 if (try_entry != nullptr &&
422 (block->GetTryCatchInformation() == nullptr ||
423 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
424 // We are either setting try block membership for the first time or it
425 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100426 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
427 }
David Brazdilffee3d32015-07-06 11:48:53 +0100428 }
429}
430
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100431void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000432// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100433 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000434 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100435 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
436 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
437 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
438 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100439 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000440 if (block->GetSuccessors().size() > 1) {
441 // Only split normal-flow edges. We cannot split exceptional edges as they
442 // are synthesized (approximate real control flow), and we do not need to
443 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000444 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
445 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
446 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100447 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000448 if (successor == exit_block_) {
449 // Throw->TryBoundary->Exit. Special case which we do not want to split
450 // because Goto->Exit is not allowed.
451 DCHECK(block->IsSingleTryBoundary());
452 DCHECK(block->GetSinglePredecessor()->GetLastInstruction()->IsThrow());
453 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100454 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000455 // SplitCriticalEdge could have invalidated the `normal_successors`
456 // ArrayRef. We must re-acquire it.
457 normal_successors = block->GetNormalSuccessors();
458 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
459 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100460 }
461 }
462 }
463 if (block->IsLoopHeader()) {
464 SimplifyLoop(block);
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000465 } else if (!block->IsEntryBlock() && block->GetFirstInstruction()->IsSuspendCheck()) {
466 // We are being called by the dead code elimiation pass, and what used to be
467 // a loop got dismantled. Just remove the suspend check.
468 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100469 }
470 }
471}
472
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000473GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100474 // Order does not matter.
475 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
476 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100477 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100478 if (block->IsCatchBlock()) {
479 // TODO: Dealing with exceptional back edges could be tricky because
480 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000481 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100482 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000483 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100484 }
485 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000486 return kAnalysisSuccess;
487}
488
489void HLoopInformation::Dump(std::ostream& os) {
490 os << "header: " << header_->GetBlockId() << std::endl;
491 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
492 for (HBasicBlock* block : back_edges_) {
493 os << "back edge: " << block->GetBlockId() << std::endl;
494 }
495 for (HBasicBlock* block : header_->GetPredecessors()) {
496 os << "predecessor: " << block->GetBlockId() << std::endl;
497 }
498 for (uint32_t idx : blocks_.Indexes()) {
499 os << " in loop: " << idx << std::endl;
500 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100501}
502
David Brazdil8d5b8b22015-03-24 10:51:52 +0000503void HGraph::InsertConstant(HConstant* constant) {
504 // New constants are inserted before the final control-flow instruction
505 // of the graph, or at its end if called from the graph builder.
506 if (entry_block_->EndsWithControlFlowInstruction()) {
507 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000508 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000509 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000510 }
511}
512
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600513HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100514 // For simplicity, don't bother reviving the cached null constant if it is
515 // not null and not in a block. Otherwise, we need to clear the instruction
516 // id and/or any invariants the graph is assuming when adding new instructions.
517 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600518 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000519 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000520 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000521 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000522 if (kIsDebugBuild) {
523 ScopedObjectAccess soa(Thread::Current());
524 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
525 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000526 return cached_null_constant_;
527}
528
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100529HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100530 // For simplicity, don't bother reviving the cached current method if it is
531 // not null and not in a block. Otherwise, we need to clear the instruction
532 // id and/or any invariants the graph is assuming when adding new instructions.
533 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700534 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600535 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
536 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100537 if (entry_block_->GetFirstInstruction() == nullptr) {
538 entry_block_->AddInstruction(cached_current_method_);
539 } else {
540 entry_block_->InsertInstructionBefore(
541 cached_current_method_, entry_block_->GetFirstInstruction());
542 }
543 }
544 return cached_current_method_;
545}
546
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600547HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000548 switch (type) {
549 case Primitive::Type::kPrimBoolean:
550 DCHECK(IsUint<1>(value));
551 FALLTHROUGH_INTENDED;
552 case Primitive::Type::kPrimByte:
553 case Primitive::Type::kPrimChar:
554 case Primitive::Type::kPrimShort:
555 case Primitive::Type::kPrimInt:
556 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600557 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000558
559 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600560 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000561
562 default:
563 LOG(FATAL) << "Unsupported constant type";
564 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000565 }
David Brazdil46e2a392015-03-16 17:31:52 +0000566}
567
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000568void HGraph::CacheFloatConstant(HFloatConstant* constant) {
569 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
570 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
571 cached_float_constants_.Overwrite(value, constant);
572}
573
574void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
575 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
576 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
577 cached_double_constants_.Overwrite(value, constant);
578}
579
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000580void HLoopInformation::Add(HBasicBlock* block) {
581 blocks_.SetBit(block->GetBlockId());
582}
583
David Brazdil46e2a392015-03-16 17:31:52 +0000584void HLoopInformation::Remove(HBasicBlock* block) {
585 blocks_.ClearBit(block->GetBlockId());
586}
587
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100588void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
589 if (blocks_.IsBitSet(block->GetBlockId())) {
590 return;
591 }
592
593 blocks_.SetBit(block->GetBlockId());
594 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000595 for (HBasicBlock* predecessor : block->GetPredecessors()) {
596 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100597 }
598}
599
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000600void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block) {
601 if (blocks_.IsBitSet(block->GetBlockId())) {
602 return;
603 }
604
605 if (block->IsLoopHeader()) {
606 // If we hit a loop header in an irreducible loop, we first check if the
607 // pre header of that loop belongs to the currently analyzed loop. If it does,
608 // then we visit the back edges.
609 // Note that we cannot use GetPreHeader, as the loop may have not been populated
610 // yet.
611 HBasicBlock* pre_header = block->GetPredecessors()[0];
612 PopulateIrreducibleRecursive(pre_header);
613 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
614 blocks_.SetBit(block->GetBlockId());
615 block->SetInLoop(this);
616 HLoopInformation* info = block->GetLoopInformation();
617 for (HBasicBlock* back_edge : info->GetBackEdges()) {
618 PopulateIrreducibleRecursive(back_edge);
619 }
620 }
621 } else {
622 // Visit all predecessors. If one predecessor is part of the loop, this
623 // block is also part of this loop.
624 for (HBasicBlock* predecessor : block->GetPredecessors()) {
625 PopulateIrreducibleRecursive(predecessor);
626 if (blocks_.IsBitSet(predecessor->GetBlockId())) {
627 blocks_.SetBit(block->GetBlockId());
628 block->SetInLoop(this);
629 }
630 }
631 }
632}
633
634void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100635 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000636 // Populate this loop: starting with the back edge, recursively add predecessors
637 // that are not already part of that loop. Set the header as part of the loop
638 // to end the recursion.
639 // This is a recursive implementation of the algorithm described in
640 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
641 blocks_.SetBit(header_->GetBlockId());
642 header_->SetInLoop(this);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100643 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100644 DCHECK(back_edge->GetDominator() != nullptr);
645 if (!header_->Dominates(back_edge)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000646 irreducible_ = true;
647 header_->GetGraph()->SetHasIrreducibleLoops(true);
648 PopulateIrreducibleRecursive(back_edge);
649 } else {
650 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100651 }
David Brazdila4b8c212015-05-07 09:59:30 +0100652 }
653}
654
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100655HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000656 HBasicBlock* block = header_->GetPredecessors()[0];
657 DCHECK(irreducible_ || (block == header_->GetDominator()));
658 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100659}
660
661bool HLoopInformation::Contains(const HBasicBlock& block) const {
662 return blocks_.IsBitSet(block.GetBlockId());
663}
664
665bool HLoopInformation::IsIn(const HLoopInformation& other) const {
666 return other.blocks_.IsBitSet(header_->GetBlockId());
667}
668
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800669bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
670 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700671}
672
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100673size_t HLoopInformation::GetLifetimeEnd() const {
674 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100675 for (HBasicBlock* back_edge : GetBackEdges()) {
676 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100677 }
678 return last_position;
679}
680
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100681bool HBasicBlock::Dominates(HBasicBlock* other) const {
682 // Walk up the dominator tree from `other`, to find out if `this`
683 // is an ancestor.
684 HBasicBlock* current = other;
685 while (current != nullptr) {
686 if (current == this) {
687 return true;
688 }
689 current = current->GetDominator();
690 }
691 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100692}
693
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100694static void UpdateInputsUsers(HInstruction* instruction) {
695 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
696 instruction->InputAt(i)->AddUseAt(instruction, i);
697 }
698 // Environment should be created later.
699 DCHECK(!instruction->HasEnvironment());
700}
701
Roland Levillainccc07a92014-09-16 14:48:16 +0100702void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
703 HInstruction* replacement) {
704 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400705 if (initial->IsControlFlow()) {
706 // We can only replace a control flow instruction with another control flow instruction.
707 DCHECK(replacement->IsControlFlow());
708 DCHECK_EQ(replacement->GetId(), -1);
709 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
710 DCHECK_EQ(initial->GetBlock(), this);
711 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
712 DCHECK(initial->GetUses().IsEmpty());
713 DCHECK(initial->GetEnvUses().IsEmpty());
714 replacement->SetBlock(this);
715 replacement->SetId(GetGraph()->GetNextInstructionId());
716 instructions_.InsertInstructionBefore(replacement, initial);
717 UpdateInputsUsers(replacement);
718 } else {
719 InsertInstructionBefore(replacement, initial);
720 initial->ReplaceWith(replacement);
721 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100722 RemoveInstruction(initial);
723}
724
David Brazdil74eb1b22015-12-14 11:44:01 +0000725void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
726 DCHECK(!cursor->IsPhi());
727 DCHECK(!insn->IsPhi());
728 DCHECK(!insn->IsControlFlow());
729 DCHECK(insn->CanBeMoved());
730 DCHECK(!insn->HasSideEffects());
731
732 HBasicBlock* from_block = insn->GetBlock();
733 HBasicBlock* to_block = cursor->GetBlock();
734 DCHECK(from_block != to_block);
735
736 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
737 insn->SetBlock(to_block);
738 to_block->instructions_.InsertInstructionBefore(insn, cursor);
739}
740
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100741static void Add(HInstructionList* instruction_list,
742 HBasicBlock* block,
743 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000744 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000745 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100746 instruction->SetBlock(block);
747 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100748 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100749 instruction_list->AddInstruction(instruction);
750}
751
752void HBasicBlock::AddInstruction(HInstruction* instruction) {
753 Add(&instructions_, this, instruction);
754}
755
756void HBasicBlock::AddPhi(HPhi* phi) {
757 Add(&phis_, this, phi);
758}
759
David Brazdilc3d743f2015-04-22 13:40:50 +0100760void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
761 DCHECK(!cursor->IsPhi());
762 DCHECK(!instruction->IsPhi());
763 DCHECK_EQ(instruction->GetId(), -1);
764 DCHECK_NE(cursor->GetId(), -1);
765 DCHECK_EQ(cursor->GetBlock(), this);
766 DCHECK(!instruction->IsControlFlow());
767 instruction->SetBlock(this);
768 instruction->SetId(GetGraph()->GetNextInstructionId());
769 UpdateInputsUsers(instruction);
770 instructions_.InsertInstructionBefore(instruction, cursor);
771}
772
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100773void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
774 DCHECK(!cursor->IsPhi());
775 DCHECK(!instruction->IsPhi());
776 DCHECK_EQ(instruction->GetId(), -1);
777 DCHECK_NE(cursor->GetId(), -1);
778 DCHECK_EQ(cursor->GetBlock(), this);
779 DCHECK(!instruction->IsControlFlow());
780 DCHECK(!cursor->IsControlFlow());
781 instruction->SetBlock(this);
782 instruction->SetId(GetGraph()->GetNextInstructionId());
783 UpdateInputsUsers(instruction);
784 instructions_.InsertInstructionAfter(instruction, cursor);
785}
786
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100787void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
788 DCHECK_EQ(phi->GetId(), -1);
789 DCHECK_NE(cursor->GetId(), -1);
790 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100791 phi->SetBlock(this);
792 phi->SetId(GetGraph()->GetNextInstructionId());
793 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100794 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100795}
796
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100797static void Remove(HInstructionList* instruction_list,
798 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000799 HInstruction* instruction,
800 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100801 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100802 instruction->SetBlock(nullptr);
803 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000804 if (ensure_safety) {
805 DCHECK(instruction->GetUses().IsEmpty());
806 DCHECK(instruction->GetEnvUses().IsEmpty());
807 RemoveAsUser(instruction);
808 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100809}
810
David Brazdil1abb4192015-02-17 18:33:36 +0000811void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100812 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000813 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100814}
815
David Brazdil1abb4192015-02-17 18:33:36 +0000816void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
817 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100818}
819
David Brazdilc7508e92015-04-27 13:28:57 +0100820void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
821 if (instruction->IsPhi()) {
822 RemovePhi(instruction->AsPhi(), ensure_safety);
823 } else {
824 RemoveInstruction(instruction, ensure_safety);
825 }
826}
827
Vladimir Marko71bf8092015-09-15 15:33:14 +0100828void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
829 for (size_t i = 0; i < locals.size(); i++) {
830 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100831 SetRawEnvAt(i, instruction);
832 if (instruction != nullptr) {
833 instruction->AddEnvUseAt(this, i);
834 }
835 }
836}
837
David Brazdiled596192015-01-23 10:39:45 +0000838void HEnvironment::CopyFrom(HEnvironment* env) {
839 for (size_t i = 0; i < env->Size(); i++) {
840 HInstruction* instruction = env->GetInstructionAt(i);
841 SetRawEnvAt(i, instruction);
842 if (instruction != nullptr) {
843 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100844 }
David Brazdiled596192015-01-23 10:39:45 +0000845 }
846}
847
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700848void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
849 HBasicBlock* loop_header) {
850 DCHECK(loop_header->IsLoopHeader());
851 for (size_t i = 0; i < env->Size(); i++) {
852 HInstruction* instruction = env->GetInstructionAt(i);
853 SetRawEnvAt(i, instruction);
854 if (instruction == nullptr) {
855 continue;
856 }
857 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
858 // At the end of the loop pre-header, the corresponding value for instruction
859 // is the first input of the phi.
860 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700861 SetRawEnvAt(i, initial);
862 initial->AddEnvUseAt(this, i);
863 } else {
864 instruction->AddEnvUseAt(this, i);
865 }
866 }
867}
868
David Brazdil1abb4192015-02-17 18:33:36 +0000869void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100870 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000871 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100872}
873
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000874HInstruction::InstructionKind HInstruction::GetKind() const {
875 return GetKindInternal();
876}
877
Calin Juravle77520bc2015-01-12 18:45:46 +0000878HInstruction* HInstruction::GetNextDisregardingMoves() const {
879 HInstruction* next = GetNext();
880 while (next != nullptr && next->IsParallelMove()) {
881 next = next->GetNext();
882 }
883 return next;
884}
885
886HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
887 HInstruction* previous = GetPrevious();
888 while (previous != nullptr && previous->IsParallelMove()) {
889 previous = previous->GetPrevious();
890 }
891 return previous;
892}
893
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100894void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000895 if (first_instruction_ == nullptr) {
896 DCHECK(last_instruction_ == nullptr);
897 first_instruction_ = last_instruction_ = instruction;
898 } else {
899 last_instruction_->next_ = instruction;
900 instruction->previous_ = last_instruction_;
901 last_instruction_ = instruction;
902 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000903}
904
David Brazdilc3d743f2015-04-22 13:40:50 +0100905void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
906 DCHECK(Contains(cursor));
907 if (cursor == first_instruction_) {
908 cursor->previous_ = instruction;
909 instruction->next_ = cursor;
910 first_instruction_ = instruction;
911 } else {
912 instruction->previous_ = cursor->previous_;
913 instruction->next_ = cursor;
914 cursor->previous_ = instruction;
915 instruction->previous_->next_ = instruction;
916 }
917}
918
919void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
920 DCHECK(Contains(cursor));
921 if (cursor == last_instruction_) {
922 cursor->next_ = instruction;
923 instruction->previous_ = cursor;
924 last_instruction_ = instruction;
925 } else {
926 instruction->next_ = cursor->next_;
927 instruction->previous_ = cursor;
928 cursor->next_ = instruction;
929 instruction->next_->previous_ = instruction;
930 }
931}
932
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100933void HInstructionList::RemoveInstruction(HInstruction* instruction) {
934 if (instruction->previous_ != nullptr) {
935 instruction->previous_->next_ = instruction->next_;
936 }
937 if (instruction->next_ != nullptr) {
938 instruction->next_->previous_ = instruction->previous_;
939 }
940 if (instruction == first_instruction_) {
941 first_instruction_ = instruction->next_;
942 }
943 if (instruction == last_instruction_) {
944 last_instruction_ = instruction->previous_;
945 }
946}
947
Roland Levillain6b469232014-09-25 10:10:38 +0100948bool HInstructionList::Contains(HInstruction* instruction) const {
949 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
950 if (it.Current() == instruction) {
951 return true;
952 }
953 }
954 return false;
955}
956
Roland Levillainccc07a92014-09-16 14:48:16 +0100957bool HInstructionList::FoundBefore(const HInstruction* instruction1,
958 const HInstruction* instruction2) const {
959 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
960 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
961 if (it.Current() == instruction1) {
962 return true;
963 }
964 if (it.Current() == instruction2) {
965 return false;
966 }
967 }
968 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
969 return true;
970}
971
Roland Levillain6c82d402014-10-13 16:10:27 +0100972bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
973 if (other_instruction == this) {
974 // An instruction does not strictly dominate itself.
975 return false;
976 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100977 HBasicBlock* block = GetBlock();
978 HBasicBlock* other_block = other_instruction->GetBlock();
979 if (block != other_block) {
980 return GetBlock()->Dominates(other_instruction->GetBlock());
981 } else {
982 // If both instructions are in the same block, ensure this
983 // instruction comes before `other_instruction`.
984 if (IsPhi()) {
985 if (!other_instruction->IsPhi()) {
986 // Phis appear before non phi-instructions so this instruction
987 // dominates `other_instruction`.
988 return true;
989 } else {
990 // There is no order among phis.
991 LOG(FATAL) << "There is no dominance between phis of a same block.";
992 return false;
993 }
994 } else {
995 // `this` is not a phi.
996 if (other_instruction->IsPhi()) {
997 // Phis appear before non phi-instructions so this instruction
998 // does not dominate `other_instruction`.
999 return false;
1000 } else {
1001 // Check whether this instruction comes before
1002 // `other_instruction` in the instruction list.
1003 return block->GetInstructions().FoundBefore(this, other_instruction);
1004 }
1005 }
1006 }
1007}
1008
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001009void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001010 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +00001011 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
1012 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001013 HInstruction* user = current->GetUser();
1014 size_t input_index = current->GetIndex();
1015 user->SetRawInputAt(input_index, other);
1016 other->AddUseAt(user, input_index);
1017 }
1018
David Brazdiled596192015-01-23 10:39:45 +00001019 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
1020 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001021 HEnvironment* user = current->GetUser();
1022 size_t input_index = current->GetIndex();
1023 user->SetRawEnvAt(input_index, other);
1024 other->AddEnvUseAt(user, input_index);
1025 }
1026
David Brazdiled596192015-01-23 10:39:45 +00001027 uses_.Clear();
1028 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001029}
1030
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001031void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +00001032 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001033 SetRawInputAt(index, replacement);
1034 replacement->AddUseAt(this, index);
1035}
1036
Nicolas Geoffray39468442014-09-02 15:17:15 +01001037size_t HInstruction::EnvironmentSize() const {
1038 return HasEnvironment() ? environment_->Size() : 0;
1039}
1040
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001041void HPhi::AddInput(HInstruction* input) {
1042 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001043 inputs_.push_back(HUserRecord<HInstruction*>(input));
1044 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001045}
1046
David Brazdil2d7352b2015-04-20 14:52:42 +01001047void HPhi::RemoveInputAt(size_t index) {
1048 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001049 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001050 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001051 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001052 InputRecordAt(i).GetUseNode()->SetIndex(i);
1053 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001054}
1055
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001056#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001057void H##name::Accept(HGraphVisitor* visitor) { \
1058 visitor->Visit##name(this); \
1059}
1060
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001061FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001062
1063#undef DEFINE_ACCEPT
1064
1065void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001066 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1067 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001068 if (block != nullptr) {
1069 VisitBasicBlock(block);
1070 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001071 }
1072}
1073
Roland Levillain633021e2014-10-01 14:12:25 +01001074void HGraphVisitor::VisitReversePostOrder() {
1075 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1076 VisitBasicBlock(it.Current());
1077 }
1078}
1079
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001080void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001081 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001082 it.Current()->Accept(this);
1083 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001084 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001085 it.Current()->Accept(this);
1086 }
1087}
1088
Mark Mendelle82549b2015-05-06 10:55:34 -04001089HConstant* HTypeConversion::TryStaticEvaluation() const {
1090 HGraph* graph = GetBlock()->GetGraph();
1091 if (GetInput()->IsIntConstant()) {
1092 int32_t value = GetInput()->AsIntConstant()->GetValue();
1093 switch (GetResultType()) {
1094 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001095 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001096 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001097 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001098 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001099 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001100 default:
1101 return nullptr;
1102 }
1103 } else if (GetInput()->IsLongConstant()) {
1104 int64_t value = GetInput()->AsLongConstant()->GetValue();
1105 switch (GetResultType()) {
1106 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001107 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001108 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001109 return graph->GetFloatConstant(static_cast<float>(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()->IsFloatConstant()) {
1116 float value = GetInput()->AsFloatConstant()->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 <= kPrimIntMin)
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::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001135 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001136 default:
1137 return nullptr;
1138 }
1139 } else if (GetInput()->IsDoubleConstant()) {
1140 double value = GetInput()->AsDoubleConstant()->GetValue();
1141 switch (GetResultType()) {
1142 case Primitive::kPrimInt:
1143 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001144 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001145 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001146 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001147 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001148 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1149 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001150 case Primitive::kPrimLong:
1151 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001152 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001153 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001154 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001155 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001156 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1157 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001158 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001159 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001160 default:
1161 return nullptr;
1162 }
1163 }
1164 return nullptr;
1165}
1166
Roland Levillain9240d6a2014-10-20 16:47:04 +01001167HConstant* HUnaryOperation::TryStaticEvaluation() const {
1168 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001169 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001170 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001171 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001172 }
1173 return nullptr;
1174}
1175
1176HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001177 if (GetLeft()->IsIntConstant()) {
1178 if (GetRight()->IsIntConstant()) {
1179 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1180 } else if (GetRight()->IsLongConstant()) {
1181 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1182 }
1183 } else if (GetLeft()->IsLongConstant()) {
1184 if (GetRight()->IsIntConstant()) {
1185 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1186 } else if (GetRight()->IsLongConstant()) {
1187 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001188 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001189 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
1190 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain556c3d12014-09-18 15:25:07 +01001191 }
1192 return nullptr;
1193}
Dave Allison20dfc792014-06-16 20:44:29 -07001194
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001195HConstant* HBinaryOperation::GetConstantRight() const {
1196 if (GetRight()->IsConstant()) {
1197 return GetRight()->AsConstant();
1198 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1199 return GetLeft()->AsConstant();
1200 } else {
1201 return nullptr;
1202 }
1203}
1204
1205// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001206// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001207HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1208 HInstruction* most_constant_right = GetConstantRight();
1209 if (most_constant_right == nullptr) {
1210 return nullptr;
1211 } else if (most_constant_right == GetLeft()) {
1212 return GetRight();
1213 } else {
1214 return GetLeft();
1215 }
1216}
1217
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001218bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1219 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001220}
1221
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001222bool HInstruction::Equals(HInstruction* other) const {
1223 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001224 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001225 if (!InstructionDataEquals(other)) return false;
1226 if (GetType() != other->GetType()) return false;
1227 if (InputCount() != other->InputCount()) return false;
1228
1229 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1230 if (InputAt(i) != other->InputAt(i)) return false;
1231 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001232 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001233 return true;
1234}
1235
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001236std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1237#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1238 switch (rhs) {
1239 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1240 default:
1241 os << "Unknown instruction kind " << static_cast<int>(rhs);
1242 break;
1243 }
1244#undef DECLARE_CASE
1245 return os;
1246}
1247
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001248void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001249 next_->previous_ = previous_;
1250 if (previous_ != nullptr) {
1251 previous_->next_ = next_;
1252 }
1253 if (block_->instructions_.first_instruction_ == this) {
1254 block_->instructions_.first_instruction_ = next_;
1255 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001256 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001257
1258 previous_ = cursor->previous_;
1259 if (previous_ != nullptr) {
1260 previous_->next_ = this;
1261 }
1262 next_ = cursor;
1263 cursor->previous_ = this;
1264 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001265
1266 if (block_->instructions_.first_instruction_ == cursor) {
1267 block_->instructions_.first_instruction_ = this;
1268 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001269}
1270
Vladimir Markofb337ea2015-11-25 15:25:10 +00001271void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1272 DCHECK(!CanThrow());
1273 DCHECK(!HasSideEffects());
1274 DCHECK(!HasEnvironmentUses());
1275 DCHECK(HasNonEnvironmentUses());
1276 DCHECK(!IsPhi()); // Makes no sense for Phi.
1277 DCHECK_EQ(InputCount(), 0u);
1278
1279 // Find the target block.
1280 HUseIterator<HInstruction*> uses_it(GetUses());
1281 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1282 uses_it.Advance();
1283 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1284 uses_it.Advance();
1285 }
1286 if (!uses_it.Done()) {
1287 // This instruction has uses in two or more blocks. Find the common dominator.
1288 CommonDominator finder(target_block);
1289 for (; !uses_it.Done(); uses_it.Advance()) {
1290 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1291 }
1292 target_block = finder.Get();
1293 DCHECK(target_block != nullptr);
1294 }
1295 // Move to the first dominator not in a loop.
1296 while (target_block->IsInLoop()) {
1297 target_block = target_block->GetDominator();
1298 DCHECK(target_block != nullptr);
1299 }
1300
1301 // Find insertion position.
1302 HInstruction* insert_pos = nullptr;
1303 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1304 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1305 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1306 insert_pos = uses_it2.Current()->GetUser();
1307 }
1308 }
1309 if (insert_pos == nullptr) {
1310 // No user in `target_block`, insert before the control flow instruction.
1311 insert_pos = target_block->GetLastInstruction();
1312 DCHECK(insert_pos->IsControlFlow());
1313 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1314 if (insert_pos->IsIf()) {
1315 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1316 if (if_input == insert_pos->GetPrevious()) {
1317 insert_pos = if_input;
1318 }
1319 }
1320 }
1321 MoveBefore(insert_pos);
1322}
1323
David Brazdilfc6a86a2015-06-26 10:33:45 +00001324HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001325 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001326 DCHECK_EQ(cursor->GetBlock(), this);
1327
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001328 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1329 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001330 new_block->instructions_.first_instruction_ = cursor;
1331 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1332 instructions_.last_instruction_ = cursor->previous_;
1333 if (cursor->previous_ == nullptr) {
1334 instructions_.first_instruction_ = nullptr;
1335 } else {
1336 cursor->previous_->next_ = nullptr;
1337 cursor->previous_ = nullptr;
1338 }
1339
1340 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001341 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001342
Vladimir Marko60584552015-09-03 13:35:12 +00001343 for (HBasicBlock* successor : GetSuccessors()) {
1344 new_block->successors_.push_back(successor);
1345 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001346 }
Vladimir Marko60584552015-09-03 13:35:12 +00001347 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001348 AddSuccessor(new_block);
1349
David Brazdil56e1acc2015-06-30 15:41:36 +01001350 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001351 return new_block;
1352}
1353
David Brazdild7558da2015-09-22 13:04:14 +01001354HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001355 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001356 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1357
1358 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1359
1360 for (HBasicBlock* predecessor : GetPredecessors()) {
1361 new_block->predecessors_.push_back(predecessor);
1362 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1363 }
1364 predecessors_.clear();
1365 AddPredecessor(new_block);
1366
1367 GetGraph()->AddBlock(new_block);
1368 return new_block;
1369}
1370
David Brazdil9bc43612015-11-05 21:25:24 +00001371HBasicBlock* HBasicBlock::SplitCatchBlockAfterMoveException() {
1372 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
1373 DCHECK(IsCatchBlock()) << "This method is intended for catch blocks only.";
1374
1375 HInstruction* first_insn = GetFirstInstruction();
1376 HInstruction* split_before = nullptr;
1377
1378 if (first_insn != nullptr && first_insn->IsLoadException()) {
1379 // Catch block starts with a LoadException. Split the block after
1380 // the StoreLocal and ClearException which must come after the load.
1381 DCHECK(first_insn->GetNext()->IsStoreLocal());
1382 DCHECK(first_insn->GetNext()->GetNext()->IsClearException());
1383 split_before = first_insn->GetNext()->GetNext()->GetNext();
1384 } else {
1385 // Catch block does not load the exception. Split at the beginning
1386 // to create an empty catch block.
1387 split_before = first_insn;
1388 }
1389
1390 if (split_before == nullptr) {
1391 // Catch block has no instructions after the split point (must be dead).
1392 // Do not split it but rather signal error by returning nullptr.
1393 return nullptr;
1394 } else {
1395 return SplitBefore(split_before);
1396 }
1397}
1398
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001399HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1400 DCHECK(!cursor->IsControlFlow());
1401 DCHECK_NE(instructions_.last_instruction_, cursor);
1402 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001403
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001404 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1405 new_block->instructions_.first_instruction_ = cursor->GetNext();
1406 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1407 cursor->next_->previous_ = nullptr;
1408 cursor->next_ = nullptr;
1409 instructions_.last_instruction_ = cursor;
1410
1411 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001412 for (HBasicBlock* successor : GetSuccessors()) {
1413 new_block->successors_.push_back(successor);
1414 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001415 }
Vladimir Marko60584552015-09-03 13:35:12 +00001416 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001417
Vladimir Marko60584552015-09-03 13:35:12 +00001418 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001419 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001420 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001421 }
Vladimir Marko60584552015-09-03 13:35:12 +00001422 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001423 return new_block;
1424}
1425
David Brazdilec16f792015-08-19 15:04:01 +01001426const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001427 if (EndsWithTryBoundary()) {
1428 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1429 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001430 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001431 return try_boundary;
1432 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001433 DCHECK(IsTryBlock());
1434 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001435 return nullptr;
1436 }
David Brazdilec16f792015-08-19 15:04:01 +01001437 } else if (IsTryBlock()) {
1438 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001439 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001440 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001441 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001442}
1443
David Brazdild7558da2015-09-22 13:04:14 +01001444bool HBasicBlock::HasThrowingInstructions() const {
1445 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1446 if (it.Current()->CanThrow()) {
1447 return true;
1448 }
1449 }
1450 return false;
1451}
1452
David Brazdilfc6a86a2015-06-26 10:33:45 +00001453static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1454 return block.GetPhis().IsEmpty()
1455 && !block.GetInstructions().IsEmpty()
1456 && block.GetFirstInstruction() == block.GetLastInstruction();
1457}
1458
David Brazdil46e2a392015-03-16 17:31:52 +00001459bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001460 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1461}
1462
1463bool HBasicBlock::IsSingleTryBoundary() const {
1464 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001465}
1466
David Brazdil8d5b8b22015-03-24 10:51:52 +00001467bool HBasicBlock::EndsWithControlFlowInstruction() const {
1468 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1469}
1470
David Brazdilb2bd1c52015-03-25 11:17:37 +00001471bool HBasicBlock::EndsWithIf() const {
1472 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1473}
1474
David Brazdilffee3d32015-07-06 11:48:53 +01001475bool HBasicBlock::EndsWithTryBoundary() const {
1476 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1477}
1478
David Brazdilb2bd1c52015-03-25 11:17:37 +00001479bool HBasicBlock::HasSinglePhi() const {
1480 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1481}
1482
David Brazdild26a4112015-11-10 11:07:31 +00001483ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1484 if (EndsWithTryBoundary()) {
1485 // The normal-flow successor of HTryBoundary is always stored at index zero.
1486 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1487 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1488 } else {
1489 // All successors of blocks not ending with TryBoundary are normal.
1490 return ArrayRef<HBasicBlock* const>(successors_);
1491 }
1492}
1493
1494ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1495 if (EndsWithTryBoundary()) {
1496 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1497 } else {
1498 // Blocks not ending with TryBoundary do not have exceptional successors.
1499 return ArrayRef<HBasicBlock* const>();
1500 }
1501}
1502
David Brazdilffee3d32015-07-06 11:48:53 +01001503bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001504 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1505 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1506
1507 size_t length = handlers1.size();
1508 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001509 return false;
1510 }
1511
David Brazdilb618ade2015-07-29 10:31:29 +01001512 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001513 for (size_t i = 0; i < length; ++i) {
1514 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001515 return false;
1516 }
1517 }
1518 return true;
1519}
1520
David Brazdil2d7352b2015-04-20 14:52:42 +01001521size_t HInstructionList::CountSize() const {
1522 size_t size = 0;
1523 HInstruction* current = first_instruction_;
1524 for (; current != nullptr; current = current->GetNext()) {
1525 size++;
1526 }
1527 return size;
1528}
1529
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001530void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1531 for (HInstruction* current = first_instruction_;
1532 current != nullptr;
1533 current = current->GetNext()) {
1534 current->SetBlock(block);
1535 }
1536}
1537
1538void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1539 DCHECK(Contains(cursor));
1540 if (!instruction_list.IsEmpty()) {
1541 if (cursor == last_instruction_) {
1542 last_instruction_ = instruction_list.last_instruction_;
1543 } else {
1544 cursor->next_->previous_ = instruction_list.last_instruction_;
1545 }
1546 instruction_list.last_instruction_->next_ = cursor->next_;
1547 cursor->next_ = instruction_list.first_instruction_;
1548 instruction_list.first_instruction_->previous_ = cursor;
1549 }
1550}
1551
1552void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001553 if (IsEmpty()) {
1554 first_instruction_ = instruction_list.first_instruction_;
1555 last_instruction_ = instruction_list.last_instruction_;
1556 } else {
1557 AddAfter(last_instruction_, instruction_list);
1558 }
1559}
1560
David Brazdil04ff4e82015-12-10 13:54:52 +00001561// Should be called on instructions in a dead block in post order. This method
1562// assumes `insn` has been removed from all users with the exception of catch
1563// phis because of missing exceptional edges in the graph. It removes the
1564// instruction from catch phi uses, together with inputs of other catch phis in
1565// the catch block at the same index, as these must be dead too.
1566static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1567 DCHECK(!insn->HasEnvironmentUses());
1568 while (insn->HasNonEnvironmentUses()) {
1569 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1570 size_t use_index = use->GetIndex();
1571 HBasicBlock* user_block = use->GetUser()->GetBlock();
1572 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1573 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1574 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1575 }
1576 }
1577}
1578
David Brazdil2d7352b2015-04-20 14:52:42 +01001579void HBasicBlock::DisconnectAndDelete() {
1580 // Dominators must be removed after all the blocks they dominate. This way
1581 // a loop header is removed last, a requirement for correct loop information
1582 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001583 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001584
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001585 // (1) Remove the block from all loops it is included in.
David Brazdil2d7352b2015-04-20 14:52:42 +01001586 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1587 HLoopInformation* loop_info = it.Current();
1588 loop_info->Remove(this);
1589 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001590 // If this was the last back edge of the loop, we deliberately leave the
1591 // loop in an inconsistent state and will fail SSAChecker unless the
1592 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001593 loop_info->RemoveBackEdge(this);
1594 }
1595 }
1596
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001597 // (2) Disconnect the block from its predecessors and update their
1598 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001599 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001600 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001601 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1602 // This block is the only normal-flow successor of the TryBoundary which
1603 // makes `predecessor` dead. Since DCE removes blocks in post order,
1604 // exception handlers of this TryBoundary were already visited and any
1605 // remaining handlers therefore must be live. We remove `predecessor` from
1606 // their list of predecessors.
1607 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1608 while (predecessor->GetSuccessors().size() > 1) {
1609 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1610 DCHECK(handler->IsCatchBlock());
1611 predecessor->RemoveSuccessor(handler);
1612 handler->RemovePredecessor(predecessor);
1613 }
1614 }
1615
David Brazdil2d7352b2015-04-20 14:52:42 +01001616 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001617 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1618 if (num_pred_successors == 1u) {
1619 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001620 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1621 // successor. Replace those with a HGoto.
1622 DCHECK(last_instruction->IsIf() ||
1623 last_instruction->IsPackedSwitch() ||
1624 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001625 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001626 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001627 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001628 // The predecessor has no remaining successors and therefore must be dead.
1629 // We deliberately leave it without a control-flow instruction so that the
1630 // SSAChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001631 predecessor->RemoveInstruction(last_instruction);
1632 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001633 // There are multiple successors left. The removed block might be a successor
1634 // of a PackedSwitch which will be completely removed (perhaps replaced with
1635 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1636 // case, leave `last_instruction` as is for now.
1637 DCHECK(last_instruction->IsPackedSwitch() ||
1638 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001639 }
David Brazdil46e2a392015-03-16 17:31:52 +00001640 }
Vladimir Marko60584552015-09-03 13:35:12 +00001641 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001642
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001643 // (3) Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001644 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001645 // Delete this block from the list of predecessors.
1646 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001647 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001648
1649 // Check that `successor` has other predecessors, otherwise `this` is the
1650 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001651 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001652
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001653 // Remove this block's entries in the successor's phis. Skip exceptional
1654 // successors because catch phi inputs do not correspond to predecessor
1655 // blocks but throwing instructions. Their inputs will be updated in step (4).
1656 if (!successor->IsCatchBlock()) {
1657 if (successor->predecessors_.size() == 1u) {
1658 // The successor has just one predecessor left. Replace phis with the only
1659 // remaining input.
1660 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1661 HPhi* phi = phi_it.Current()->AsPhi();
1662 phi->ReplaceWith(phi->InputAt(1 - this_index));
1663 successor->RemovePhi(phi);
1664 }
1665 } else {
1666 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1667 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1668 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001669 }
1670 }
1671 }
Vladimir Marko60584552015-09-03 13:35:12 +00001672 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001673
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001674 // (4) Remove instructions and phis. Instructions should have no remaining uses
1675 // except in catch phis. If an instruction is used by a catch phi at `index`,
1676 // remove `index`-th input of all phis in the catch block since they are
1677 // guaranteed dead. Note that we may miss dead inputs this way but the
1678 // graph will always remain consistent.
1679 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1680 HInstruction* insn = it.Current();
David Brazdil04ff4e82015-12-10 13:54:52 +00001681 RemoveUsesOfDeadInstruction(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001682 RemoveInstruction(insn);
1683 }
1684 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
David Brazdil04ff4e82015-12-10 13:54:52 +00001685 HPhi* insn = it.Current()->AsPhi();
1686 RemoveUsesOfDeadInstruction(insn);
1687 RemovePhi(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001688 }
1689
David Brazdil2d7352b2015-04-20 14:52:42 +01001690 // Disconnect from the dominator.
1691 dominator_->RemoveDominatedBlock(this);
1692 SetDominator(nullptr);
1693
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001694 // Delete from the graph, update reverse post order.
1695 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001696 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001697}
1698
1699void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001700 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001701 DCHECK(ContainsElement(dominated_blocks_, other));
1702 DCHECK_EQ(GetSingleSuccessor(), other);
1703 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001704 DCHECK(other->GetPhis().IsEmpty());
1705
David Brazdil2d7352b2015-04-20 14:52:42 +01001706 // Move instructions from `other` to `this`.
1707 DCHECK(EndsWithControlFlowInstruction());
1708 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001709 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001710 other->instructions_.SetBlockOfInstructions(this);
1711 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001712
David Brazdil2d7352b2015-04-20 14:52:42 +01001713 // Remove `other` from the loops it is included in.
1714 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1715 HLoopInformation* loop_info = it.Current();
1716 loop_info->Remove(other);
1717 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001718 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001719 }
1720 }
1721
1722 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001723 successors_.clear();
1724 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001725 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001726 successor->ReplacePredecessor(other, this);
1727 }
1728
David Brazdil2d7352b2015-04-20 14:52:42 +01001729 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001730 RemoveDominatedBlock(other);
1731 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1732 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001733 dominated->SetDominator(this);
1734 }
Vladimir Marko60584552015-09-03 13:35:12 +00001735 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001736 other->dominator_ = nullptr;
1737
1738 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001739 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001740
1741 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001742 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001743 other->SetGraph(nullptr);
1744}
1745
1746void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1747 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001748 DCHECK(GetDominatedBlocks().empty());
1749 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001750 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001751 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001752 DCHECK(other->GetPhis().IsEmpty());
1753 DCHECK(!other->IsInLoop());
1754
1755 // Move instructions from `other` to `this`.
1756 instructions_.Add(other->GetInstructions());
1757 other->instructions_.SetBlockOfInstructions(this);
1758
1759 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001760 successors_.clear();
1761 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001762 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001763 successor->ReplacePredecessor(other, this);
1764 }
1765
1766 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001767 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1768 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001769 dominated->SetDominator(this);
1770 }
Vladimir Marko60584552015-09-03 13:35:12 +00001771 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001772 other->dominator_ = nullptr;
1773 other->graph_ = nullptr;
1774}
1775
1776void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001777 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001778 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001779 predecessor->ReplaceSuccessor(this, other);
1780 }
Vladimir Marko60584552015-09-03 13:35:12 +00001781 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001782 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001783 successor->ReplacePredecessor(this, other);
1784 }
Vladimir Marko60584552015-09-03 13:35:12 +00001785 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1786 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001787 }
1788 GetDominator()->ReplaceDominatedBlock(this, other);
1789 other->SetDominator(GetDominator());
1790 dominator_ = nullptr;
1791 graph_ = nullptr;
1792}
1793
1794// Create space in `blocks` for adding `number_of_new_blocks` entries
1795// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001796static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001797 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001798 size_t after) {
1799 DCHECK_LT(after, blocks->size());
1800 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001801 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001802 blocks->resize(new_size);
1803 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001804}
1805
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001806void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001807 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001808 DCHECK(block->GetSuccessors().empty());
1809 DCHECK(block->GetPredecessors().empty());
1810 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001811 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001812 DCHECK(block->GetInstructions().IsEmpty());
1813 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001814
David Brazdilc7af85d2015-05-26 12:05:55 +01001815 if (block->IsExitBlock()) {
1816 exit_block_ = nullptr;
1817 }
1818
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001819 RemoveElement(reverse_post_order_, block);
1820 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001821}
1822
Calin Juravle2e768302015-07-28 14:41:11 +00001823HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001824 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001825 // Update the environments in this graph to have the invoke's environment
1826 // as parent.
1827 {
1828 HReversePostOrderIterator it(*this);
1829 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1830 for (; !it.Done(); it.Advance()) {
1831 HBasicBlock* block = it.Current();
1832 for (HInstructionIterator instr_it(block->GetInstructions());
1833 !instr_it.Done();
1834 instr_it.Advance()) {
1835 HInstruction* current = instr_it.Current();
1836 if (current->NeedsEnvironment()) {
1837 current->GetEnvironment()->SetAndCopyParentChain(
1838 outer_graph->GetArena(), invoke->GetEnvironment());
1839 }
1840 }
1841 }
1842 }
1843 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1844 if (HasBoundsChecks()) {
1845 outer_graph->SetHasBoundsChecks(true);
1846 }
1847
Calin Juravle2e768302015-07-28 14:41:11 +00001848 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001849 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001850 // Simple case of an entry block, a body block, and an exit block.
1851 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001852 HBasicBlock* body = GetBlocks()[1];
1853 DCHECK(GetBlocks()[0]->IsEntryBlock());
1854 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001855 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001856 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001857 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001858
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001859 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1860 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001861
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001862 // Replace the invoke with the return value of the inlined graph.
1863 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001864 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001865 } else {
1866 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001867 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001868
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001869 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001870 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001871 // Need to inline multiple blocks. We split `invoke`'s block
1872 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001873 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001874 // with the second half.
1875 ArenaAllocator* allocator = outer_graph->GetArena();
1876 HBasicBlock* at = invoke->GetBlock();
1877 HBasicBlock* to = at->SplitAfter(invoke);
1878
Vladimir Markoec7802a2015-10-01 20:57:57 +01001879 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001880 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001881 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001882 exit_block_->ReplaceWith(to);
1883
1884 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001885 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001886 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001887 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001888 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001889 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001890 if (!returns_void) {
1891 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001892 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001893 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001894 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001895 } else {
1896 if (!returns_void) {
1897 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001898 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001899 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001900 to->AddPhi(return_value->AsPhi());
1901 }
Vladimir Marko60584552015-09-03 13:35:12 +00001902 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001903 HInstruction* last = predecessor->GetLastInstruction();
1904 if (!returns_void) {
1905 return_value->AsPhi()->AddInput(last->InputAt(0));
1906 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001907 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001908 predecessor->RemoveInstruction(last);
1909 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001910 }
1911
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001912 // Update the meta information surrounding blocks:
1913 // (1) the graph they are now in,
1914 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001915 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05001916 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001917 // Note that we do not need to update catch phi inputs because they
1918 // correspond to the register file of the outer method which the inlinee
1919 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001920
1921 // We don't add the entry block, the exit block, and the first block, which
1922 // has been merged with `at`.
1923 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1924
1925 // We add the `to` block.
1926 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001927 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001928 + kNumberOfNewBlocksInCaller;
1929
1930 // Find the location of `at` in the outer graph's reverse post order. The new
1931 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001932 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001933 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1934
David Brazdil95177982015-10-30 12:56:58 -05001935 HLoopInformation* loop_info = at->GetLoopInformation();
1936 // Copy TryCatchInformation if `at` is a try block, not if it is a catch block.
1937 TryCatchInformation* try_catch_info = at->IsTryBlock() ? at->GetTryCatchInformation() : nullptr;
1938
1939 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1940 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001941 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1942 HBasicBlock* current = it.Current();
1943 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05001944 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001945 DCHECK(current->GetGraph() == this);
1946 current->SetGraph(outer_graph);
1947 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001948 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001949 if (!current->IsInLoop()) {
David Brazdil95177982015-10-30 12:56:58 -05001950 current->SetLoopInformation(loop_info);
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001951 } else if (current->IsLoopHeader()) {
1952 // Clear the information of which blocks are contained in that loop. Since the
1953 // information is stored as a bit vector based on block ids, we have to update
1954 // it, as those block ids were specific to the callee graph and we are now adding
1955 // these blocks to the caller graph.
1956 current->GetLoopInformation()->ClearAllBlocks();
1957 }
1958 if (current->IsInLoop()) {
1959 for (HLoopInformationOutwardIterator loop_it(*current);
1960 !loop_it.Done();
1961 loop_it.Advance()) {
David Brazdil7d275372015-04-21 16:36:35 +01001962 loop_it.Current()->Add(current);
1963 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001964 }
David Brazdil95177982015-10-30 12:56:58 -05001965 current->SetTryCatchInformation(try_catch_info);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001966 }
1967 }
1968
David Brazdil95177982015-10-30 12:56:58 -05001969 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001970 to->SetGraph(outer_graph);
1971 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001972 outer_graph->reverse_post_order_[++index_of_at] = to;
David Brazdil95177982015-10-30 12:56:58 -05001973 if (loop_info != nullptr) {
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001974 if (!to->IsInLoop()) {
1975 to->SetLoopInformation(loop_info);
1976 }
David Brazdil7d275372015-04-21 16:36:35 +01001977 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1978 loop_it.Current()->Add(to);
1979 }
David Brazdil95177982015-10-30 12:56:58 -05001980 if (loop_info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001981 // Only `to` can become a back edge, as the inlined blocks
1982 // are predecessors of `to`.
David Brazdil95177982015-10-30 12:56:58 -05001983 loop_info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001984 }
1985 }
David Brazdil95177982015-10-30 12:56:58 -05001986 to->SetTryCatchInformation(try_catch_info);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001987 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001988
David Brazdil05144f42015-04-16 15:18:00 +01001989 // Update the next instruction id of the outer graph, so that instructions
1990 // added later get bigger ids than those in the inner graph.
1991 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1992
1993 // Walk over the entry block and:
1994 // - Move constants from the entry block to the outer_graph's entry block,
1995 // - Replace HParameterValue instructions with their real value.
1996 // - Remove suspend checks, that hold an environment.
1997 // We must do this after the other blocks have been inlined, otherwise ids of
1998 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001999 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002000 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2001 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002002 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002003 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002004 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002005 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002006 replacement = outer_graph->GetIntConstant(
2007 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002008 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002009 replacement = outer_graph->GetLongConstant(
2010 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002011 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002012 replacement = outer_graph->GetFloatConstant(
2013 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002014 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002015 replacement = outer_graph->GetDoubleConstant(
2016 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002017 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002018 if (kIsDebugBuild
2019 && invoke->IsInvokeStaticOrDirect()
2020 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2021 // Ensure we do not use the last input of `invoke`, as it
2022 // contains a clinit check which is not an actual argument.
2023 size_t last_input_index = invoke->InputCount() - 1;
2024 DCHECK(parameter_index != last_input_index);
2025 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002026 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002027 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002028 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002029 } else {
2030 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2031 entry_block_->RemoveInstruction(current);
2032 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002033 if (replacement != nullptr) {
2034 current->ReplaceWith(replacement);
2035 // If the current is the return value then we need to update the latter.
2036 if (current == return_value) {
2037 DCHECK_EQ(entry_block_, return_value->GetBlock());
2038 return_value = replacement;
2039 }
2040 }
2041 }
2042
2043 if (return_value != nullptr) {
2044 invoke->ReplaceWith(return_value);
David Brazdil05144f42015-04-16 15:18:00 +01002045 }
2046
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002047 // Finally remove the invoke from the caller.
2048 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00002049
2050 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002051}
2052
Mingyao Yang3584bce2015-05-19 16:01:59 -07002053/*
2054 * Loop will be transformed to:
2055 * old_pre_header
2056 * |
2057 * if_block
2058 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002059 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002060 * \ /
2061 * new_pre_header
2062 * |
2063 * header
2064 */
2065void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2066 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002067 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002068
Aart Bik3fc7f352015-11-20 22:03:03 -08002069 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002070 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002071 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2072 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002073 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2074 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002075 AddBlock(true_block);
2076 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002077 AddBlock(new_pre_header);
2078
Aart Bik3fc7f352015-11-20 22:03:03 -08002079 header->ReplacePredecessor(old_pre_header, new_pre_header);
2080 old_pre_header->successors_.clear();
2081 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002082
Aart Bik3fc7f352015-11-20 22:03:03 -08002083 old_pre_header->AddSuccessor(if_block);
2084 if_block->AddSuccessor(true_block); // True successor
2085 if_block->AddSuccessor(false_block); // False successor
2086 true_block->AddSuccessor(new_pre_header);
2087 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002088
Aart Bik3fc7f352015-11-20 22:03:03 -08002089 old_pre_header->dominated_blocks_.push_back(if_block);
2090 if_block->SetDominator(old_pre_header);
2091 if_block->dominated_blocks_.push_back(true_block);
2092 true_block->SetDominator(if_block);
2093 if_block->dominated_blocks_.push_back(false_block);
2094 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002095 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002096 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002097 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002098 header->SetDominator(new_pre_header);
2099
Aart Bik3fc7f352015-11-20 22:03:03 -08002100 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002101 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002102 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002103 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002104 reverse_post_order_[index_of_header++] = true_block;
2105 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002106 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002107
Aart Bik3fc7f352015-11-20 22:03:03 -08002108 // Fix loop information.
2109 HLoopInformation* loop_info = old_pre_header->GetLoopInformation();
2110 if (loop_info != nullptr) {
2111 if_block->SetLoopInformation(loop_info);
2112 true_block->SetLoopInformation(loop_info);
2113 false_block->SetLoopInformation(loop_info);
2114 new_pre_header->SetLoopInformation(loop_info);
2115 // Add blocks to all enveloping loops.
2116 for (HLoopInformationOutwardIterator loop_it(*old_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002117 !loop_it.Done();
2118 loop_it.Advance()) {
2119 loop_it.Current()->Add(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002120 loop_it.Current()->Add(true_block);
2121 loop_it.Current()->Add(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002122 loop_it.Current()->Add(new_pre_header);
2123 }
2124 }
Aart Bik3fc7f352015-11-20 22:03:03 -08002125
2126 // Fix try/catch information.
2127 TryCatchInformation* try_catch_info = old_pre_header->IsTryBlock()
2128 ? old_pre_header->GetTryCatchInformation()
2129 : nullptr;
2130 if_block->SetTryCatchInformation(try_catch_info);
2131 true_block->SetTryCatchInformation(try_catch_info);
2132 false_block->SetTryCatchInformation(try_catch_info);
2133 new_pre_header->SetTryCatchInformation(try_catch_info);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002134}
2135
David Brazdilf5552582015-12-27 13:36:12 +00002136static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2137 SHARED_REQUIRES(Locks::mutator_lock_) {
2138 if (rti.IsValid()) {
2139 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2140 << " upper_bound_rti: " << upper_bound_rti
2141 << " rti: " << rti;
2142 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
2143 }
2144}
2145
Calin Juravle2e768302015-07-28 14:41:11 +00002146void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2147 if (kIsDebugBuild) {
2148 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2149 ScopedObjectAccess soa(Thread::Current());
2150 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2151 if (IsBoundType()) {
2152 // Having the test here spares us from making the method virtual just for
2153 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002154 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002155 }
2156 }
2157 reference_type_info_ = rti;
2158}
2159
David Brazdilf5552582015-12-27 13:36:12 +00002160void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2161 if (kIsDebugBuild) {
2162 ScopedObjectAccess soa(Thread::Current());
2163 DCHECK(upper_bound.IsValid());
2164 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2165 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2166 }
2167 upper_bound_ = upper_bound;
2168 upper_can_be_null_ = can_be_null;
2169}
2170
Calin Juravle2e768302015-07-28 14:41:11 +00002171ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
2172
2173ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
2174 : type_handle_(type_handle), is_exact_(is_exact) {
2175 if (kIsDebugBuild) {
2176 ScopedObjectAccess soa(Thread::Current());
2177 DCHECK(IsValidHandle(type_handle));
2178 }
2179}
2180
Calin Juravleacf735c2015-02-12 15:25:22 +00002181std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2182 ScopedObjectAccess soa(Thread::Current());
2183 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002184 << " is_valid=" << rhs.IsValid()
2185 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002186 << " is_exact=" << rhs.IsExact()
2187 << " ]";
2188 return os;
2189}
2190
Mark Mendellc4701932015-04-10 13:18:51 -04002191bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2192 // For now, assume that instructions in different blocks may use the
2193 // environment.
2194 // TODO: Use the control flow to decide if this is true.
2195 if (GetBlock() != other->GetBlock()) {
2196 return true;
2197 }
2198
2199 // We know that we are in the same block. Walk from 'this' to 'other',
2200 // checking to see if there is any instruction with an environment.
2201 HInstruction* current = this;
2202 for (; current != other && current != nullptr; current = current->GetNext()) {
2203 // This is a conservative check, as the instruction result may not be in
2204 // the referenced environment.
2205 if (current->HasEnvironment()) {
2206 return true;
2207 }
2208 }
2209
2210 // We should have been called with 'this' before 'other' in the block.
2211 // Just confirm this.
2212 DCHECK(current != nullptr);
2213 return false;
2214}
2215
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002216void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002217 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2218 IntrinsicSideEffects side_effects,
2219 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002220 intrinsic_ = intrinsic;
2221 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002222
Aart Bik5d75afe2015-12-14 11:57:01 -08002223 // Adjust method's side effects from intrinsic table.
2224 switch (side_effects) {
2225 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2226 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2227 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2228 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2229 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002230
2231 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2232 opt.SetDoesNotNeedDexCache();
2233 opt.SetDoesNotNeedEnvironment();
2234 } else {
2235 // If we need an environment, that means there will be a call, which can trigger GC.
2236 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2237 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002238 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002239 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002240}
2241
David Brazdil6de19382016-01-08 17:37:10 +00002242bool HNewInstance::IsStringAlloc() const {
2243 ScopedObjectAccess soa(Thread::Current());
2244 return GetReferenceTypeInfo().IsStringClass();
2245}
2246
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002247bool HInvoke::NeedsEnvironment() const {
2248 if (!IsIntrinsic()) {
2249 return true;
2250 }
2251 IntrinsicOptimizations opt(*this);
2252 return !opt.GetDoesNotNeedEnvironment();
2253}
2254
Vladimir Markodc151b22015-10-15 18:02:30 +01002255bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2256 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002257 return false;
2258 }
2259 if (!IsIntrinsic()) {
2260 return true;
2261 }
2262 IntrinsicOptimizations opt(*this);
2263 return !opt.GetDoesNotNeedDexCache();
2264}
2265
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002266void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2267 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2268 input->AddUseAt(this, index);
2269 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2270 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2271 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2272 InputRecordAt(i).GetUseNode()->SetIndex(i);
2273 }
2274}
2275
Vladimir Markob554b5a2015-11-06 12:57:55 +00002276void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2277 RemoveAsUserOfInput(index);
2278 inputs_.erase(inputs_.begin() + index);
2279 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2280 for (size_t i = index, e = InputCount(); i < e; ++i) {
2281 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2282 InputRecordAt(i).GetUseNode()->SetIndex(i);
2283 }
2284}
2285
Vladimir Markof64242a2015-12-01 14:58:23 +00002286std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2287 switch (rhs) {
2288 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2289 return os << "string_init";
2290 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2291 return os << "recursive";
2292 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2293 return os << "direct";
2294 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2295 return os << "direct_fixup";
2296 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2297 return os << "dex_cache_pc_relative";
2298 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2299 return os << "dex_cache_via_method";
2300 default:
2301 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2302 UNREACHABLE();
2303 }
2304}
2305
Vladimir Markofbb184a2015-11-13 14:47:00 +00002306std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2307 switch (rhs) {
2308 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2309 return os << "explicit";
2310 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2311 return os << "implicit";
2312 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2313 return os << "none";
2314 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002315 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2316 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002317 }
2318}
2319
Mark Mendellc4701932015-04-10 13:18:51 -04002320void HInstruction::RemoveEnvironmentUsers() {
2321 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2322 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2323 HEnvironment* user = user_node->GetUser();
2324 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2325 }
2326 env_uses_.Clear();
2327}
2328
Mark Mendellf6529172015-11-17 11:16:56 -05002329// Returns an instruction with the opposite boolean value from 'cond'.
2330HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2331 ArenaAllocator* allocator = GetArena();
2332
2333 if (cond->IsCondition() &&
2334 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2335 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2336 HInstruction* lhs = cond->InputAt(0);
2337 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002338 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002339 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2340 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2341 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2342 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2343 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2344 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2345 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2346 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2347 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2348 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2349 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002350 default:
2351 LOG(FATAL) << "Unexpected condition";
2352 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002353 }
2354 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2355 return replacement;
2356 } else if (cond->IsIntConstant()) {
2357 HIntConstant* int_const = cond->AsIntConstant();
2358 if (int_const->IsZero()) {
2359 return GetIntConstant(1);
2360 } else {
2361 DCHECK(int_const->IsOne());
2362 return GetIntConstant(0);
2363 }
2364 } else {
2365 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2366 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2367 return replacement;
2368 }
2369}
2370
Roland Levillainc9285912015-12-18 10:38:42 +00002371std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2372 os << "["
2373 << " source=" << rhs.GetSource()
2374 << " destination=" << rhs.GetDestination()
2375 << " type=" << rhs.GetType()
2376 << " instruction=";
2377 if (rhs.GetInstruction() != nullptr) {
2378 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2379 } else {
2380 os << "null";
2381 }
2382 os << " ]";
2383 return os;
2384}
2385
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002386} // namespace art