blob: f2698859076021d4b2e06a391324b6764b3482ce [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 {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000650 if (header_->GetGraph()->IsCompilingOsr()) {
651 irreducible_ = true;
652 header_->GetGraph()->SetHasIrreducibleLoops(true);
653 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000654 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100655 }
David Brazdila4b8c212015-05-07 09:59:30 +0100656 }
657}
658
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100659HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000660 HBasicBlock* block = header_->GetPredecessors()[0];
661 DCHECK(irreducible_ || (block == header_->GetDominator()));
662 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100663}
664
665bool HLoopInformation::Contains(const HBasicBlock& block) const {
666 return blocks_.IsBitSet(block.GetBlockId());
667}
668
669bool HLoopInformation::IsIn(const HLoopInformation& other) const {
670 return other.blocks_.IsBitSet(header_->GetBlockId());
671}
672
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800673bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
674 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700675}
676
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100677size_t HLoopInformation::GetLifetimeEnd() const {
678 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100679 for (HBasicBlock* back_edge : GetBackEdges()) {
680 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100681 }
682 return last_position;
683}
684
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100685bool HBasicBlock::Dominates(HBasicBlock* other) const {
686 // Walk up the dominator tree from `other`, to find out if `this`
687 // is an ancestor.
688 HBasicBlock* current = other;
689 while (current != nullptr) {
690 if (current == this) {
691 return true;
692 }
693 current = current->GetDominator();
694 }
695 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100696}
697
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100698static void UpdateInputsUsers(HInstruction* instruction) {
699 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
700 instruction->InputAt(i)->AddUseAt(instruction, i);
701 }
702 // Environment should be created later.
703 DCHECK(!instruction->HasEnvironment());
704}
705
Roland Levillainccc07a92014-09-16 14:48:16 +0100706void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
707 HInstruction* replacement) {
708 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400709 if (initial->IsControlFlow()) {
710 // We can only replace a control flow instruction with another control flow instruction.
711 DCHECK(replacement->IsControlFlow());
712 DCHECK_EQ(replacement->GetId(), -1);
713 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
714 DCHECK_EQ(initial->GetBlock(), this);
715 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
716 DCHECK(initial->GetUses().IsEmpty());
717 DCHECK(initial->GetEnvUses().IsEmpty());
718 replacement->SetBlock(this);
719 replacement->SetId(GetGraph()->GetNextInstructionId());
720 instructions_.InsertInstructionBefore(replacement, initial);
721 UpdateInputsUsers(replacement);
722 } else {
723 InsertInstructionBefore(replacement, initial);
724 initial->ReplaceWith(replacement);
725 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100726 RemoveInstruction(initial);
727}
728
David Brazdil74eb1b22015-12-14 11:44:01 +0000729void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
730 DCHECK(!cursor->IsPhi());
731 DCHECK(!insn->IsPhi());
732 DCHECK(!insn->IsControlFlow());
733 DCHECK(insn->CanBeMoved());
734 DCHECK(!insn->HasSideEffects());
735
736 HBasicBlock* from_block = insn->GetBlock();
737 HBasicBlock* to_block = cursor->GetBlock();
738 DCHECK(from_block != to_block);
739
740 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
741 insn->SetBlock(to_block);
742 to_block->instructions_.InsertInstructionBefore(insn, cursor);
743}
744
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100745static void Add(HInstructionList* instruction_list,
746 HBasicBlock* block,
747 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000748 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000749 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100750 instruction->SetBlock(block);
751 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100752 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100753 instruction_list->AddInstruction(instruction);
754}
755
756void HBasicBlock::AddInstruction(HInstruction* instruction) {
757 Add(&instructions_, this, instruction);
758}
759
760void HBasicBlock::AddPhi(HPhi* phi) {
761 Add(&phis_, this, phi);
762}
763
David Brazdilc3d743f2015-04-22 13:40:50 +0100764void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
765 DCHECK(!cursor->IsPhi());
766 DCHECK(!instruction->IsPhi());
767 DCHECK_EQ(instruction->GetId(), -1);
768 DCHECK_NE(cursor->GetId(), -1);
769 DCHECK_EQ(cursor->GetBlock(), this);
770 DCHECK(!instruction->IsControlFlow());
771 instruction->SetBlock(this);
772 instruction->SetId(GetGraph()->GetNextInstructionId());
773 UpdateInputsUsers(instruction);
774 instructions_.InsertInstructionBefore(instruction, cursor);
775}
776
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100777void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
778 DCHECK(!cursor->IsPhi());
779 DCHECK(!instruction->IsPhi());
780 DCHECK_EQ(instruction->GetId(), -1);
781 DCHECK_NE(cursor->GetId(), -1);
782 DCHECK_EQ(cursor->GetBlock(), this);
783 DCHECK(!instruction->IsControlFlow());
784 DCHECK(!cursor->IsControlFlow());
785 instruction->SetBlock(this);
786 instruction->SetId(GetGraph()->GetNextInstructionId());
787 UpdateInputsUsers(instruction);
788 instructions_.InsertInstructionAfter(instruction, cursor);
789}
790
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100791void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
792 DCHECK_EQ(phi->GetId(), -1);
793 DCHECK_NE(cursor->GetId(), -1);
794 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100795 phi->SetBlock(this);
796 phi->SetId(GetGraph()->GetNextInstructionId());
797 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100798 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100799}
800
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100801static void Remove(HInstructionList* instruction_list,
802 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000803 HInstruction* instruction,
804 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100805 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100806 instruction->SetBlock(nullptr);
807 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000808 if (ensure_safety) {
809 DCHECK(instruction->GetUses().IsEmpty());
810 DCHECK(instruction->GetEnvUses().IsEmpty());
811 RemoveAsUser(instruction);
812 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100813}
814
David Brazdil1abb4192015-02-17 18:33:36 +0000815void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100816 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000817 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100818}
819
David Brazdil1abb4192015-02-17 18:33:36 +0000820void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
821 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100822}
823
David Brazdilc7508e92015-04-27 13:28:57 +0100824void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
825 if (instruction->IsPhi()) {
826 RemovePhi(instruction->AsPhi(), ensure_safety);
827 } else {
828 RemoveInstruction(instruction, ensure_safety);
829 }
830}
831
Vladimir Marko71bf8092015-09-15 15:33:14 +0100832void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
833 for (size_t i = 0; i < locals.size(); i++) {
834 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100835 SetRawEnvAt(i, instruction);
836 if (instruction != nullptr) {
837 instruction->AddEnvUseAt(this, i);
838 }
839 }
840}
841
David Brazdiled596192015-01-23 10:39:45 +0000842void HEnvironment::CopyFrom(HEnvironment* env) {
843 for (size_t i = 0; i < env->Size(); i++) {
844 HInstruction* instruction = env->GetInstructionAt(i);
845 SetRawEnvAt(i, instruction);
846 if (instruction != nullptr) {
847 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100848 }
David Brazdiled596192015-01-23 10:39:45 +0000849 }
850}
851
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700852void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
853 HBasicBlock* loop_header) {
854 DCHECK(loop_header->IsLoopHeader());
855 for (size_t i = 0; i < env->Size(); i++) {
856 HInstruction* instruction = env->GetInstructionAt(i);
857 SetRawEnvAt(i, instruction);
858 if (instruction == nullptr) {
859 continue;
860 }
861 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
862 // At the end of the loop pre-header, the corresponding value for instruction
863 // is the first input of the phi.
864 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700865 SetRawEnvAt(i, initial);
866 initial->AddEnvUseAt(this, i);
867 } else {
868 instruction->AddEnvUseAt(this, i);
869 }
870 }
871}
872
David Brazdil1abb4192015-02-17 18:33:36 +0000873void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100874 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000875 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100876}
877
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000878HInstruction::InstructionKind HInstruction::GetKind() const {
879 return GetKindInternal();
880}
881
Calin Juravle77520bc2015-01-12 18:45:46 +0000882HInstruction* HInstruction::GetNextDisregardingMoves() const {
883 HInstruction* next = GetNext();
884 while (next != nullptr && next->IsParallelMove()) {
885 next = next->GetNext();
886 }
887 return next;
888}
889
890HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
891 HInstruction* previous = GetPrevious();
892 while (previous != nullptr && previous->IsParallelMove()) {
893 previous = previous->GetPrevious();
894 }
895 return previous;
896}
897
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100898void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000899 if (first_instruction_ == nullptr) {
900 DCHECK(last_instruction_ == nullptr);
901 first_instruction_ = last_instruction_ = instruction;
902 } else {
903 last_instruction_->next_ = instruction;
904 instruction->previous_ = last_instruction_;
905 last_instruction_ = instruction;
906 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000907}
908
David Brazdilc3d743f2015-04-22 13:40:50 +0100909void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
910 DCHECK(Contains(cursor));
911 if (cursor == first_instruction_) {
912 cursor->previous_ = instruction;
913 instruction->next_ = cursor;
914 first_instruction_ = instruction;
915 } else {
916 instruction->previous_ = cursor->previous_;
917 instruction->next_ = cursor;
918 cursor->previous_ = instruction;
919 instruction->previous_->next_ = instruction;
920 }
921}
922
923void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
924 DCHECK(Contains(cursor));
925 if (cursor == last_instruction_) {
926 cursor->next_ = instruction;
927 instruction->previous_ = cursor;
928 last_instruction_ = instruction;
929 } else {
930 instruction->next_ = cursor->next_;
931 instruction->previous_ = cursor;
932 cursor->next_ = instruction;
933 instruction->next_->previous_ = instruction;
934 }
935}
936
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100937void HInstructionList::RemoveInstruction(HInstruction* instruction) {
938 if (instruction->previous_ != nullptr) {
939 instruction->previous_->next_ = instruction->next_;
940 }
941 if (instruction->next_ != nullptr) {
942 instruction->next_->previous_ = instruction->previous_;
943 }
944 if (instruction == first_instruction_) {
945 first_instruction_ = instruction->next_;
946 }
947 if (instruction == last_instruction_) {
948 last_instruction_ = instruction->previous_;
949 }
950}
951
Roland Levillain6b469232014-09-25 10:10:38 +0100952bool HInstructionList::Contains(HInstruction* instruction) const {
953 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
954 if (it.Current() == instruction) {
955 return true;
956 }
957 }
958 return false;
959}
960
Roland Levillainccc07a92014-09-16 14:48:16 +0100961bool HInstructionList::FoundBefore(const HInstruction* instruction1,
962 const HInstruction* instruction2) const {
963 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
964 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
965 if (it.Current() == instruction1) {
966 return true;
967 }
968 if (it.Current() == instruction2) {
969 return false;
970 }
971 }
972 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
973 return true;
974}
975
Roland Levillain6c82d402014-10-13 16:10:27 +0100976bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
977 if (other_instruction == this) {
978 // An instruction does not strictly dominate itself.
979 return false;
980 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100981 HBasicBlock* block = GetBlock();
982 HBasicBlock* other_block = other_instruction->GetBlock();
983 if (block != other_block) {
984 return GetBlock()->Dominates(other_instruction->GetBlock());
985 } else {
986 // If both instructions are in the same block, ensure this
987 // instruction comes before `other_instruction`.
988 if (IsPhi()) {
989 if (!other_instruction->IsPhi()) {
990 // Phis appear before non phi-instructions so this instruction
991 // dominates `other_instruction`.
992 return true;
993 } else {
994 // There is no order among phis.
995 LOG(FATAL) << "There is no dominance between phis of a same block.";
996 return false;
997 }
998 } else {
999 // `this` is not a phi.
1000 if (other_instruction->IsPhi()) {
1001 // Phis appear before non phi-instructions so this instruction
1002 // does not dominate `other_instruction`.
1003 return false;
1004 } else {
1005 // Check whether this instruction comes before
1006 // `other_instruction` in the instruction list.
1007 return block->GetInstructions().FoundBefore(this, other_instruction);
1008 }
1009 }
1010 }
1011}
1012
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001013void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001014 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +00001015 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
1016 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001017 HInstruction* user = current->GetUser();
1018 size_t input_index = current->GetIndex();
1019 user->SetRawInputAt(input_index, other);
1020 other->AddUseAt(user, input_index);
1021 }
1022
David Brazdiled596192015-01-23 10:39:45 +00001023 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
1024 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001025 HEnvironment* user = current->GetUser();
1026 size_t input_index = current->GetIndex();
1027 user->SetRawEnvAt(input_index, other);
1028 other->AddEnvUseAt(user, input_index);
1029 }
1030
David Brazdiled596192015-01-23 10:39:45 +00001031 uses_.Clear();
1032 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001033}
1034
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001035void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +00001036 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001037 SetRawInputAt(index, replacement);
1038 replacement->AddUseAt(this, index);
1039}
1040
Nicolas Geoffray39468442014-09-02 15:17:15 +01001041size_t HInstruction::EnvironmentSize() const {
1042 return HasEnvironment() ? environment_->Size() : 0;
1043}
1044
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001045void HPhi::AddInput(HInstruction* input) {
1046 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001047 inputs_.push_back(HUserRecord<HInstruction*>(input));
1048 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001049}
1050
David Brazdil2d7352b2015-04-20 14:52:42 +01001051void HPhi::RemoveInputAt(size_t index) {
1052 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001053 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001054 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001055 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001056 InputRecordAt(i).GetUseNode()->SetIndex(i);
1057 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001058}
1059
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001060#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001061void H##name::Accept(HGraphVisitor* visitor) { \
1062 visitor->Visit##name(this); \
1063}
1064
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001065FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001066
1067#undef DEFINE_ACCEPT
1068
1069void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001070 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1071 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001072 if (block != nullptr) {
1073 VisitBasicBlock(block);
1074 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001075 }
1076}
1077
Roland Levillain633021e2014-10-01 14:12:25 +01001078void HGraphVisitor::VisitReversePostOrder() {
1079 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1080 VisitBasicBlock(it.Current());
1081 }
1082}
1083
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001084void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001085 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001086 it.Current()->Accept(this);
1087 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001088 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001089 it.Current()->Accept(this);
1090 }
1091}
1092
Mark Mendelle82549b2015-05-06 10:55:34 -04001093HConstant* HTypeConversion::TryStaticEvaluation() const {
1094 HGraph* graph = GetBlock()->GetGraph();
1095 if (GetInput()->IsIntConstant()) {
1096 int32_t value = GetInput()->AsIntConstant()->GetValue();
1097 switch (GetResultType()) {
1098 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001099 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001100 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001101 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001102 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001103 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001104 default:
1105 return nullptr;
1106 }
1107 } else if (GetInput()->IsLongConstant()) {
1108 int64_t value = GetInput()->AsLongConstant()->GetValue();
1109 switch (GetResultType()) {
1110 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001111 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001112 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001113 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001114 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001115 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001116 default:
1117 return nullptr;
1118 }
1119 } else if (GetInput()->IsFloatConstant()) {
1120 float value = GetInput()->AsFloatConstant()->GetValue();
1121 switch (GetResultType()) {
1122 case Primitive::kPrimInt:
1123 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001124 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001125 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001126 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001127 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001128 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1129 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001130 case Primitive::kPrimLong:
1131 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001132 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001133 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001134 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001135 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001136 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1137 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001138 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001139 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001140 default:
1141 return nullptr;
1142 }
1143 } else if (GetInput()->IsDoubleConstant()) {
1144 double value = GetInput()->AsDoubleConstant()->GetValue();
1145 switch (GetResultType()) {
1146 case Primitive::kPrimInt:
1147 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001148 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001149 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001150 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001151 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001152 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1153 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001154 case Primitive::kPrimLong:
1155 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001156 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001157 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001158 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001159 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001160 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1161 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001162 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001163 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001164 default:
1165 return nullptr;
1166 }
1167 }
1168 return nullptr;
1169}
1170
Roland Levillain9240d6a2014-10-20 16:47:04 +01001171HConstant* HUnaryOperation::TryStaticEvaluation() const {
1172 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001173 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001174 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001175 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001176 }
1177 return nullptr;
1178}
1179
1180HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001181 if (GetLeft()->IsIntConstant()) {
1182 if (GetRight()->IsIntConstant()) {
1183 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1184 } else if (GetRight()->IsLongConstant()) {
1185 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1186 }
1187 } else if (GetLeft()->IsLongConstant()) {
1188 if (GetRight()->IsIntConstant()) {
1189 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1190 } else if (GetRight()->IsLongConstant()) {
1191 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001192 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001193 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
1194 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain556c3d12014-09-18 15:25:07 +01001195 }
1196 return nullptr;
1197}
Dave Allison20dfc792014-06-16 20:44:29 -07001198
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001199HConstant* HBinaryOperation::GetConstantRight() const {
1200 if (GetRight()->IsConstant()) {
1201 return GetRight()->AsConstant();
1202 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1203 return GetLeft()->AsConstant();
1204 } else {
1205 return nullptr;
1206 }
1207}
1208
1209// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001210// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001211HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1212 HInstruction* most_constant_right = GetConstantRight();
1213 if (most_constant_right == nullptr) {
1214 return nullptr;
1215 } else if (most_constant_right == GetLeft()) {
1216 return GetRight();
1217 } else {
1218 return GetLeft();
1219 }
1220}
1221
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001222bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1223 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001224}
1225
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001226bool HInstruction::Equals(HInstruction* other) const {
1227 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001228 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001229 if (!InstructionDataEquals(other)) return false;
1230 if (GetType() != other->GetType()) return false;
1231 if (InputCount() != other->InputCount()) return false;
1232
1233 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1234 if (InputAt(i) != other->InputAt(i)) return false;
1235 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001236 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001237 return true;
1238}
1239
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001240std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1241#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1242 switch (rhs) {
1243 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1244 default:
1245 os << "Unknown instruction kind " << static_cast<int>(rhs);
1246 break;
1247 }
1248#undef DECLARE_CASE
1249 return os;
1250}
1251
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001252void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001253 next_->previous_ = previous_;
1254 if (previous_ != nullptr) {
1255 previous_->next_ = next_;
1256 }
1257 if (block_->instructions_.first_instruction_ == this) {
1258 block_->instructions_.first_instruction_ = next_;
1259 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001260 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001261
1262 previous_ = cursor->previous_;
1263 if (previous_ != nullptr) {
1264 previous_->next_ = this;
1265 }
1266 next_ = cursor;
1267 cursor->previous_ = this;
1268 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001269
1270 if (block_->instructions_.first_instruction_ == cursor) {
1271 block_->instructions_.first_instruction_ = this;
1272 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001273}
1274
Vladimir Markofb337ea2015-11-25 15:25:10 +00001275void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1276 DCHECK(!CanThrow());
1277 DCHECK(!HasSideEffects());
1278 DCHECK(!HasEnvironmentUses());
1279 DCHECK(HasNonEnvironmentUses());
1280 DCHECK(!IsPhi()); // Makes no sense for Phi.
1281 DCHECK_EQ(InputCount(), 0u);
1282
1283 // Find the target block.
1284 HUseIterator<HInstruction*> uses_it(GetUses());
1285 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1286 uses_it.Advance();
1287 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1288 uses_it.Advance();
1289 }
1290 if (!uses_it.Done()) {
1291 // This instruction has uses in two or more blocks. Find the common dominator.
1292 CommonDominator finder(target_block);
1293 for (; !uses_it.Done(); uses_it.Advance()) {
1294 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1295 }
1296 target_block = finder.Get();
1297 DCHECK(target_block != nullptr);
1298 }
1299 // Move to the first dominator not in a loop.
1300 while (target_block->IsInLoop()) {
1301 target_block = target_block->GetDominator();
1302 DCHECK(target_block != nullptr);
1303 }
1304
1305 // Find insertion position.
1306 HInstruction* insert_pos = nullptr;
1307 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1308 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1309 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1310 insert_pos = uses_it2.Current()->GetUser();
1311 }
1312 }
1313 if (insert_pos == nullptr) {
1314 // No user in `target_block`, insert before the control flow instruction.
1315 insert_pos = target_block->GetLastInstruction();
1316 DCHECK(insert_pos->IsControlFlow());
1317 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1318 if (insert_pos->IsIf()) {
1319 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1320 if (if_input == insert_pos->GetPrevious()) {
1321 insert_pos = if_input;
1322 }
1323 }
1324 }
1325 MoveBefore(insert_pos);
1326}
1327
David Brazdilfc6a86a2015-06-26 10:33:45 +00001328HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001329 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001330 DCHECK_EQ(cursor->GetBlock(), this);
1331
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001332 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1333 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001334 new_block->instructions_.first_instruction_ = cursor;
1335 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1336 instructions_.last_instruction_ = cursor->previous_;
1337 if (cursor->previous_ == nullptr) {
1338 instructions_.first_instruction_ = nullptr;
1339 } else {
1340 cursor->previous_->next_ = nullptr;
1341 cursor->previous_ = nullptr;
1342 }
1343
1344 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001345 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001346
Vladimir Marko60584552015-09-03 13:35:12 +00001347 for (HBasicBlock* successor : GetSuccessors()) {
1348 new_block->successors_.push_back(successor);
1349 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001350 }
Vladimir Marko60584552015-09-03 13:35:12 +00001351 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001352 AddSuccessor(new_block);
1353
David Brazdil56e1acc2015-06-30 15:41:36 +01001354 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001355 return new_block;
1356}
1357
David Brazdild7558da2015-09-22 13:04:14 +01001358HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001359 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001360 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1361
1362 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1363
1364 for (HBasicBlock* predecessor : GetPredecessors()) {
1365 new_block->predecessors_.push_back(predecessor);
1366 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1367 }
1368 predecessors_.clear();
1369 AddPredecessor(new_block);
1370
1371 GetGraph()->AddBlock(new_block);
1372 return new_block;
1373}
1374
David Brazdil9bc43612015-11-05 21:25:24 +00001375HBasicBlock* HBasicBlock::SplitCatchBlockAfterMoveException() {
1376 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
1377 DCHECK(IsCatchBlock()) << "This method is intended for catch blocks only.";
1378
1379 HInstruction* first_insn = GetFirstInstruction();
1380 HInstruction* split_before = nullptr;
1381
1382 if (first_insn != nullptr && first_insn->IsLoadException()) {
1383 // Catch block starts with a LoadException. Split the block after
1384 // the StoreLocal and ClearException which must come after the load.
1385 DCHECK(first_insn->GetNext()->IsStoreLocal());
1386 DCHECK(first_insn->GetNext()->GetNext()->IsClearException());
1387 split_before = first_insn->GetNext()->GetNext()->GetNext();
1388 } else {
1389 // Catch block does not load the exception. Split at the beginning
1390 // to create an empty catch block.
1391 split_before = first_insn;
1392 }
1393
1394 if (split_before == nullptr) {
1395 // Catch block has no instructions after the split point (must be dead).
1396 // Do not split it but rather signal error by returning nullptr.
1397 return nullptr;
1398 } else {
1399 return SplitBefore(split_before);
1400 }
1401}
1402
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001403HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1404 DCHECK(!cursor->IsControlFlow());
1405 DCHECK_NE(instructions_.last_instruction_, cursor);
1406 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001407
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001408 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1409 new_block->instructions_.first_instruction_ = cursor->GetNext();
1410 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1411 cursor->next_->previous_ = nullptr;
1412 cursor->next_ = nullptr;
1413 instructions_.last_instruction_ = cursor;
1414
1415 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001416 for (HBasicBlock* successor : GetSuccessors()) {
1417 new_block->successors_.push_back(successor);
1418 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001419 }
Vladimir Marko60584552015-09-03 13:35:12 +00001420 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001421
Vladimir Marko60584552015-09-03 13:35:12 +00001422 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001423 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001424 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001425 }
Vladimir Marko60584552015-09-03 13:35:12 +00001426 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001427 return new_block;
1428}
1429
David Brazdilec16f792015-08-19 15:04:01 +01001430const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001431 if (EndsWithTryBoundary()) {
1432 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1433 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001434 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001435 return try_boundary;
1436 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001437 DCHECK(IsTryBlock());
1438 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001439 return nullptr;
1440 }
David Brazdilec16f792015-08-19 15:04:01 +01001441 } else if (IsTryBlock()) {
1442 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001443 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001444 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001445 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001446}
1447
David Brazdild7558da2015-09-22 13:04:14 +01001448bool HBasicBlock::HasThrowingInstructions() const {
1449 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1450 if (it.Current()->CanThrow()) {
1451 return true;
1452 }
1453 }
1454 return false;
1455}
1456
David Brazdilfc6a86a2015-06-26 10:33:45 +00001457static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1458 return block.GetPhis().IsEmpty()
1459 && !block.GetInstructions().IsEmpty()
1460 && block.GetFirstInstruction() == block.GetLastInstruction();
1461}
1462
David Brazdil46e2a392015-03-16 17:31:52 +00001463bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001464 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1465}
1466
1467bool HBasicBlock::IsSingleTryBoundary() const {
1468 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001469}
1470
David Brazdil8d5b8b22015-03-24 10:51:52 +00001471bool HBasicBlock::EndsWithControlFlowInstruction() const {
1472 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1473}
1474
David Brazdilb2bd1c52015-03-25 11:17:37 +00001475bool HBasicBlock::EndsWithIf() const {
1476 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1477}
1478
David Brazdilffee3d32015-07-06 11:48:53 +01001479bool HBasicBlock::EndsWithTryBoundary() const {
1480 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1481}
1482
David Brazdilb2bd1c52015-03-25 11:17:37 +00001483bool HBasicBlock::HasSinglePhi() const {
1484 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1485}
1486
David Brazdild26a4112015-11-10 11:07:31 +00001487ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1488 if (EndsWithTryBoundary()) {
1489 // The normal-flow successor of HTryBoundary is always stored at index zero.
1490 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1491 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1492 } else {
1493 // All successors of blocks not ending with TryBoundary are normal.
1494 return ArrayRef<HBasicBlock* const>(successors_);
1495 }
1496}
1497
1498ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1499 if (EndsWithTryBoundary()) {
1500 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1501 } else {
1502 // Blocks not ending with TryBoundary do not have exceptional successors.
1503 return ArrayRef<HBasicBlock* const>();
1504 }
1505}
1506
David Brazdilffee3d32015-07-06 11:48:53 +01001507bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001508 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1509 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1510
1511 size_t length = handlers1.size();
1512 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001513 return false;
1514 }
1515
David Brazdilb618ade2015-07-29 10:31:29 +01001516 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001517 for (size_t i = 0; i < length; ++i) {
1518 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001519 return false;
1520 }
1521 }
1522 return true;
1523}
1524
David Brazdil2d7352b2015-04-20 14:52:42 +01001525size_t HInstructionList::CountSize() const {
1526 size_t size = 0;
1527 HInstruction* current = first_instruction_;
1528 for (; current != nullptr; current = current->GetNext()) {
1529 size++;
1530 }
1531 return size;
1532}
1533
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001534void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1535 for (HInstruction* current = first_instruction_;
1536 current != nullptr;
1537 current = current->GetNext()) {
1538 current->SetBlock(block);
1539 }
1540}
1541
1542void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1543 DCHECK(Contains(cursor));
1544 if (!instruction_list.IsEmpty()) {
1545 if (cursor == last_instruction_) {
1546 last_instruction_ = instruction_list.last_instruction_;
1547 } else {
1548 cursor->next_->previous_ = instruction_list.last_instruction_;
1549 }
1550 instruction_list.last_instruction_->next_ = cursor->next_;
1551 cursor->next_ = instruction_list.first_instruction_;
1552 instruction_list.first_instruction_->previous_ = cursor;
1553 }
1554}
1555
1556void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001557 if (IsEmpty()) {
1558 first_instruction_ = instruction_list.first_instruction_;
1559 last_instruction_ = instruction_list.last_instruction_;
1560 } else {
1561 AddAfter(last_instruction_, instruction_list);
1562 }
1563}
1564
David Brazdil04ff4e82015-12-10 13:54:52 +00001565// Should be called on instructions in a dead block in post order. This method
1566// assumes `insn` has been removed from all users with the exception of catch
1567// phis because of missing exceptional edges in the graph. It removes the
1568// instruction from catch phi uses, together with inputs of other catch phis in
1569// the catch block at the same index, as these must be dead too.
1570static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1571 DCHECK(!insn->HasEnvironmentUses());
1572 while (insn->HasNonEnvironmentUses()) {
1573 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1574 size_t use_index = use->GetIndex();
1575 HBasicBlock* user_block = use->GetUser()->GetBlock();
1576 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1577 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1578 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1579 }
1580 }
1581}
1582
David Brazdil2d7352b2015-04-20 14:52:42 +01001583void HBasicBlock::DisconnectAndDelete() {
1584 // Dominators must be removed after all the blocks they dominate. This way
1585 // a loop header is removed last, a requirement for correct loop information
1586 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001587 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001588
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001589 // (1) Remove the block from all loops it is included in.
David Brazdil2d7352b2015-04-20 14:52:42 +01001590 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1591 HLoopInformation* loop_info = it.Current();
1592 loop_info->Remove(this);
1593 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001594 // If this was the last back edge of the loop, we deliberately leave the
1595 // loop in an inconsistent state and will fail SSAChecker unless the
1596 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001597 loop_info->RemoveBackEdge(this);
1598 }
1599 }
1600
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001601 // (2) Disconnect the block from its predecessors and update their
1602 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001603 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001604 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001605 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1606 // This block is the only normal-flow successor of the TryBoundary which
1607 // makes `predecessor` dead. Since DCE removes blocks in post order,
1608 // exception handlers of this TryBoundary were already visited and any
1609 // remaining handlers therefore must be live. We remove `predecessor` from
1610 // their list of predecessors.
1611 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1612 while (predecessor->GetSuccessors().size() > 1) {
1613 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1614 DCHECK(handler->IsCatchBlock());
1615 predecessor->RemoveSuccessor(handler);
1616 handler->RemovePredecessor(predecessor);
1617 }
1618 }
1619
David Brazdil2d7352b2015-04-20 14:52:42 +01001620 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001621 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1622 if (num_pred_successors == 1u) {
1623 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001624 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1625 // successor. Replace those with a HGoto.
1626 DCHECK(last_instruction->IsIf() ||
1627 last_instruction->IsPackedSwitch() ||
1628 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001629 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001630 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001631 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001632 // The predecessor has no remaining successors and therefore must be dead.
1633 // We deliberately leave it without a control-flow instruction so that the
1634 // SSAChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001635 predecessor->RemoveInstruction(last_instruction);
1636 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001637 // There are multiple successors left. The removed block might be a successor
1638 // of a PackedSwitch which will be completely removed (perhaps replaced with
1639 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1640 // case, leave `last_instruction` as is for now.
1641 DCHECK(last_instruction->IsPackedSwitch() ||
1642 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001643 }
David Brazdil46e2a392015-03-16 17:31:52 +00001644 }
Vladimir Marko60584552015-09-03 13:35:12 +00001645 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001646
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001647 // (3) Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001648 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001649 // Delete this block from the list of predecessors.
1650 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001651 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001652
1653 // Check that `successor` has other predecessors, otherwise `this` is the
1654 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001655 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001656
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001657 // Remove this block's entries in the successor's phis. Skip exceptional
1658 // successors because catch phi inputs do not correspond to predecessor
1659 // blocks but throwing instructions. Their inputs will be updated in step (4).
1660 if (!successor->IsCatchBlock()) {
1661 if (successor->predecessors_.size() == 1u) {
1662 // The successor has just one predecessor left. Replace phis with the only
1663 // remaining input.
1664 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1665 HPhi* phi = phi_it.Current()->AsPhi();
1666 phi->ReplaceWith(phi->InputAt(1 - this_index));
1667 successor->RemovePhi(phi);
1668 }
1669 } else {
1670 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1671 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1672 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001673 }
1674 }
1675 }
Vladimir Marko60584552015-09-03 13:35:12 +00001676 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001677
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001678 // (4) Remove instructions and phis. Instructions should have no remaining uses
1679 // except in catch phis. If an instruction is used by a catch phi at `index`,
1680 // remove `index`-th input of all phis in the catch block since they are
1681 // guaranteed dead. Note that we may miss dead inputs this way but the
1682 // graph will always remain consistent.
1683 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1684 HInstruction* insn = it.Current();
David Brazdil04ff4e82015-12-10 13:54:52 +00001685 RemoveUsesOfDeadInstruction(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001686 RemoveInstruction(insn);
1687 }
1688 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
David Brazdil04ff4e82015-12-10 13:54:52 +00001689 HPhi* insn = it.Current()->AsPhi();
1690 RemoveUsesOfDeadInstruction(insn);
1691 RemovePhi(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001692 }
1693
David Brazdil2d7352b2015-04-20 14:52:42 +01001694 // Disconnect from the dominator.
1695 dominator_->RemoveDominatedBlock(this);
1696 SetDominator(nullptr);
1697
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001698 // Delete from the graph, update reverse post order.
1699 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001700 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001701}
1702
1703void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001704 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001705 DCHECK(ContainsElement(dominated_blocks_, other));
1706 DCHECK_EQ(GetSingleSuccessor(), other);
1707 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001708 DCHECK(other->GetPhis().IsEmpty());
1709
David Brazdil2d7352b2015-04-20 14:52:42 +01001710 // Move instructions from `other` to `this`.
1711 DCHECK(EndsWithControlFlowInstruction());
1712 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001713 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001714 other->instructions_.SetBlockOfInstructions(this);
1715 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001716
David Brazdil2d7352b2015-04-20 14:52:42 +01001717 // Remove `other` from the loops it is included in.
1718 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1719 HLoopInformation* loop_info = it.Current();
1720 loop_info->Remove(other);
1721 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001722 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001723 }
1724 }
1725
1726 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001727 successors_.clear();
1728 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001729 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001730 successor->ReplacePredecessor(other, this);
1731 }
1732
David Brazdil2d7352b2015-04-20 14:52:42 +01001733 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001734 RemoveDominatedBlock(other);
1735 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1736 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001737 dominated->SetDominator(this);
1738 }
Vladimir Marko60584552015-09-03 13:35:12 +00001739 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001740 other->dominator_ = nullptr;
1741
1742 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001743 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001744
1745 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001746 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001747 other->SetGraph(nullptr);
1748}
1749
1750void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1751 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001752 DCHECK(GetDominatedBlocks().empty());
1753 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001754 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001755 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001756 DCHECK(other->GetPhis().IsEmpty());
1757 DCHECK(!other->IsInLoop());
1758
1759 // Move instructions from `other` to `this`.
1760 instructions_.Add(other->GetInstructions());
1761 other->instructions_.SetBlockOfInstructions(this);
1762
1763 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001764 successors_.clear();
1765 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001766 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001767 successor->ReplacePredecessor(other, this);
1768 }
1769
1770 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001771 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1772 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001773 dominated->SetDominator(this);
1774 }
Vladimir Marko60584552015-09-03 13:35:12 +00001775 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001776 other->dominator_ = nullptr;
1777 other->graph_ = nullptr;
1778}
1779
1780void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001781 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001782 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001783 predecessor->ReplaceSuccessor(this, other);
1784 }
Vladimir Marko60584552015-09-03 13:35:12 +00001785 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001786 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001787 successor->ReplacePredecessor(this, other);
1788 }
Vladimir Marko60584552015-09-03 13:35:12 +00001789 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1790 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001791 }
1792 GetDominator()->ReplaceDominatedBlock(this, other);
1793 other->SetDominator(GetDominator());
1794 dominator_ = nullptr;
1795 graph_ = nullptr;
1796}
1797
1798// Create space in `blocks` for adding `number_of_new_blocks` entries
1799// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001800static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001801 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001802 size_t after) {
1803 DCHECK_LT(after, blocks->size());
1804 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001805 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001806 blocks->resize(new_size);
1807 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001808}
1809
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001810void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001811 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001812 DCHECK(block->GetSuccessors().empty());
1813 DCHECK(block->GetPredecessors().empty());
1814 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001815 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001816 DCHECK(block->GetInstructions().IsEmpty());
1817 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001818
David Brazdilc7af85d2015-05-26 12:05:55 +01001819 if (block->IsExitBlock()) {
1820 exit_block_ = nullptr;
1821 }
1822
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001823 RemoveElement(reverse_post_order_, block);
1824 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001825}
1826
Calin Juravle2e768302015-07-28 14:41:11 +00001827HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001828 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001829 // Update the environments in this graph to have the invoke's environment
1830 // as parent.
1831 {
1832 HReversePostOrderIterator it(*this);
1833 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1834 for (; !it.Done(); it.Advance()) {
1835 HBasicBlock* block = it.Current();
1836 for (HInstructionIterator instr_it(block->GetInstructions());
1837 !instr_it.Done();
1838 instr_it.Advance()) {
1839 HInstruction* current = instr_it.Current();
1840 if (current->NeedsEnvironment()) {
1841 current->GetEnvironment()->SetAndCopyParentChain(
1842 outer_graph->GetArena(), invoke->GetEnvironment());
1843 }
1844 }
1845 }
1846 }
1847 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1848 if (HasBoundsChecks()) {
1849 outer_graph->SetHasBoundsChecks(true);
1850 }
1851
Calin Juravle2e768302015-07-28 14:41:11 +00001852 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001853 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001854 // Simple case of an entry block, a body block, and an exit block.
1855 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001856 HBasicBlock* body = GetBlocks()[1];
1857 DCHECK(GetBlocks()[0]->IsEntryBlock());
1858 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001859 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001860 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001861 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001862
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001863 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1864 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001865
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001866 // Replace the invoke with the return value of the inlined graph.
1867 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001868 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001869 } else {
1870 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001871 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001872
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001873 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001874 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001875 // Need to inline multiple blocks. We split `invoke`'s block
1876 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001877 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001878 // with the second half.
1879 ArenaAllocator* allocator = outer_graph->GetArena();
1880 HBasicBlock* at = invoke->GetBlock();
1881 HBasicBlock* to = at->SplitAfter(invoke);
1882
Vladimir Markoec7802a2015-10-01 20:57:57 +01001883 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001884 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001885 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001886 exit_block_->ReplaceWith(to);
1887
1888 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001889 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001890 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001891 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001892 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001893 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001894 if (!returns_void) {
1895 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001896 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001897 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001898 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001899 } else {
1900 if (!returns_void) {
1901 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001902 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001903 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001904 to->AddPhi(return_value->AsPhi());
1905 }
Vladimir Marko60584552015-09-03 13:35:12 +00001906 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001907 HInstruction* last = predecessor->GetLastInstruction();
1908 if (!returns_void) {
1909 return_value->AsPhi()->AddInput(last->InputAt(0));
1910 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001911 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001912 predecessor->RemoveInstruction(last);
1913 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001914 }
1915
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001916 // Update the meta information surrounding blocks:
1917 // (1) the graph they are now in,
1918 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001919 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05001920 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001921 // Note that we do not need to update catch phi inputs because they
1922 // correspond to the register file of the outer method which the inlinee
1923 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001924
1925 // We don't add the entry block, the exit block, and the first block, which
1926 // has been merged with `at`.
1927 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1928
1929 // We add the `to` block.
1930 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001931 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001932 + kNumberOfNewBlocksInCaller;
1933
1934 // Find the location of `at` in the outer graph's reverse post order. The new
1935 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001936 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001937 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1938
David Brazdil95177982015-10-30 12:56:58 -05001939 HLoopInformation* loop_info = at->GetLoopInformation();
1940 // Copy TryCatchInformation if `at` is a try block, not if it is a catch block.
1941 TryCatchInformation* try_catch_info = at->IsTryBlock() ? at->GetTryCatchInformation() : nullptr;
1942
1943 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1944 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001945 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1946 HBasicBlock* current = it.Current();
1947 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05001948 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001949 DCHECK(current->GetGraph() == this);
1950 current->SetGraph(outer_graph);
1951 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001952 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001953 if (!current->IsInLoop()) {
David Brazdil95177982015-10-30 12:56:58 -05001954 current->SetLoopInformation(loop_info);
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001955 } else if (current->IsLoopHeader()) {
1956 // Clear the information of which blocks are contained in that loop. Since the
1957 // information is stored as a bit vector based on block ids, we have to update
1958 // it, as those block ids were specific to the callee graph and we are now adding
1959 // these blocks to the caller graph.
1960 current->GetLoopInformation()->ClearAllBlocks();
1961 }
1962 if (current->IsInLoop()) {
1963 for (HLoopInformationOutwardIterator loop_it(*current);
1964 !loop_it.Done();
1965 loop_it.Advance()) {
David Brazdil7d275372015-04-21 16:36:35 +01001966 loop_it.Current()->Add(current);
1967 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001968 }
David Brazdil95177982015-10-30 12:56:58 -05001969 current->SetTryCatchInformation(try_catch_info);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001970 }
1971 }
1972
David Brazdil95177982015-10-30 12:56:58 -05001973 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001974 to->SetGraph(outer_graph);
1975 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001976 outer_graph->reverse_post_order_[++index_of_at] = to;
David Brazdil95177982015-10-30 12:56:58 -05001977 if (loop_info != nullptr) {
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001978 if (!to->IsInLoop()) {
1979 to->SetLoopInformation(loop_info);
1980 }
David Brazdil7d275372015-04-21 16:36:35 +01001981 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1982 loop_it.Current()->Add(to);
1983 }
David Brazdil95177982015-10-30 12:56:58 -05001984 if (loop_info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001985 // Only `to` can become a back edge, as the inlined blocks
1986 // are predecessors of `to`.
David Brazdil95177982015-10-30 12:56:58 -05001987 loop_info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001988 }
1989 }
David Brazdil95177982015-10-30 12:56:58 -05001990 to->SetTryCatchInformation(try_catch_info);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001991 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001992
David Brazdil05144f42015-04-16 15:18:00 +01001993 // Update the next instruction id of the outer graph, so that instructions
1994 // added later get bigger ids than those in the inner graph.
1995 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1996
1997 // Walk over the entry block and:
1998 // - Move constants from the entry block to the outer_graph's entry block,
1999 // - Replace HParameterValue instructions with their real value.
2000 // - Remove suspend checks, that hold an environment.
2001 // We must do this after the other blocks have been inlined, otherwise ids of
2002 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002003 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002004 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2005 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002006 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002007 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002008 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002009 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002010 replacement = outer_graph->GetIntConstant(
2011 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002012 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002013 replacement = outer_graph->GetLongConstant(
2014 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002015 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002016 replacement = outer_graph->GetFloatConstant(
2017 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002018 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002019 replacement = outer_graph->GetDoubleConstant(
2020 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002021 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002022 if (kIsDebugBuild
2023 && invoke->IsInvokeStaticOrDirect()
2024 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2025 // Ensure we do not use the last input of `invoke`, as it
2026 // contains a clinit check which is not an actual argument.
2027 size_t last_input_index = invoke->InputCount() - 1;
2028 DCHECK(parameter_index != last_input_index);
2029 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002030 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002031 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002032 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002033 } else {
2034 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2035 entry_block_->RemoveInstruction(current);
2036 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002037 if (replacement != nullptr) {
2038 current->ReplaceWith(replacement);
2039 // If the current is the return value then we need to update the latter.
2040 if (current == return_value) {
2041 DCHECK_EQ(entry_block_, return_value->GetBlock());
2042 return_value = replacement;
2043 }
2044 }
2045 }
2046
2047 if (return_value != nullptr) {
2048 invoke->ReplaceWith(return_value);
David Brazdil05144f42015-04-16 15:18:00 +01002049 }
2050
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002051 // Finally remove the invoke from the caller.
2052 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00002053
2054 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002055}
2056
Mingyao Yang3584bce2015-05-19 16:01:59 -07002057/*
2058 * Loop will be transformed to:
2059 * old_pre_header
2060 * |
2061 * if_block
2062 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002063 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002064 * \ /
2065 * new_pre_header
2066 * |
2067 * header
2068 */
2069void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2070 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002071 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002072
Aart Bik3fc7f352015-11-20 22:03:03 -08002073 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002074 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002075 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2076 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002077 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2078 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002079 AddBlock(true_block);
2080 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002081 AddBlock(new_pre_header);
2082
Aart Bik3fc7f352015-11-20 22:03:03 -08002083 header->ReplacePredecessor(old_pre_header, new_pre_header);
2084 old_pre_header->successors_.clear();
2085 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002086
Aart Bik3fc7f352015-11-20 22:03:03 -08002087 old_pre_header->AddSuccessor(if_block);
2088 if_block->AddSuccessor(true_block); // True successor
2089 if_block->AddSuccessor(false_block); // False successor
2090 true_block->AddSuccessor(new_pre_header);
2091 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002092
Aart Bik3fc7f352015-11-20 22:03:03 -08002093 old_pre_header->dominated_blocks_.push_back(if_block);
2094 if_block->SetDominator(old_pre_header);
2095 if_block->dominated_blocks_.push_back(true_block);
2096 true_block->SetDominator(if_block);
2097 if_block->dominated_blocks_.push_back(false_block);
2098 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002099 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002100 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002101 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002102 header->SetDominator(new_pre_header);
2103
Aart Bik3fc7f352015-11-20 22:03:03 -08002104 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002105 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002106 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002107 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002108 reverse_post_order_[index_of_header++] = true_block;
2109 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002110 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002111
Aart Bik3fc7f352015-11-20 22:03:03 -08002112 // Fix loop information.
2113 HLoopInformation* loop_info = old_pre_header->GetLoopInformation();
2114 if (loop_info != nullptr) {
2115 if_block->SetLoopInformation(loop_info);
2116 true_block->SetLoopInformation(loop_info);
2117 false_block->SetLoopInformation(loop_info);
2118 new_pre_header->SetLoopInformation(loop_info);
2119 // Add blocks to all enveloping loops.
2120 for (HLoopInformationOutwardIterator loop_it(*old_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002121 !loop_it.Done();
2122 loop_it.Advance()) {
2123 loop_it.Current()->Add(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002124 loop_it.Current()->Add(true_block);
2125 loop_it.Current()->Add(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002126 loop_it.Current()->Add(new_pre_header);
2127 }
2128 }
Aart Bik3fc7f352015-11-20 22:03:03 -08002129
2130 // Fix try/catch information.
2131 TryCatchInformation* try_catch_info = old_pre_header->IsTryBlock()
2132 ? old_pre_header->GetTryCatchInformation()
2133 : nullptr;
2134 if_block->SetTryCatchInformation(try_catch_info);
2135 true_block->SetTryCatchInformation(try_catch_info);
2136 false_block->SetTryCatchInformation(try_catch_info);
2137 new_pre_header->SetTryCatchInformation(try_catch_info);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002138}
2139
David Brazdilf5552582015-12-27 13:36:12 +00002140static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2141 SHARED_REQUIRES(Locks::mutator_lock_) {
2142 if (rti.IsValid()) {
2143 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2144 << " upper_bound_rti: " << upper_bound_rti
2145 << " rti: " << rti;
2146 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
2147 }
2148}
2149
Calin Juravle2e768302015-07-28 14:41:11 +00002150void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2151 if (kIsDebugBuild) {
2152 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2153 ScopedObjectAccess soa(Thread::Current());
2154 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2155 if (IsBoundType()) {
2156 // Having the test here spares us from making the method virtual just for
2157 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002158 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002159 }
2160 }
2161 reference_type_info_ = rti;
2162}
2163
David Brazdilf5552582015-12-27 13:36:12 +00002164void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2165 if (kIsDebugBuild) {
2166 ScopedObjectAccess soa(Thread::Current());
2167 DCHECK(upper_bound.IsValid());
2168 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2169 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2170 }
2171 upper_bound_ = upper_bound;
2172 upper_can_be_null_ = can_be_null;
2173}
2174
Calin Juravle2e768302015-07-28 14:41:11 +00002175ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
2176
2177ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
2178 : type_handle_(type_handle), is_exact_(is_exact) {
2179 if (kIsDebugBuild) {
2180 ScopedObjectAccess soa(Thread::Current());
2181 DCHECK(IsValidHandle(type_handle));
2182 }
2183}
2184
Calin Juravleacf735c2015-02-12 15:25:22 +00002185std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2186 ScopedObjectAccess soa(Thread::Current());
2187 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002188 << " is_valid=" << rhs.IsValid()
2189 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002190 << " is_exact=" << rhs.IsExact()
2191 << " ]";
2192 return os;
2193}
2194
Mark Mendellc4701932015-04-10 13:18:51 -04002195bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2196 // For now, assume that instructions in different blocks may use the
2197 // environment.
2198 // TODO: Use the control flow to decide if this is true.
2199 if (GetBlock() != other->GetBlock()) {
2200 return true;
2201 }
2202
2203 // We know that we are in the same block. Walk from 'this' to 'other',
2204 // checking to see if there is any instruction with an environment.
2205 HInstruction* current = this;
2206 for (; current != other && current != nullptr; current = current->GetNext()) {
2207 // This is a conservative check, as the instruction result may not be in
2208 // the referenced environment.
2209 if (current->HasEnvironment()) {
2210 return true;
2211 }
2212 }
2213
2214 // We should have been called with 'this' before 'other' in the block.
2215 // Just confirm this.
2216 DCHECK(current != nullptr);
2217 return false;
2218}
2219
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002220void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002221 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2222 IntrinsicSideEffects side_effects,
2223 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002224 intrinsic_ = intrinsic;
2225 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002226
Aart Bik5d75afe2015-12-14 11:57:01 -08002227 // Adjust method's side effects from intrinsic table.
2228 switch (side_effects) {
2229 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2230 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2231 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2232 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2233 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002234
2235 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2236 opt.SetDoesNotNeedDexCache();
2237 opt.SetDoesNotNeedEnvironment();
2238 } else {
2239 // If we need an environment, that means there will be a call, which can trigger GC.
2240 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2241 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002242 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002243 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002244}
2245
David Brazdil6de19382016-01-08 17:37:10 +00002246bool HNewInstance::IsStringAlloc() const {
2247 ScopedObjectAccess soa(Thread::Current());
2248 return GetReferenceTypeInfo().IsStringClass();
2249}
2250
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002251bool HInvoke::NeedsEnvironment() const {
2252 if (!IsIntrinsic()) {
2253 return true;
2254 }
2255 IntrinsicOptimizations opt(*this);
2256 return !opt.GetDoesNotNeedEnvironment();
2257}
2258
Vladimir Markodc151b22015-10-15 18:02:30 +01002259bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2260 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002261 return false;
2262 }
2263 if (!IsIntrinsic()) {
2264 return true;
2265 }
2266 IntrinsicOptimizations opt(*this);
2267 return !opt.GetDoesNotNeedDexCache();
2268}
2269
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002270void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2271 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2272 input->AddUseAt(this, index);
2273 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2274 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2275 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2276 InputRecordAt(i).GetUseNode()->SetIndex(i);
2277 }
2278}
2279
Vladimir Markob554b5a2015-11-06 12:57:55 +00002280void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2281 RemoveAsUserOfInput(index);
2282 inputs_.erase(inputs_.begin() + index);
2283 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2284 for (size_t i = index, e = InputCount(); i < e; ++i) {
2285 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2286 InputRecordAt(i).GetUseNode()->SetIndex(i);
2287 }
2288}
2289
Vladimir Markof64242a2015-12-01 14:58:23 +00002290std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2291 switch (rhs) {
2292 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2293 return os << "string_init";
2294 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2295 return os << "recursive";
2296 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2297 return os << "direct";
2298 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2299 return os << "direct_fixup";
2300 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2301 return os << "dex_cache_pc_relative";
2302 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2303 return os << "dex_cache_via_method";
2304 default:
2305 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2306 UNREACHABLE();
2307 }
2308}
2309
Vladimir Markofbb184a2015-11-13 14:47:00 +00002310std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2311 switch (rhs) {
2312 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2313 return os << "explicit";
2314 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2315 return os << "implicit";
2316 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2317 return os << "none";
2318 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002319 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2320 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002321 }
2322}
2323
Mark Mendellc4701932015-04-10 13:18:51 -04002324void HInstruction::RemoveEnvironmentUsers() {
2325 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2326 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2327 HEnvironment* user = user_node->GetUser();
2328 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2329 }
2330 env_uses_.Clear();
2331}
2332
Mark Mendellf6529172015-11-17 11:16:56 -05002333// Returns an instruction with the opposite boolean value from 'cond'.
2334HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2335 ArenaAllocator* allocator = GetArena();
2336
2337 if (cond->IsCondition() &&
2338 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2339 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2340 HInstruction* lhs = cond->InputAt(0);
2341 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002342 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002343 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2344 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2345 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2346 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2347 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2348 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2349 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2350 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2351 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2352 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2353 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002354 default:
2355 LOG(FATAL) << "Unexpected condition";
2356 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002357 }
2358 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2359 return replacement;
2360 } else if (cond->IsIntConstant()) {
2361 HIntConstant* int_const = cond->AsIntConstant();
2362 if (int_const->IsZero()) {
2363 return GetIntConstant(1);
2364 } else {
2365 DCHECK(int_const->IsOne());
2366 return GetIntConstant(0);
2367 }
2368 } else {
2369 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2370 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2371 return replacement;
2372 }
2373}
2374
Roland Levillainc9285912015-12-18 10:38:42 +00002375std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2376 os << "["
2377 << " source=" << rhs.GetSource()
2378 << " destination=" << rhs.GetDestination()
2379 << " type=" << rhs.GetType()
2380 << " instruction=";
2381 if (rhs.GetInstruction() != nullptr) {
2382 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2383 } else {
2384 os << "null";
2385 }
2386 os << " ]";
2387 return os;
2388}
2389
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002390} // namespace art