blob: eb9c381c4ec3dac3c7559924df5db5bb462c9ef2 [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
Roland Levillain31dd3d62016-02-16 12:21:02 +000018#include <cfloat>
19
Mark Mendelle82549b2015-05-06 10:55:34 -040020#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000021#include "common_dominator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010022#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010023#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010024#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010025#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010026#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010027#include "mirror/class-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000028#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000029
30namespace art {
31
Roland Levillain31dd3d62016-02-16 12:21:02 +000032// Enable floating-point static evaluation during constant folding
33// only if all floating-point operations and constants evaluate in the
34// range and precision of the type used (i.e., 32-bit float, 64-bit
35// double).
36static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
37
David Brazdilbadd8262016-02-02 16:28:56 +000038void HGraph::InitializeInexactObjectRTI(StackHandleScopeCollection* handles) {
39 ScopedObjectAccess soa(Thread::Current());
40 // Create the inexact Object reference type and store it in the HGraph.
41 ClassLinker* linker = Runtime::Current()->GetClassLinker();
42 inexact_object_rti_ = ReferenceTypeInfo::Create(
43 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
44 /* is_exact */ false);
45}
46
Nicolas Geoffray818f2102014-02-18 16:43:35 +000047void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010048 block->SetBlockId(blocks_.size());
49 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000050}
51
Nicolas Geoffray804d0932014-05-02 08:46:00 +010052void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010053 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
54 DCHECK_EQ(visited->GetHighestBitSet(), -1);
55
56 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markof6a35de2016-03-21 12:01:50 +000057 ArenaBitVector visiting(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010058 // Number of successors visited from a given node, indexed by block id.
59 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
60 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
61 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
62 constexpr size_t kDefaultWorklistSize = 8;
63 worklist.reserve(kDefaultWorklistSize);
64 visited->SetBit(entry_block_->GetBlockId());
65 visiting.SetBit(entry_block_->GetBlockId());
66 worklist.push_back(entry_block_);
67
68 while (!worklist.empty()) {
69 HBasicBlock* current = worklist.back();
70 uint32_t current_id = current->GetBlockId();
71 if (successors_visited[current_id] == current->GetSuccessors().size()) {
72 visiting.ClearBit(current_id);
73 worklist.pop_back();
74 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010075 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
76 uint32_t successor_id = successor->GetBlockId();
77 if (visiting.IsBitSet(successor_id)) {
78 DCHECK(ContainsElement(worklist, successor));
79 successor->AddBackEdge(current);
80 } else if (!visited->IsBitSet(successor_id)) {
81 visited->SetBit(successor_id);
82 visiting.SetBit(successor_id);
83 worklist.push_back(successor);
84 }
85 }
86 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000087}
88
Vladimir Markocac5a7e2016-02-22 10:39:50 +000089static void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010090 for (HEnvironment* environment = instruction->GetEnvironment();
91 environment != nullptr;
92 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000093 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000094 if (environment->GetInstructionAt(i) != nullptr) {
95 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000096 }
97 }
98 }
99}
100
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000101static void RemoveAsUser(HInstruction* instruction) {
102 for (size_t i = 0; i < instruction->InputCount(); i++) {
103 instruction->RemoveAsUserOfInput(i);
104 }
105
106 RemoveEnvironmentUses(instruction);
107}
108
Roland Levillainfc600dc2014-12-02 17:16:31 +0000109void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100110 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000111 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100112 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000113 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100114 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000115 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
116 RemoveAsUser(it.Current());
117 }
118 }
119 }
120}
121
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100122void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100123 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000124 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100125 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000126 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100127 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000128 for (HBasicBlock* successor : block->GetSuccessors()) {
129 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000130 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100131 // Remove the block from the list of blocks, so that further analyses
132 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100133 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600134 if (block->IsExitBlock()) {
135 SetExitBlock(nullptr);
136 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000137 // Mark the block as removed. This is used by the HGraphBuilder to discard
138 // the block as a branch target.
139 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000140 }
141 }
142}
143
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000144GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000145 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000146
David Brazdil86ea7ee2016-02-16 09:26:07 +0000147 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000148 FindBackEdges(&visited);
149
David Brazdil86ea7ee2016-02-16 09:26:07 +0000150 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000151 // the initial DFS as users from other instructions, so that
152 // users can be safely removed before uses later.
153 RemoveInstructionsAsUsersFromDeadBlocks(visited);
154
David Brazdil86ea7ee2016-02-16 09:26:07 +0000155 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000156 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000157 // predecessors list of live blocks.
158 RemoveDeadBlocks(visited);
159
David Brazdil86ea7ee2016-02-16 09:26:07 +0000160 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100161 // dominators and the reverse post order.
162 SimplifyCFG();
163
David Brazdil86ea7ee2016-02-16 09:26:07 +0000164 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100165 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000166
David Brazdil86ea7ee2016-02-16 09:26:07 +0000167 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000168 // set the loop information on each block.
169 GraphAnalysisResult result = AnalyzeLoops();
170 if (result != kAnalysisSuccess) {
171 return result;
172 }
173
David Brazdil86ea7ee2016-02-16 09:26:07 +0000174 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000175 // which needs the information to build catch block phis from values of
176 // locals at throwing instructions inside try blocks.
177 ComputeTryBlockInformation();
178
179 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100180}
181
182void HGraph::ClearDominanceInformation() {
183 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
184 it.Current()->ClearDominanceInformation();
185 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100186 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100187}
188
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000189void HGraph::ClearLoopInformation() {
190 SetHasIrreducibleLoops(false);
191 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000192 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000193 }
194}
195
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100196void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000197 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100198 dominator_ = nullptr;
199}
200
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000201HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
202 HInstruction* instruction = GetFirstInstruction();
203 while (instruction->IsParallelMove()) {
204 instruction = instruction->GetNext();
205 }
206 return instruction;
207}
208
David Brazdil3f4a5222016-05-06 12:46:21 +0100209static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
210 DCHECK(ContainsElement(block->GetSuccessors(), successor));
211
212 HBasicBlock* old_dominator = successor->GetDominator();
213 HBasicBlock* new_dominator =
214 (old_dominator == nullptr) ? block
215 : CommonDominator::ForPair(old_dominator, block);
216
217 if (old_dominator == new_dominator) {
218 return false;
219 } else {
220 successor->SetDominator(new_dominator);
221 return true;
222 }
223}
224
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100225void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100226 DCHECK(reverse_post_order_.empty());
227 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100228 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100229
230 // Number of visits of a given node, indexed by block id.
231 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
232 // Number of successors visited from a given node, indexed by block id.
233 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
234 // Nodes for which we need to visit successors.
235 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
236 constexpr size_t kDefaultWorklistSize = 8;
237 worklist.reserve(kDefaultWorklistSize);
238 worklist.push_back(entry_block_);
239
240 while (!worklist.empty()) {
241 HBasicBlock* current = worklist.back();
242 uint32_t current_id = current->GetBlockId();
243 if (successors_visited[current_id] == current->GetSuccessors().size()) {
244 worklist.pop_back();
245 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100246 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100247 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100248
249 // Once all the forward edges have been visited, we know the immediate
250 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100251 if (++visits[successor->GetBlockId()] ==
252 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100253 reverse_post_order_.push_back(successor);
254 worklist.push_back(successor);
255 }
256 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000257 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000258
David Brazdil3f4a5222016-05-06 12:46:21 +0100259 // Check if the graph has back edges not dominated by their respective headers.
260 // If so, we need to update the dominators of those headers and recursively of
261 // their successors. We do that with a fix-point iteration over all blocks.
262 // The algorithm is guaranteed to terminate because it loops only if the sum
263 // of all dominator chains has decreased in the current iteration.
264 bool must_run_fix_point = false;
265 for (HBasicBlock* block : blocks_) {
266 if (block != nullptr &&
267 block->IsLoopHeader() &&
268 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
269 must_run_fix_point = true;
270 break;
271 }
272 }
273 if (must_run_fix_point) {
274 bool update_occurred = true;
275 while (update_occurred) {
276 update_occurred = false;
277 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
278 HBasicBlock* block = it.Current();
279 for (HBasicBlock* successor : block->GetSuccessors()) {
280 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
281 }
282 }
283 }
284 }
285
286 // Make sure that there are no remaining blocks whose dominator information
287 // needs to be updated.
288 if (kIsDebugBuild) {
289 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
290 HBasicBlock* block = it.Current();
291 for (HBasicBlock* successor : block->GetSuccessors()) {
292 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
293 }
294 }
295 }
296
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000297 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000298 // The potential presence of irreducible loops requires to do it after.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000299 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
300 HBasicBlock* block = it.Current();
301 if (!block->IsEntryBlock()) {
302 block->GetDominator()->AddDominatedBlock(block);
303 }
304 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000305}
306
David Brazdilfc6a86a2015-06-26 10:33:45 +0000307HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000308 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
309 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000310 // Use `InsertBetween` to ensure the predecessor index and successor index of
311 // `block` and `successor` are preserved.
312 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000313 return new_block;
314}
315
316void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
317 // Insert a new node between `block` and `successor` to split the
318 // critical edge.
319 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600320 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100321 if (successor->IsLoopHeader()) {
322 // If we split at a back edge boundary, make the new block the back edge.
323 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000324 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100325 info->RemoveBackEdge(block);
326 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100327 }
328 }
329}
330
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100331void HGraph::SimplifyLoop(HBasicBlock* header) {
332 HLoopInformation* info = header->GetLoopInformation();
333
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100334 // Make sure the loop has only one pre header. This simplifies SSA building by having
335 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000336 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
337 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000338 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000339 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100340 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100341 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600342 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100343
Vladimir Marko60584552015-09-03 13:35:12 +0000344 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100345 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100346 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100347 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100348 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100349 }
350 }
351 pre_header->AddSuccessor(header);
352 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100353
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100354 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100355 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
356 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000357 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100358 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100359 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000360 header->predecessors_[pred] = to_swap;
361 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100362 break;
363 }
364 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100365 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100366
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100367 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000368 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
369 // Called from DeadBlockElimination. Update SuspendCheck pointer.
370 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100371 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100372}
373
David Brazdilffee3d32015-07-06 11:48:53 +0100374void HGraph::ComputeTryBlockInformation() {
375 // Iterate in reverse post order to propagate try membership information from
376 // predecessors to their successors.
377 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
378 HBasicBlock* block = it.Current();
379 if (block->IsEntryBlock() || block->IsCatchBlock()) {
380 // Catch blocks after simplification have only exceptional predecessors
381 // and hence are never in tries.
382 continue;
383 }
384
385 // Infer try membership from the first predecessor. Having simplified loops,
386 // the first predecessor can never be a back edge and therefore it must have
387 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100388 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100389 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100390 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000391 if (try_entry != nullptr &&
392 (block->GetTryCatchInformation() == nullptr ||
393 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
394 // We are either setting try block membership for the first time or it
395 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100396 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
397 }
David Brazdilffee3d32015-07-06 11:48:53 +0100398 }
399}
400
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100401void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000402// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100403 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000404 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100405 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
406 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
407 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
408 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100409 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000410 if (block->GetSuccessors().size() > 1) {
411 // Only split normal-flow edges. We cannot split exceptional edges as they
412 // are synthesized (approximate real control flow), and we do not need to
413 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000414 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
415 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
416 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100417 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000418 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000419 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
420 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000421 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000422 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100423 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000424 // SplitCriticalEdge could have invalidated the `normal_successors`
425 // ArrayRef. We must re-acquire it.
426 normal_successors = block->GetNormalSuccessors();
427 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
428 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100429 }
430 }
431 }
432 if (block->IsLoopHeader()) {
433 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000434 } else if (!block->IsEntryBlock() &&
435 block->GetFirstInstruction() != nullptr &&
436 block->GetFirstInstruction()->IsSuspendCheck()) {
437 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000438 // a loop got dismantled. Just remove the suspend check.
439 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100440 }
441 }
442}
443
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000444GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100445 // Order does not matter.
446 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
447 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100448 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100449 if (block->IsCatchBlock()) {
450 // TODO: Dealing with exceptional back edges could be tricky because
451 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000452 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100453 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000454 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100455 }
456 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000457 return kAnalysisSuccess;
458}
459
460void HLoopInformation::Dump(std::ostream& os) {
461 os << "header: " << header_->GetBlockId() << std::endl;
462 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
463 for (HBasicBlock* block : back_edges_) {
464 os << "back edge: " << block->GetBlockId() << std::endl;
465 }
466 for (HBasicBlock* block : header_->GetPredecessors()) {
467 os << "predecessor: " << block->GetBlockId() << std::endl;
468 }
469 for (uint32_t idx : blocks_.Indexes()) {
470 os << " in loop: " << idx << std::endl;
471 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100472}
473
David Brazdil8d5b8b22015-03-24 10:51:52 +0000474void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000475 // New constants are inserted before the SuspendCheck at the bottom of the
476 // entry block. Note that this method can be called from the graph builder and
477 // the entry block therefore may not end with SuspendCheck->Goto yet.
478 HInstruction* insert_before = nullptr;
479
480 HInstruction* gota = entry_block_->GetLastInstruction();
481 if (gota != nullptr && gota->IsGoto()) {
482 HInstruction* suspend_check = gota->GetPrevious();
483 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
484 insert_before = suspend_check;
485 } else {
486 insert_before = gota;
487 }
488 }
489
490 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000491 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000492 } else {
493 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000494 }
495}
496
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600497HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100498 // For simplicity, don't bother reviving the cached null constant if it is
499 // not null and not in a block. Otherwise, we need to clear the instruction
500 // id and/or any invariants the graph is assuming when adding new instructions.
501 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600502 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000503 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000504 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000505 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000506 if (kIsDebugBuild) {
507 ScopedObjectAccess soa(Thread::Current());
508 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
509 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000510 return cached_null_constant_;
511}
512
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100513HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100514 // For simplicity, don't bother reviving the cached current method 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_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700518 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600519 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
520 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100521 if (entry_block_->GetFirstInstruction() == nullptr) {
522 entry_block_->AddInstruction(cached_current_method_);
523 } else {
524 entry_block_->InsertInstructionBefore(
525 cached_current_method_, entry_block_->GetFirstInstruction());
526 }
527 }
528 return cached_current_method_;
529}
530
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600531HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000532 switch (type) {
533 case Primitive::Type::kPrimBoolean:
534 DCHECK(IsUint<1>(value));
535 FALLTHROUGH_INTENDED;
536 case Primitive::Type::kPrimByte:
537 case Primitive::Type::kPrimChar:
538 case Primitive::Type::kPrimShort:
539 case Primitive::Type::kPrimInt:
540 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600541 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000542
543 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600544 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000545
546 default:
547 LOG(FATAL) << "Unsupported constant type";
548 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000549 }
David Brazdil46e2a392015-03-16 17:31:52 +0000550}
551
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000552void HGraph::CacheFloatConstant(HFloatConstant* constant) {
553 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
554 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
555 cached_float_constants_.Overwrite(value, constant);
556}
557
558void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
559 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
560 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
561 cached_double_constants_.Overwrite(value, constant);
562}
563
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000564void HLoopInformation::Add(HBasicBlock* block) {
565 blocks_.SetBit(block->GetBlockId());
566}
567
David Brazdil46e2a392015-03-16 17:31:52 +0000568void HLoopInformation::Remove(HBasicBlock* block) {
569 blocks_.ClearBit(block->GetBlockId());
570}
571
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100572void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
573 if (blocks_.IsBitSet(block->GetBlockId())) {
574 return;
575 }
576
577 blocks_.SetBit(block->GetBlockId());
578 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000579 for (HBasicBlock* predecessor : block->GetPredecessors()) {
580 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100581 }
582}
583
David Brazdilc2e8af92016-04-05 17:15:19 +0100584void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
585 size_t block_id = block->GetBlockId();
586
587 // If `block` is in `finalized`, we know its membership in the loop has been
588 // decided and it does not need to be revisited.
589 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000590 return;
591 }
592
David Brazdilc2e8af92016-04-05 17:15:19 +0100593 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000594 if (block->IsLoopHeader()) {
595 // If we hit a loop header in an irreducible loop, we first check if the
596 // pre header of that loop belongs to the currently analyzed loop. If it does,
597 // then we visit the back edges.
598 // Note that we cannot use GetPreHeader, as the loop may have not been populated
599 // yet.
600 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100601 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000602 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000603 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100604 blocks_.SetBit(block_id);
605 finalized->SetBit(block_id);
606 is_finalized = true;
607
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000608 HLoopInformation* info = block->GetLoopInformation();
609 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100610 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000611 }
612 }
613 } else {
614 // Visit all predecessors. If one predecessor is part of the loop, this
615 // block is also part of this loop.
616 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100617 PopulateIrreducibleRecursive(predecessor, finalized);
618 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000619 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100620 blocks_.SetBit(block_id);
621 finalized->SetBit(block_id);
622 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000623 }
624 }
625 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100626
627 // All predecessors have been recursively visited. Mark finalized if not marked yet.
628 if (!is_finalized) {
629 finalized->SetBit(block_id);
630 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000631}
632
633void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100634 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000635 // Populate this loop: starting with the back edge, recursively add predecessors
636 // that are not already part of that loop. Set the header as part of the loop
637 // to end the recursion.
638 // This is a recursive implementation of the algorithm described in
639 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100640 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000641 blocks_.SetBit(header_->GetBlockId());
642 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100643
David Brazdil3f4a5222016-05-06 12:46:21 +0100644 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100645
646 if (is_irreducible_loop) {
647 ArenaBitVector visited(graph->GetArena(),
648 graph->GetBlocks().size(),
649 /* expandable */ false,
650 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100651 // Stop marking blocks at the loop header.
652 visited.SetBit(header_->GetBlockId());
653
David Brazdilc2e8af92016-04-05 17:15:19 +0100654 for (HBasicBlock* back_edge : GetBackEdges()) {
655 PopulateIrreducibleRecursive(back_edge, &visited);
656 }
657 } else {
658 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000659 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100660 }
David Brazdila4b8c212015-05-07 09:59:30 +0100661 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100662
Vladimir Markofd66c502016-04-18 15:37:01 +0100663 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
664 // When compiling in OSR mode, all loops in the compiled method may be entered
665 // from the interpreter. We treat this OSR entry point just like an extra entry
666 // to an irreducible loop, so we need to mark the method's loops as irreducible.
667 // This does not apply to inlined loops which do not act as OSR entry points.
668 if (suspend_check_ == nullptr) {
669 // Just building the graph in OSR mode, this loop is not inlined. We never build an
670 // inner graph in OSR mode as we can do OSR transition only from the outer method.
671 is_irreducible_loop = true;
672 } else {
673 // Look at the suspend check's environment to determine if the loop was inlined.
674 DCHECK(suspend_check_->HasEnvironment());
675 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
676 is_irreducible_loop = true;
677 }
678 }
679 }
680 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100681 irreducible_ = true;
682 graph->SetHasIrreducibleLoops(true);
683 }
David Brazdila4b8c212015-05-07 09:59:30 +0100684}
685
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100686HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000687 HBasicBlock* block = header_->GetPredecessors()[0];
688 DCHECK(irreducible_ || (block == header_->GetDominator()));
689 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100690}
691
692bool HLoopInformation::Contains(const HBasicBlock& block) const {
693 return blocks_.IsBitSet(block.GetBlockId());
694}
695
696bool HLoopInformation::IsIn(const HLoopInformation& other) const {
697 return other.blocks_.IsBitSet(header_->GetBlockId());
698}
699
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800700bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
701 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700702}
703
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100704size_t HLoopInformation::GetLifetimeEnd() const {
705 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100706 for (HBasicBlock* back_edge : GetBackEdges()) {
707 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100708 }
709 return last_position;
710}
711
David Brazdil3f4a5222016-05-06 12:46:21 +0100712bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
713 for (HBasicBlock* back_edge : GetBackEdges()) {
714 DCHECK(back_edge->GetDominator() != nullptr);
715 if (!header_->Dominates(back_edge)) {
716 return true;
717 }
718 }
719 return false;
720}
721
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100722bool HBasicBlock::Dominates(HBasicBlock* other) const {
723 // Walk up the dominator tree from `other`, to find out if `this`
724 // is an ancestor.
725 HBasicBlock* current = other;
726 while (current != nullptr) {
727 if (current == this) {
728 return true;
729 }
730 current = current->GetDominator();
731 }
732 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100733}
734
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100735static void UpdateInputsUsers(HInstruction* instruction) {
736 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
737 instruction->InputAt(i)->AddUseAt(instruction, i);
738 }
739 // Environment should be created later.
740 DCHECK(!instruction->HasEnvironment());
741}
742
Roland Levillainccc07a92014-09-16 14:48:16 +0100743void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
744 HInstruction* replacement) {
745 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400746 if (initial->IsControlFlow()) {
747 // We can only replace a control flow instruction with another control flow instruction.
748 DCHECK(replacement->IsControlFlow());
749 DCHECK_EQ(replacement->GetId(), -1);
750 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
751 DCHECK_EQ(initial->GetBlock(), this);
752 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100753 DCHECK(initial->GetUses().empty());
754 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400755 replacement->SetBlock(this);
756 replacement->SetId(GetGraph()->GetNextInstructionId());
757 instructions_.InsertInstructionBefore(replacement, initial);
758 UpdateInputsUsers(replacement);
759 } else {
760 InsertInstructionBefore(replacement, initial);
761 initial->ReplaceWith(replacement);
762 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100763 RemoveInstruction(initial);
764}
765
David Brazdil74eb1b22015-12-14 11:44:01 +0000766void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
767 DCHECK(!cursor->IsPhi());
768 DCHECK(!insn->IsPhi());
769 DCHECK(!insn->IsControlFlow());
770 DCHECK(insn->CanBeMoved());
771 DCHECK(!insn->HasSideEffects());
772
773 HBasicBlock* from_block = insn->GetBlock();
774 HBasicBlock* to_block = cursor->GetBlock();
775 DCHECK(from_block != to_block);
776
777 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
778 insn->SetBlock(to_block);
779 to_block->instructions_.InsertInstructionBefore(insn, cursor);
780}
781
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100782static void Add(HInstructionList* instruction_list,
783 HBasicBlock* block,
784 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000785 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000786 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100787 instruction->SetBlock(block);
788 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100789 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100790 instruction_list->AddInstruction(instruction);
791}
792
793void HBasicBlock::AddInstruction(HInstruction* instruction) {
794 Add(&instructions_, this, instruction);
795}
796
797void HBasicBlock::AddPhi(HPhi* phi) {
798 Add(&phis_, this, phi);
799}
800
David Brazdilc3d743f2015-04-22 13:40:50 +0100801void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
802 DCHECK(!cursor->IsPhi());
803 DCHECK(!instruction->IsPhi());
804 DCHECK_EQ(instruction->GetId(), -1);
805 DCHECK_NE(cursor->GetId(), -1);
806 DCHECK_EQ(cursor->GetBlock(), this);
807 DCHECK(!instruction->IsControlFlow());
808 instruction->SetBlock(this);
809 instruction->SetId(GetGraph()->GetNextInstructionId());
810 UpdateInputsUsers(instruction);
811 instructions_.InsertInstructionBefore(instruction, cursor);
812}
813
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100814void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
815 DCHECK(!cursor->IsPhi());
816 DCHECK(!instruction->IsPhi());
817 DCHECK_EQ(instruction->GetId(), -1);
818 DCHECK_NE(cursor->GetId(), -1);
819 DCHECK_EQ(cursor->GetBlock(), this);
820 DCHECK(!instruction->IsControlFlow());
821 DCHECK(!cursor->IsControlFlow());
822 instruction->SetBlock(this);
823 instruction->SetId(GetGraph()->GetNextInstructionId());
824 UpdateInputsUsers(instruction);
825 instructions_.InsertInstructionAfter(instruction, cursor);
826}
827
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100828void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
829 DCHECK_EQ(phi->GetId(), -1);
830 DCHECK_NE(cursor->GetId(), -1);
831 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100832 phi->SetBlock(this);
833 phi->SetId(GetGraph()->GetNextInstructionId());
834 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100835 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100836}
837
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100838static void Remove(HInstructionList* instruction_list,
839 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000840 HInstruction* instruction,
841 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100842 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100843 instruction->SetBlock(nullptr);
844 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000845 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100846 DCHECK(instruction->GetUses().empty());
847 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000848 RemoveAsUser(instruction);
849 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100850}
851
David Brazdil1abb4192015-02-17 18:33:36 +0000852void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100853 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000854 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100855}
856
David Brazdil1abb4192015-02-17 18:33:36 +0000857void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
858 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100859}
860
David Brazdilc7508e92015-04-27 13:28:57 +0100861void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
862 if (instruction->IsPhi()) {
863 RemovePhi(instruction->AsPhi(), ensure_safety);
864 } else {
865 RemoveInstruction(instruction, ensure_safety);
866 }
867}
868
Vladimir Marko71bf8092015-09-15 15:33:14 +0100869void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
870 for (size_t i = 0; i < locals.size(); i++) {
871 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100872 SetRawEnvAt(i, instruction);
873 if (instruction != nullptr) {
874 instruction->AddEnvUseAt(this, i);
875 }
876 }
877}
878
David Brazdiled596192015-01-23 10:39:45 +0000879void HEnvironment::CopyFrom(HEnvironment* env) {
880 for (size_t i = 0; i < env->Size(); i++) {
881 HInstruction* instruction = env->GetInstructionAt(i);
882 SetRawEnvAt(i, instruction);
883 if (instruction != nullptr) {
884 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100885 }
David Brazdiled596192015-01-23 10:39:45 +0000886 }
887}
888
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700889void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
890 HBasicBlock* loop_header) {
891 DCHECK(loop_header->IsLoopHeader());
892 for (size_t i = 0; i < env->Size(); i++) {
893 HInstruction* instruction = env->GetInstructionAt(i);
894 SetRawEnvAt(i, instruction);
895 if (instruction == nullptr) {
896 continue;
897 }
898 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
899 // At the end of the loop pre-header, the corresponding value for instruction
900 // is the first input of the phi.
901 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700902 SetRawEnvAt(i, initial);
903 initial->AddEnvUseAt(this, i);
904 } else {
905 instruction->AddEnvUseAt(this, i);
906 }
907 }
908}
909
David Brazdil1abb4192015-02-17 18:33:36 +0000910void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100911 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
912 HInstruction* user = env_use.GetInstruction();
913 auto before_env_use_node = env_use.GetBeforeUseNode();
914 user->env_uses_.erase_after(before_env_use_node);
915 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100916}
917
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000918HInstruction::InstructionKind HInstruction::GetKind() const {
919 return GetKindInternal();
920}
921
Calin Juravle77520bc2015-01-12 18:45:46 +0000922HInstruction* HInstruction::GetNextDisregardingMoves() const {
923 HInstruction* next = GetNext();
924 while (next != nullptr && next->IsParallelMove()) {
925 next = next->GetNext();
926 }
927 return next;
928}
929
930HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
931 HInstruction* previous = GetPrevious();
932 while (previous != nullptr && previous->IsParallelMove()) {
933 previous = previous->GetPrevious();
934 }
935 return previous;
936}
937
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100938void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000939 if (first_instruction_ == nullptr) {
940 DCHECK(last_instruction_ == nullptr);
941 first_instruction_ = last_instruction_ = instruction;
942 } else {
943 last_instruction_->next_ = instruction;
944 instruction->previous_ = last_instruction_;
945 last_instruction_ = instruction;
946 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000947}
948
David Brazdilc3d743f2015-04-22 13:40:50 +0100949void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
950 DCHECK(Contains(cursor));
951 if (cursor == first_instruction_) {
952 cursor->previous_ = instruction;
953 instruction->next_ = cursor;
954 first_instruction_ = instruction;
955 } else {
956 instruction->previous_ = cursor->previous_;
957 instruction->next_ = cursor;
958 cursor->previous_ = instruction;
959 instruction->previous_->next_ = instruction;
960 }
961}
962
963void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
964 DCHECK(Contains(cursor));
965 if (cursor == last_instruction_) {
966 cursor->next_ = instruction;
967 instruction->previous_ = cursor;
968 last_instruction_ = instruction;
969 } else {
970 instruction->next_ = cursor->next_;
971 instruction->previous_ = cursor;
972 cursor->next_ = instruction;
973 instruction->next_->previous_ = instruction;
974 }
975}
976
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100977void HInstructionList::RemoveInstruction(HInstruction* instruction) {
978 if (instruction->previous_ != nullptr) {
979 instruction->previous_->next_ = instruction->next_;
980 }
981 if (instruction->next_ != nullptr) {
982 instruction->next_->previous_ = instruction->previous_;
983 }
984 if (instruction == first_instruction_) {
985 first_instruction_ = instruction->next_;
986 }
987 if (instruction == last_instruction_) {
988 last_instruction_ = instruction->previous_;
989 }
990}
991
Roland Levillain6b469232014-09-25 10:10:38 +0100992bool HInstructionList::Contains(HInstruction* instruction) const {
993 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
994 if (it.Current() == instruction) {
995 return true;
996 }
997 }
998 return false;
999}
1000
Roland Levillainccc07a92014-09-16 14:48:16 +01001001bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1002 const HInstruction* instruction2) const {
1003 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1004 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1005 if (it.Current() == instruction1) {
1006 return true;
1007 }
1008 if (it.Current() == instruction2) {
1009 return false;
1010 }
1011 }
1012 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1013 return true;
1014}
1015
Roland Levillain6c82d402014-10-13 16:10:27 +01001016bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1017 if (other_instruction == this) {
1018 // An instruction does not strictly dominate itself.
1019 return false;
1020 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001021 HBasicBlock* block = GetBlock();
1022 HBasicBlock* other_block = other_instruction->GetBlock();
1023 if (block != other_block) {
1024 return GetBlock()->Dominates(other_instruction->GetBlock());
1025 } else {
1026 // If both instructions are in the same block, ensure this
1027 // instruction comes before `other_instruction`.
1028 if (IsPhi()) {
1029 if (!other_instruction->IsPhi()) {
1030 // Phis appear before non phi-instructions so this instruction
1031 // dominates `other_instruction`.
1032 return true;
1033 } else {
1034 // There is no order among phis.
1035 LOG(FATAL) << "There is no dominance between phis of a same block.";
1036 return false;
1037 }
1038 } else {
1039 // `this` is not a phi.
1040 if (other_instruction->IsPhi()) {
1041 // Phis appear before non phi-instructions so this instruction
1042 // does not dominate `other_instruction`.
1043 return false;
1044 } else {
1045 // Check whether this instruction comes before
1046 // `other_instruction` in the instruction list.
1047 return block->GetInstructions().FoundBefore(this, other_instruction);
1048 }
1049 }
1050 }
1051}
1052
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001053void HInstruction::RemoveEnvironment() {
1054 RemoveEnvironmentUses(this);
1055 environment_ = nullptr;
1056}
1057
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001058void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001059 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001060 // Note: fixup_end remains valid across splice_after().
1061 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1062 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1063 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001064
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001065 // Note: env_fixup_end remains valid across splice_after().
1066 auto env_fixup_end =
1067 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1068 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1069 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001070
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001071 DCHECK(uses_.empty());
1072 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001073}
1074
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001075void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001076 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001077 if (input_use.GetInstruction() == replacement) {
1078 // Nothing to do.
1079 return;
1080 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001081 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001082 // Note: fixup_end remains valid across splice_after().
1083 auto fixup_end =
1084 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1085 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1086 input_use.GetInstruction()->uses_,
1087 before_use_node);
1088 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1089 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001090}
1091
Nicolas Geoffray39468442014-09-02 15:17:15 +01001092size_t HInstruction::EnvironmentSize() const {
1093 return HasEnvironment() ? environment_->Size() : 0;
1094}
1095
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001096void HPhi::AddInput(HInstruction* input) {
1097 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001098 inputs_.push_back(HUserRecord<HInstruction*>(input));
1099 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001100}
1101
David Brazdil2d7352b2015-04-20 14:52:42 +01001102void HPhi::RemoveInputAt(size_t index) {
1103 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001104 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001105 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001106 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001107 InputRecordAt(i).GetUseNode()->SetIndex(i);
1108 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001109}
1110
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001111#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001112void H##name::Accept(HGraphVisitor* visitor) { \
1113 visitor->Visit##name(this); \
1114}
1115
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001116FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001117
1118#undef DEFINE_ACCEPT
1119
1120void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001121 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1122 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001123 if (block != nullptr) {
1124 VisitBasicBlock(block);
1125 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001126 }
1127}
1128
Roland Levillain633021e2014-10-01 14:12:25 +01001129void HGraphVisitor::VisitReversePostOrder() {
1130 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1131 VisitBasicBlock(it.Current());
1132 }
1133}
1134
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001135void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001136 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001137 it.Current()->Accept(this);
1138 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001139 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001140 it.Current()->Accept(this);
1141 }
1142}
1143
Mark Mendelle82549b2015-05-06 10:55:34 -04001144HConstant* HTypeConversion::TryStaticEvaluation() const {
1145 HGraph* graph = GetBlock()->GetGraph();
1146 if (GetInput()->IsIntConstant()) {
1147 int32_t value = GetInput()->AsIntConstant()->GetValue();
1148 switch (GetResultType()) {
1149 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001150 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001151 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001152 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001153 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001154 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001155 default:
1156 return nullptr;
1157 }
1158 } else if (GetInput()->IsLongConstant()) {
1159 int64_t value = GetInput()->AsLongConstant()->GetValue();
1160 switch (GetResultType()) {
1161 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001162 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001163 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001164 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001165 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001166 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001167 default:
1168 return nullptr;
1169 }
1170 } else if (GetInput()->IsFloatConstant()) {
1171 float value = GetInput()->AsFloatConstant()->GetValue();
1172 switch (GetResultType()) {
1173 case Primitive::kPrimInt:
1174 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001175 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001176 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001177 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001178 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001179 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1180 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001181 case Primitive::kPrimLong:
1182 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001183 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001184 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001185 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001186 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001187 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1188 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001189 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001190 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001191 default:
1192 return nullptr;
1193 }
1194 } else if (GetInput()->IsDoubleConstant()) {
1195 double value = GetInput()->AsDoubleConstant()->GetValue();
1196 switch (GetResultType()) {
1197 case Primitive::kPrimInt:
1198 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001199 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001200 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001201 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001202 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001203 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1204 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001205 case Primitive::kPrimLong:
1206 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001207 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001208 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001209 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001210 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001211 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1212 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001213 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001214 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001215 default:
1216 return nullptr;
1217 }
1218 }
1219 return nullptr;
1220}
1221
Roland Levillain9240d6a2014-10-20 16:47:04 +01001222HConstant* HUnaryOperation::TryStaticEvaluation() const {
1223 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001224 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001225 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001226 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001227 } else if (kEnableFloatingPointStaticEvaluation) {
1228 if (GetInput()->IsFloatConstant()) {
1229 return Evaluate(GetInput()->AsFloatConstant());
1230 } else if (GetInput()->IsDoubleConstant()) {
1231 return Evaluate(GetInput()->AsDoubleConstant());
1232 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001233 }
1234 return nullptr;
1235}
1236
1237HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001238 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1239 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001240 } else if (GetLeft()->IsLongConstant()) {
1241 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001242 // The binop(long, int) case is only valid for shifts and rotations.
1243 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001244 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1245 } else if (GetRight()->IsLongConstant()) {
1246 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001247 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001248 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001249 // The binop(null, null) case is only valid for equal and not-equal conditions.
1250 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001251 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001252 } else if (kEnableFloatingPointStaticEvaluation) {
1253 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1254 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1255 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1256 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1257 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001258 }
1259 return nullptr;
1260}
Dave Allison20dfc792014-06-16 20:44:29 -07001261
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001262HConstant* HBinaryOperation::GetConstantRight() const {
1263 if (GetRight()->IsConstant()) {
1264 return GetRight()->AsConstant();
1265 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1266 return GetLeft()->AsConstant();
1267 } else {
1268 return nullptr;
1269 }
1270}
1271
1272// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001273// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001274HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1275 HInstruction* most_constant_right = GetConstantRight();
1276 if (most_constant_right == nullptr) {
1277 return nullptr;
1278 } else if (most_constant_right == GetLeft()) {
1279 return GetRight();
1280 } else {
1281 return GetLeft();
1282 }
1283}
1284
Roland Levillain31dd3d62016-02-16 12:21:02 +00001285std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1286 switch (rhs) {
1287 case ComparisonBias::kNoBias:
1288 return os << "no_bias";
1289 case ComparisonBias::kGtBias:
1290 return os << "gt_bias";
1291 case ComparisonBias::kLtBias:
1292 return os << "lt_bias";
1293 default:
1294 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1295 UNREACHABLE();
1296 }
1297}
1298
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001299bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1300 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001301}
1302
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001303bool HInstruction::Equals(HInstruction* other) const {
1304 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001305 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001306 if (!InstructionDataEquals(other)) return false;
1307 if (GetType() != other->GetType()) return false;
1308 if (InputCount() != other->InputCount()) return false;
1309
1310 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1311 if (InputAt(i) != other->InputAt(i)) return false;
1312 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001313 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001314 return true;
1315}
1316
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001317std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1318#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1319 switch (rhs) {
1320 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1321 default:
1322 os << "Unknown instruction kind " << static_cast<int>(rhs);
1323 break;
1324 }
1325#undef DECLARE_CASE
1326 return os;
1327}
1328
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001329void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001330 next_->previous_ = previous_;
1331 if (previous_ != nullptr) {
1332 previous_->next_ = next_;
1333 }
1334 if (block_->instructions_.first_instruction_ == this) {
1335 block_->instructions_.first_instruction_ = next_;
1336 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001337 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001338
1339 previous_ = cursor->previous_;
1340 if (previous_ != nullptr) {
1341 previous_->next_ = this;
1342 }
1343 next_ = cursor;
1344 cursor->previous_ = this;
1345 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001346
1347 if (block_->instructions_.first_instruction_ == cursor) {
1348 block_->instructions_.first_instruction_ = this;
1349 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001350}
1351
Vladimir Markofb337ea2015-11-25 15:25:10 +00001352void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1353 DCHECK(!CanThrow());
1354 DCHECK(!HasSideEffects());
1355 DCHECK(!HasEnvironmentUses());
1356 DCHECK(HasNonEnvironmentUses());
1357 DCHECK(!IsPhi()); // Makes no sense for Phi.
1358 DCHECK_EQ(InputCount(), 0u);
1359
1360 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001361 auto uses_it = GetUses().begin();
1362 auto uses_end = GetUses().end();
1363 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1364 ++uses_it;
1365 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1366 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001367 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001368 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001369 // This instruction has uses in two or more blocks. Find the common dominator.
1370 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001371 for (; uses_it != uses_end; ++uses_it) {
1372 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001373 }
1374 target_block = finder.Get();
1375 DCHECK(target_block != nullptr);
1376 }
1377 // Move to the first dominator not in a loop.
1378 while (target_block->IsInLoop()) {
1379 target_block = target_block->GetDominator();
1380 DCHECK(target_block != nullptr);
1381 }
1382
1383 // Find insertion position.
1384 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001385 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1386 if (use.GetUser()->GetBlock() == target_block &&
1387 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1388 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001389 }
1390 }
1391 if (insert_pos == nullptr) {
1392 // No user in `target_block`, insert before the control flow instruction.
1393 insert_pos = target_block->GetLastInstruction();
1394 DCHECK(insert_pos->IsControlFlow());
1395 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1396 if (insert_pos->IsIf()) {
1397 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1398 if (if_input == insert_pos->GetPrevious()) {
1399 insert_pos = if_input;
1400 }
1401 }
1402 }
1403 MoveBefore(insert_pos);
1404}
1405
David Brazdilfc6a86a2015-06-26 10:33:45 +00001406HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001407 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001408 DCHECK_EQ(cursor->GetBlock(), this);
1409
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001410 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1411 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001412 new_block->instructions_.first_instruction_ = cursor;
1413 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1414 instructions_.last_instruction_ = cursor->previous_;
1415 if (cursor->previous_ == nullptr) {
1416 instructions_.first_instruction_ = nullptr;
1417 } else {
1418 cursor->previous_->next_ = nullptr;
1419 cursor->previous_ = nullptr;
1420 }
1421
1422 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001423 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001424
Vladimir Marko60584552015-09-03 13:35:12 +00001425 for (HBasicBlock* successor : GetSuccessors()) {
1426 new_block->successors_.push_back(successor);
1427 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001428 }
Vladimir Marko60584552015-09-03 13:35:12 +00001429 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001430 AddSuccessor(new_block);
1431
David Brazdil56e1acc2015-06-30 15:41:36 +01001432 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001433 return new_block;
1434}
1435
David Brazdild7558da2015-09-22 13:04:14 +01001436HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001437 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001438 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1439
1440 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1441
1442 for (HBasicBlock* predecessor : GetPredecessors()) {
1443 new_block->predecessors_.push_back(predecessor);
1444 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1445 }
1446 predecessors_.clear();
1447 AddPredecessor(new_block);
1448
1449 GetGraph()->AddBlock(new_block);
1450 return new_block;
1451}
1452
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001453HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1454 DCHECK_EQ(cursor->GetBlock(), this);
1455
1456 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1457 cursor->GetDexPc());
1458 new_block->instructions_.first_instruction_ = cursor;
1459 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1460 instructions_.last_instruction_ = cursor->previous_;
1461 if (cursor->previous_ == nullptr) {
1462 instructions_.first_instruction_ = nullptr;
1463 } else {
1464 cursor->previous_->next_ = nullptr;
1465 cursor->previous_ = nullptr;
1466 }
1467
1468 new_block->instructions_.SetBlockOfInstructions(new_block);
1469
1470 for (HBasicBlock* successor : GetSuccessors()) {
1471 new_block->successors_.push_back(successor);
1472 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1473 }
1474 successors_.clear();
1475
1476 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1477 dominated->dominator_ = new_block;
1478 new_block->dominated_blocks_.push_back(dominated);
1479 }
1480 dominated_blocks_.clear();
1481 return new_block;
1482}
1483
1484HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001485 DCHECK(!cursor->IsControlFlow());
1486 DCHECK_NE(instructions_.last_instruction_, cursor);
1487 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001488
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001489 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1490 new_block->instructions_.first_instruction_ = cursor->GetNext();
1491 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1492 cursor->next_->previous_ = nullptr;
1493 cursor->next_ = nullptr;
1494 instructions_.last_instruction_ = cursor;
1495
1496 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001497 for (HBasicBlock* successor : GetSuccessors()) {
1498 new_block->successors_.push_back(successor);
1499 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001500 }
Vladimir Marko60584552015-09-03 13:35:12 +00001501 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001502
Vladimir Marko60584552015-09-03 13:35:12 +00001503 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001504 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001505 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001506 }
Vladimir Marko60584552015-09-03 13:35:12 +00001507 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001508 return new_block;
1509}
1510
David Brazdilec16f792015-08-19 15:04:01 +01001511const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001512 if (EndsWithTryBoundary()) {
1513 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1514 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001515 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001516 return try_boundary;
1517 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001518 DCHECK(IsTryBlock());
1519 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001520 return nullptr;
1521 }
David Brazdilec16f792015-08-19 15:04:01 +01001522 } else if (IsTryBlock()) {
1523 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001524 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001525 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001526 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001527}
1528
David Brazdild7558da2015-09-22 13:04:14 +01001529bool HBasicBlock::HasThrowingInstructions() const {
1530 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1531 if (it.Current()->CanThrow()) {
1532 return true;
1533 }
1534 }
1535 return false;
1536}
1537
David Brazdilfc6a86a2015-06-26 10:33:45 +00001538static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1539 return block.GetPhis().IsEmpty()
1540 && !block.GetInstructions().IsEmpty()
1541 && block.GetFirstInstruction() == block.GetLastInstruction();
1542}
1543
David Brazdil46e2a392015-03-16 17:31:52 +00001544bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001545 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1546}
1547
1548bool HBasicBlock::IsSingleTryBoundary() const {
1549 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001550}
1551
David Brazdil8d5b8b22015-03-24 10:51:52 +00001552bool HBasicBlock::EndsWithControlFlowInstruction() const {
1553 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1554}
1555
David Brazdilb2bd1c52015-03-25 11:17:37 +00001556bool HBasicBlock::EndsWithIf() const {
1557 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1558}
1559
David Brazdilffee3d32015-07-06 11:48:53 +01001560bool HBasicBlock::EndsWithTryBoundary() const {
1561 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1562}
1563
David Brazdilb2bd1c52015-03-25 11:17:37 +00001564bool HBasicBlock::HasSinglePhi() const {
1565 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1566}
1567
David Brazdild26a4112015-11-10 11:07:31 +00001568ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1569 if (EndsWithTryBoundary()) {
1570 // The normal-flow successor of HTryBoundary is always stored at index zero.
1571 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1572 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1573 } else {
1574 // All successors of blocks not ending with TryBoundary are normal.
1575 return ArrayRef<HBasicBlock* const>(successors_);
1576 }
1577}
1578
1579ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1580 if (EndsWithTryBoundary()) {
1581 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1582 } else {
1583 // Blocks not ending with TryBoundary do not have exceptional successors.
1584 return ArrayRef<HBasicBlock* const>();
1585 }
1586}
1587
David Brazdilffee3d32015-07-06 11:48:53 +01001588bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001589 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1590 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1591
1592 size_t length = handlers1.size();
1593 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001594 return false;
1595 }
1596
David Brazdilb618ade2015-07-29 10:31:29 +01001597 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001598 for (size_t i = 0; i < length; ++i) {
1599 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001600 return false;
1601 }
1602 }
1603 return true;
1604}
1605
David Brazdil2d7352b2015-04-20 14:52:42 +01001606size_t HInstructionList::CountSize() const {
1607 size_t size = 0;
1608 HInstruction* current = first_instruction_;
1609 for (; current != nullptr; current = current->GetNext()) {
1610 size++;
1611 }
1612 return size;
1613}
1614
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001615void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1616 for (HInstruction* current = first_instruction_;
1617 current != nullptr;
1618 current = current->GetNext()) {
1619 current->SetBlock(block);
1620 }
1621}
1622
1623void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1624 DCHECK(Contains(cursor));
1625 if (!instruction_list.IsEmpty()) {
1626 if (cursor == last_instruction_) {
1627 last_instruction_ = instruction_list.last_instruction_;
1628 } else {
1629 cursor->next_->previous_ = instruction_list.last_instruction_;
1630 }
1631 instruction_list.last_instruction_->next_ = cursor->next_;
1632 cursor->next_ = instruction_list.first_instruction_;
1633 instruction_list.first_instruction_->previous_ = cursor;
1634 }
1635}
1636
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001637void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1638 DCHECK(Contains(cursor));
1639 if (!instruction_list.IsEmpty()) {
1640 if (cursor == first_instruction_) {
1641 first_instruction_ = instruction_list.first_instruction_;
1642 } else {
1643 cursor->previous_->next_ = instruction_list.first_instruction_;
1644 }
1645 instruction_list.last_instruction_->next_ = cursor;
1646 instruction_list.first_instruction_->previous_ = cursor->previous_;
1647 cursor->previous_ = instruction_list.last_instruction_;
1648 }
1649}
1650
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001651void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001652 if (IsEmpty()) {
1653 first_instruction_ = instruction_list.first_instruction_;
1654 last_instruction_ = instruction_list.last_instruction_;
1655 } else {
1656 AddAfter(last_instruction_, instruction_list);
1657 }
1658}
1659
David Brazdil04ff4e82015-12-10 13:54:52 +00001660// Should be called on instructions in a dead block in post order. This method
1661// assumes `insn` has been removed from all users with the exception of catch
1662// phis because of missing exceptional edges in the graph. It removes the
1663// instruction from catch phi uses, together with inputs of other catch phis in
1664// the catch block at the same index, as these must be dead too.
1665static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1666 DCHECK(!insn->HasEnvironmentUses());
1667 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001668 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1669 size_t use_index = use.GetIndex();
1670 HBasicBlock* user_block = use.GetUser()->GetBlock();
1671 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001672 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1673 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1674 }
1675 }
1676}
1677
David Brazdil2d7352b2015-04-20 14:52:42 +01001678void HBasicBlock::DisconnectAndDelete() {
1679 // Dominators must be removed after all the blocks they dominate. This way
1680 // a loop header is removed last, a requirement for correct loop information
1681 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001682 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001683
David Brazdil9eeebf62016-03-24 11:18:15 +00001684 // The following steps gradually remove the block from all its dependants in
1685 // post order (b/27683071).
1686
1687 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1688 // We need to do this before step (4) which destroys the predecessor list.
1689 HBasicBlock* loop_update_start = this;
1690 if (IsLoopHeader()) {
1691 HLoopInformation* loop_info = GetLoopInformation();
1692 // All other blocks in this loop should have been removed because the header
1693 // was their dominator.
1694 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1695 DCHECK(!loop_info->IsIrreducible());
1696 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1697 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1698 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001699 }
1700
David Brazdil9eeebf62016-03-24 11:18:15 +00001701 // (2) Disconnect the block from its successors and update their phis.
1702 for (HBasicBlock* successor : successors_) {
1703 // Delete this block from the list of predecessors.
1704 size_t this_index = successor->GetPredecessorIndexOf(this);
1705 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1706
1707 // Check that `successor` has other predecessors, otherwise `this` is the
1708 // dominator of `successor` which violates the order DCHECKed at the top.
1709 DCHECK(!successor->predecessors_.empty());
1710
1711 // Remove this block's entries in the successor's phis. Skip exceptional
1712 // successors because catch phi inputs do not correspond to predecessor
1713 // blocks but throwing instructions. The inputs of the catch phis will be
1714 // updated in step (3).
1715 if (!successor->IsCatchBlock()) {
1716 if (successor->predecessors_.size() == 1u) {
1717 // The successor has just one predecessor left. Replace phis with the only
1718 // remaining input.
1719 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1720 HPhi* phi = phi_it.Current()->AsPhi();
1721 phi->ReplaceWith(phi->InputAt(1 - this_index));
1722 successor->RemovePhi(phi);
1723 }
1724 } else {
1725 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1726 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1727 }
1728 }
1729 }
1730 }
1731 successors_.clear();
1732
1733 // (3) Remove instructions and phis. Instructions should have no remaining uses
1734 // except in catch phis. If an instruction is used by a catch phi at `index`,
1735 // remove `index`-th input of all phis in the catch block since they are
1736 // guaranteed dead. Note that we may miss dead inputs this way but the
1737 // graph will always remain consistent.
1738 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1739 HInstruction* insn = it.Current();
1740 RemoveUsesOfDeadInstruction(insn);
1741 RemoveInstruction(insn);
1742 }
1743 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1744 HPhi* insn = it.Current()->AsPhi();
1745 RemoveUsesOfDeadInstruction(insn);
1746 RemovePhi(insn);
1747 }
1748
1749 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001750 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001751 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001752 // We should not see any back edges as they would have been removed by step (3).
1753 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1754
David Brazdil2d7352b2015-04-20 14:52:42 +01001755 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001756 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1757 // This block is the only normal-flow successor of the TryBoundary which
1758 // makes `predecessor` dead. Since DCE removes blocks in post order,
1759 // exception handlers of this TryBoundary were already visited and any
1760 // remaining handlers therefore must be live. We remove `predecessor` from
1761 // their list of predecessors.
1762 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1763 while (predecessor->GetSuccessors().size() > 1) {
1764 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1765 DCHECK(handler->IsCatchBlock());
1766 predecessor->RemoveSuccessor(handler);
1767 handler->RemovePredecessor(predecessor);
1768 }
1769 }
1770
David Brazdil2d7352b2015-04-20 14:52:42 +01001771 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001772 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1773 if (num_pred_successors == 1u) {
1774 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001775 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1776 // successor. Replace those with a HGoto.
1777 DCHECK(last_instruction->IsIf() ||
1778 last_instruction->IsPackedSwitch() ||
1779 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001780 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001781 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001782 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001783 // The predecessor has no remaining successors and therefore must be dead.
1784 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001785 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001786 predecessor->RemoveInstruction(last_instruction);
1787 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001788 // There are multiple successors left. The removed block might be a successor
1789 // of a PackedSwitch which will be completely removed (perhaps replaced with
1790 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1791 // case, leave `last_instruction` as is for now.
1792 DCHECK(last_instruction->IsPackedSwitch() ||
1793 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001794 }
David Brazdil46e2a392015-03-16 17:31:52 +00001795 }
Vladimir Marko60584552015-09-03 13:35:12 +00001796 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001797
David Brazdil9eeebf62016-03-24 11:18:15 +00001798 // (5) Remove the block from all loops it is included in. Skip the inner-most
1799 // loop if this is the loop header (see definition of `loop_update_start`)
1800 // because the loop header's predecessor list has been destroyed in step (4).
1801 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1802 HLoopInformation* loop_info = it.Current();
1803 loop_info->Remove(this);
1804 if (loop_info->IsBackEdge(*this)) {
1805 // If this was the last back edge of the loop, we deliberately leave the
1806 // loop in an inconsistent state and will fail GraphChecker unless the
1807 // entire loop is removed during the pass.
1808 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001809 }
1810 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001811
David Brazdil9eeebf62016-03-24 11:18:15 +00001812 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001813 dominator_->RemoveDominatedBlock(this);
1814 SetDominator(nullptr);
1815
David Brazdil9eeebf62016-03-24 11:18:15 +00001816 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001817 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001818 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001819}
1820
1821void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001822 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001823 DCHECK(ContainsElement(dominated_blocks_, other));
1824 DCHECK_EQ(GetSingleSuccessor(), other);
1825 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001826 DCHECK(other->GetPhis().IsEmpty());
1827
David Brazdil2d7352b2015-04-20 14:52:42 +01001828 // Move instructions from `other` to `this`.
1829 DCHECK(EndsWithControlFlowInstruction());
1830 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001831 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001832 other->instructions_.SetBlockOfInstructions(this);
1833 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001834
David Brazdil2d7352b2015-04-20 14:52:42 +01001835 // Remove `other` from the loops it is included in.
1836 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1837 HLoopInformation* loop_info = it.Current();
1838 loop_info->Remove(other);
1839 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001840 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001841 }
1842 }
1843
1844 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001845 successors_.clear();
1846 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001847 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001848 successor->ReplacePredecessor(other, this);
1849 }
1850
David Brazdil2d7352b2015-04-20 14:52:42 +01001851 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001852 RemoveDominatedBlock(other);
1853 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1854 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001855 dominated->SetDominator(this);
1856 }
Vladimir Marko60584552015-09-03 13:35:12 +00001857 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001858 other->dominator_ = nullptr;
1859
1860 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001861 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001862
1863 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001864 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001865 other->SetGraph(nullptr);
1866}
1867
1868void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1869 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001870 DCHECK(GetDominatedBlocks().empty());
1871 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001872 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001873 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001874 DCHECK(other->GetPhis().IsEmpty());
1875 DCHECK(!other->IsInLoop());
1876
1877 // Move instructions from `other` to `this`.
1878 instructions_.Add(other->GetInstructions());
1879 other->instructions_.SetBlockOfInstructions(this);
1880
1881 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001882 successors_.clear();
1883 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001884 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001885 successor->ReplacePredecessor(other, this);
1886 }
1887
1888 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001889 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1890 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001891 dominated->SetDominator(this);
1892 }
Vladimir Marko60584552015-09-03 13:35:12 +00001893 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001894 other->dominator_ = nullptr;
1895 other->graph_ = nullptr;
1896}
1897
1898void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001899 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001900 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001901 predecessor->ReplaceSuccessor(this, other);
1902 }
Vladimir Marko60584552015-09-03 13:35:12 +00001903 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001904 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001905 successor->ReplacePredecessor(this, other);
1906 }
Vladimir Marko60584552015-09-03 13:35:12 +00001907 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1908 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001909 }
1910 GetDominator()->ReplaceDominatedBlock(this, other);
1911 other->SetDominator(GetDominator());
1912 dominator_ = nullptr;
1913 graph_ = nullptr;
1914}
1915
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001916void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001917 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001918 DCHECK(block->GetSuccessors().empty());
1919 DCHECK(block->GetPredecessors().empty());
1920 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001921 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001922 DCHECK(block->GetInstructions().IsEmpty());
1923 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001924
David Brazdilc7af85d2015-05-26 12:05:55 +01001925 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06001926 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01001927 }
1928
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001929 RemoveElement(reverse_post_order_, block);
1930 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00001931 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01001932}
1933
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001934void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
1935 HBasicBlock* reference,
1936 bool replace_if_back_edge) {
1937 if (block->IsLoopHeader()) {
1938 // Clear the information of which blocks are contained in that loop. Since the
1939 // information is stored as a bit vector based on block ids, we have to update
1940 // it, as those block ids were specific to the callee graph and we are now adding
1941 // these blocks to the caller graph.
1942 block->GetLoopInformation()->ClearAllBlocks();
1943 }
1944
1945 // If not already in a loop, update the loop information.
1946 if (!block->IsInLoop()) {
1947 block->SetLoopInformation(reference->GetLoopInformation());
1948 }
1949
1950 // If the block is in a loop, update all its outward loops.
1951 HLoopInformation* loop_info = block->GetLoopInformation();
1952 if (loop_info != nullptr) {
1953 for (HLoopInformationOutwardIterator loop_it(*block);
1954 !loop_it.Done();
1955 loop_it.Advance()) {
1956 loop_it.Current()->Add(block);
1957 }
1958 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
1959 loop_info->ReplaceBackEdge(reference, block);
1960 }
1961 }
1962
1963 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
1964 TryCatchInformation* try_catch_info = reference->IsTryBlock()
1965 ? reference->GetTryCatchInformation()
1966 : nullptr;
1967 block->SetTryCatchInformation(try_catch_info);
1968}
1969
Calin Juravle2e768302015-07-28 14:41:11 +00001970HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001971 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001972 // Update the environments in this graph to have the invoke's environment
1973 // as parent.
1974 {
1975 HReversePostOrderIterator it(*this);
1976 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1977 for (; !it.Done(); it.Advance()) {
1978 HBasicBlock* block = it.Current();
1979 for (HInstructionIterator instr_it(block->GetInstructions());
1980 !instr_it.Done();
1981 instr_it.Advance()) {
1982 HInstruction* current = instr_it.Current();
1983 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00001984 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001985 current->GetEnvironment()->SetAndCopyParentChain(
1986 outer_graph->GetArena(), invoke->GetEnvironment());
1987 }
1988 }
1989 }
1990 }
1991 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1992 if (HasBoundsChecks()) {
1993 outer_graph->SetHasBoundsChecks(true);
1994 }
1995
Calin Juravle2e768302015-07-28 14:41:11 +00001996 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001997 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001998 // Simple case of an entry block, a body block, and an exit block.
1999 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002000 HBasicBlock* body = GetBlocks()[1];
2001 DCHECK(GetBlocks()[0]->IsEntryBlock());
2002 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002003 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002004 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002005 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002006
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002007 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2008 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002009 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002010
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002011 // Replace the invoke with the return value of the inlined graph.
2012 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002013 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002014 } else {
2015 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002016 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002017
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002018 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002019 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002020 // Need to inline multiple blocks. We split `invoke`'s block
2021 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002022 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002023 // with the second half.
2024 ArenaAllocator* allocator = outer_graph->GetArena();
2025 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002026 // Note that we split before the invoke only to simplify polymorphic inlining.
2027 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002028
Vladimir Markoec7802a2015-10-01 20:57:57 +01002029 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002030 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002031 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002032 exit_block_->ReplaceWith(to);
2033
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002034 // Update the meta information surrounding blocks:
2035 // (1) the graph they are now in,
2036 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002037 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002038 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002039 // Note that we do not need to update catch phi inputs because they
2040 // correspond to the register file of the outer method which the inlinee
2041 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002042
2043 // We don't add the entry block, the exit block, and the first block, which
2044 // has been merged with `at`.
2045 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2046
2047 // We add the `to` block.
2048 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002049 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002050 + kNumberOfNewBlocksInCaller;
2051
2052 // Find the location of `at` in the outer graph's reverse post order. The new
2053 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002054 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002055 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2056
David Brazdil95177982015-10-30 12:56:58 -05002057 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2058 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002059 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
2060 HBasicBlock* current = it.Current();
2061 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002062 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002063 DCHECK(current->GetGraph() == this);
2064 current->SetGraph(outer_graph);
2065 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002066 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002067 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002068 }
2069 }
2070
David Brazdil95177982015-10-30 12:56:58 -05002071 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002072 to->SetGraph(outer_graph);
2073 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002074 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002075 // Only `to` can become a back edge, as the inlined blocks
2076 // are predecessors of `to`.
2077 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002078
David Brazdil3f523062016-02-29 16:53:33 +00002079 // Update all predecessors of the exit block (now the `to` block)
2080 // to not `HReturn` but `HGoto` instead.
2081 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
2082 if (to->GetPredecessors().size() == 1) {
2083 HBasicBlock* predecessor = to->GetPredecessors()[0];
2084 HInstruction* last = predecessor->GetLastInstruction();
2085 if (!returns_void) {
2086 return_value = last->InputAt(0);
2087 }
2088 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2089 predecessor->RemoveInstruction(last);
2090 } else {
2091 if (!returns_void) {
2092 // There will be multiple returns.
2093 return_value = new (allocator) HPhi(
2094 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2095 to->AddPhi(return_value->AsPhi());
2096 }
2097 for (HBasicBlock* predecessor : to->GetPredecessors()) {
2098 HInstruction* last = predecessor->GetLastInstruction();
2099 if (!returns_void) {
2100 DCHECK(last->IsReturn());
2101 return_value->AsPhi()->AddInput(last->InputAt(0));
2102 }
2103 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2104 predecessor->RemoveInstruction(last);
2105 }
2106 }
2107 }
David Brazdil05144f42015-04-16 15:18:00 +01002108
2109 // Walk over the entry block and:
2110 // - Move constants from the entry block to the outer_graph's entry block,
2111 // - Replace HParameterValue instructions with their real value.
2112 // - Remove suspend checks, that hold an environment.
2113 // We must do this after the other blocks have been inlined, otherwise ids of
2114 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002115 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002116 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2117 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002118 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002119 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002120 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002121 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002122 replacement = outer_graph->GetIntConstant(
2123 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002124 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002125 replacement = outer_graph->GetLongConstant(
2126 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002127 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002128 replacement = outer_graph->GetFloatConstant(
2129 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002130 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002131 replacement = outer_graph->GetDoubleConstant(
2132 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002133 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002134 if (kIsDebugBuild
2135 && invoke->IsInvokeStaticOrDirect()
2136 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2137 // Ensure we do not use the last input of `invoke`, as it
2138 // contains a clinit check which is not an actual argument.
2139 size_t last_input_index = invoke->InputCount() - 1;
2140 DCHECK(parameter_index != last_input_index);
2141 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002142 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002143 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002144 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002145 } else {
2146 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2147 entry_block_->RemoveInstruction(current);
2148 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002149 if (replacement != nullptr) {
2150 current->ReplaceWith(replacement);
2151 // If the current is the return value then we need to update the latter.
2152 if (current == return_value) {
2153 DCHECK_EQ(entry_block_, return_value->GetBlock());
2154 return_value = replacement;
2155 }
2156 }
2157 }
2158
Calin Juravle2e768302015-07-28 14:41:11 +00002159 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002160}
2161
Mingyao Yang3584bce2015-05-19 16:01:59 -07002162/*
2163 * Loop will be transformed to:
2164 * old_pre_header
2165 * |
2166 * if_block
2167 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002168 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002169 * \ /
2170 * new_pre_header
2171 * |
2172 * header
2173 */
2174void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2175 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002176 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002177
Aart Bik3fc7f352015-11-20 22:03:03 -08002178 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002179 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002180 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2181 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002182 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2183 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002184 AddBlock(true_block);
2185 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002186 AddBlock(new_pre_header);
2187
Aart Bik3fc7f352015-11-20 22:03:03 -08002188 header->ReplacePredecessor(old_pre_header, new_pre_header);
2189 old_pre_header->successors_.clear();
2190 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002191
Aart Bik3fc7f352015-11-20 22:03:03 -08002192 old_pre_header->AddSuccessor(if_block);
2193 if_block->AddSuccessor(true_block); // True successor
2194 if_block->AddSuccessor(false_block); // False successor
2195 true_block->AddSuccessor(new_pre_header);
2196 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002197
Aart Bik3fc7f352015-11-20 22:03:03 -08002198 old_pre_header->dominated_blocks_.push_back(if_block);
2199 if_block->SetDominator(old_pre_header);
2200 if_block->dominated_blocks_.push_back(true_block);
2201 true_block->SetDominator(if_block);
2202 if_block->dominated_blocks_.push_back(false_block);
2203 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002204 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002205 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002206 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002207 header->SetDominator(new_pre_header);
2208
Aart Bik3fc7f352015-11-20 22:03:03 -08002209 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002210 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002211 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002212 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002213 reverse_post_order_[index_of_header++] = true_block;
2214 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002215 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002216
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002217 // The pre_header can never be a back edge of a loop.
2218 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2219 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2220 UpdateLoopAndTryInformationOfNewBlock(
2221 if_block, old_pre_header, /* replace_if_back_edge */ false);
2222 UpdateLoopAndTryInformationOfNewBlock(
2223 true_block, old_pre_header, /* replace_if_back_edge */ false);
2224 UpdateLoopAndTryInformationOfNewBlock(
2225 false_block, old_pre_header, /* replace_if_back_edge */ false);
2226 UpdateLoopAndTryInformationOfNewBlock(
2227 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002228}
2229
David Brazdilf5552582015-12-27 13:36:12 +00002230static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2231 SHARED_REQUIRES(Locks::mutator_lock_) {
2232 if (rti.IsValid()) {
2233 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2234 << " upper_bound_rti: " << upper_bound_rti
2235 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002236 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2237 << " upper_bound_rti: " << upper_bound_rti
2238 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002239 }
2240}
2241
Calin Juravle2e768302015-07-28 14:41:11 +00002242void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2243 if (kIsDebugBuild) {
2244 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2245 ScopedObjectAccess soa(Thread::Current());
2246 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2247 if (IsBoundType()) {
2248 // Having the test here spares us from making the method virtual just for
2249 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002250 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002251 }
2252 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002253 reference_type_handle_ = rti.GetTypeHandle();
2254 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002255}
2256
David Brazdilf5552582015-12-27 13:36:12 +00002257void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2258 if (kIsDebugBuild) {
2259 ScopedObjectAccess soa(Thread::Current());
2260 DCHECK(upper_bound.IsValid());
2261 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2262 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2263 }
2264 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002265 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002266}
2267
Vladimir Markoa1de9182016-02-25 11:37:38 +00002268ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002269 if (kIsDebugBuild) {
2270 ScopedObjectAccess soa(Thread::Current());
2271 DCHECK(IsValidHandle(type_handle));
Aart Bik8b3f9b22016-04-06 11:22:12 -07002272 DCHECK(!type_handle->IsErroneous());
Aart Bikf417ff42016-04-25 12:51:37 -07002273 DCHECK(!type_handle->IsArrayClass() || !type_handle->GetComponentType()->IsErroneous());
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002274 if (!is_exact) {
2275 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2276 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2277 }
Calin Juravle2e768302015-07-28 14:41:11 +00002278 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002279 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002280}
2281
Calin Juravleacf735c2015-02-12 15:25:22 +00002282std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2283 ScopedObjectAccess soa(Thread::Current());
2284 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002285 << " is_valid=" << rhs.IsValid()
2286 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002287 << " is_exact=" << rhs.IsExact()
2288 << " ]";
2289 return os;
2290}
2291
Mark Mendellc4701932015-04-10 13:18:51 -04002292bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2293 // For now, assume that instructions in different blocks may use the
2294 // environment.
2295 // TODO: Use the control flow to decide if this is true.
2296 if (GetBlock() != other->GetBlock()) {
2297 return true;
2298 }
2299
2300 // We know that we are in the same block. Walk from 'this' to 'other',
2301 // checking to see if there is any instruction with an environment.
2302 HInstruction* current = this;
2303 for (; current != other && current != nullptr; current = current->GetNext()) {
2304 // This is a conservative check, as the instruction result may not be in
2305 // the referenced environment.
2306 if (current->HasEnvironment()) {
2307 return true;
2308 }
2309 }
2310
2311 // We should have been called with 'this' before 'other' in the block.
2312 // Just confirm this.
2313 DCHECK(current != nullptr);
2314 return false;
2315}
2316
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002317void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002318 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2319 IntrinsicSideEffects side_effects,
2320 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002321 intrinsic_ = intrinsic;
2322 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002323
Aart Bik5d75afe2015-12-14 11:57:01 -08002324 // Adjust method's side effects from intrinsic table.
2325 switch (side_effects) {
2326 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2327 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2328 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2329 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2330 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002331
2332 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2333 opt.SetDoesNotNeedDexCache();
2334 opt.SetDoesNotNeedEnvironment();
2335 } else {
2336 // If we need an environment, that means there will be a call, which can trigger GC.
2337 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2338 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002339 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002340 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002341}
2342
David Brazdil6de19382016-01-08 17:37:10 +00002343bool HNewInstance::IsStringAlloc() const {
2344 ScopedObjectAccess soa(Thread::Current());
2345 return GetReferenceTypeInfo().IsStringClass();
2346}
2347
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002348bool HInvoke::NeedsEnvironment() const {
2349 if (!IsIntrinsic()) {
2350 return true;
2351 }
2352 IntrinsicOptimizations opt(*this);
2353 return !opt.GetDoesNotNeedEnvironment();
2354}
2355
Vladimir Markodc151b22015-10-15 18:02:30 +01002356bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2357 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002358 return false;
2359 }
2360 if (!IsIntrinsic()) {
2361 return true;
2362 }
2363 IntrinsicOptimizations opt(*this);
2364 return !opt.GetDoesNotNeedDexCache();
2365}
2366
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002367void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2368 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2369 input->AddUseAt(this, index);
2370 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2371 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2372 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2373 InputRecordAt(i).GetUseNode()->SetIndex(i);
2374 }
2375}
2376
Vladimir Markob554b5a2015-11-06 12:57:55 +00002377void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2378 RemoveAsUserOfInput(index);
2379 inputs_.erase(inputs_.begin() + index);
2380 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2381 for (size_t i = index, e = InputCount(); i < e; ++i) {
2382 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2383 InputRecordAt(i).GetUseNode()->SetIndex(i);
2384 }
2385}
2386
Vladimir Markof64242a2015-12-01 14:58:23 +00002387std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2388 switch (rhs) {
2389 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2390 return os << "string_init";
2391 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2392 return os << "recursive";
2393 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2394 return os << "direct";
2395 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2396 return os << "direct_fixup";
2397 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2398 return os << "dex_cache_pc_relative";
2399 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2400 return os << "dex_cache_via_method";
2401 default:
2402 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2403 UNREACHABLE();
2404 }
2405}
2406
Vladimir Markofbb184a2015-11-13 14:47:00 +00002407std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2408 switch (rhs) {
2409 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2410 return os << "explicit";
2411 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2412 return os << "implicit";
2413 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2414 return os << "none";
2415 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002416 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2417 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002418 }
2419}
2420
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002421bool HLoadString::InstructionDataEquals(HInstruction* other) const {
2422 HLoadString* other_load_string = other->AsLoadString();
2423 if (string_index_ != other_load_string->string_index_ ||
2424 GetPackedFields() != other_load_string->GetPackedFields()) {
2425 return false;
2426 }
2427 LoadKind load_kind = GetLoadKind();
2428 if (HasAddress(load_kind)) {
2429 return GetAddress() == other_load_string->GetAddress();
2430 } else if (HasStringReference(load_kind)) {
2431 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2432 } else {
2433 DCHECK(HasDexCacheReference(load_kind)) << load_kind;
2434 // If the string indexes and dex files are the same, dex cache element offsets
2435 // must also be the same, so we don't need to compare them.
2436 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2437 }
2438}
2439
2440void HLoadString::SetLoadKindInternal(LoadKind load_kind) {
2441 // Once sharpened, the load kind should not be changed again.
2442 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2443 SetPackedField<LoadKindField>(load_kind);
2444
2445 if (load_kind != LoadKind::kDexCacheViaMethod) {
2446 RemoveAsUserOfInput(0u);
2447 SetRawInputAt(0u, nullptr);
2448 }
2449 if (!NeedsEnvironment()) {
2450 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002451 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002452 }
2453}
2454
2455std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2456 switch (rhs) {
2457 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2458 return os << "BootImageLinkTimeAddress";
2459 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2460 return os << "BootImageLinkTimePcRelative";
2461 case HLoadString::LoadKind::kBootImageAddress:
2462 return os << "BootImageAddress";
2463 case HLoadString::LoadKind::kDexCacheAddress:
2464 return os << "DexCacheAddress";
2465 case HLoadString::LoadKind::kDexCachePcRelative:
2466 return os << "DexCachePcRelative";
2467 case HLoadString::LoadKind::kDexCacheViaMethod:
2468 return os << "DexCacheViaMethod";
2469 default:
2470 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2471 UNREACHABLE();
2472 }
2473}
2474
Mark Mendellc4701932015-04-10 13:18:51 -04002475void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002476 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2477 HEnvironment* user = use.GetUser();
2478 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002479 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002480 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002481}
2482
Roland Levillainc9b21f82016-03-23 16:36:59 +00002483// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002484HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2485 ArenaAllocator* allocator = GetArena();
2486
2487 if (cond->IsCondition() &&
2488 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2489 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2490 HInstruction* lhs = cond->InputAt(0);
2491 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002492 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002493 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2494 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2495 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2496 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2497 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2498 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2499 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2500 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2501 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2502 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2503 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002504 default:
2505 LOG(FATAL) << "Unexpected condition";
2506 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002507 }
2508 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2509 return replacement;
2510 } else if (cond->IsIntConstant()) {
2511 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002512 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002513 return GetIntConstant(1);
2514 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002515 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002516 return GetIntConstant(0);
2517 }
2518 } else {
2519 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2520 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2521 return replacement;
2522 }
2523}
2524
Roland Levillainc9285912015-12-18 10:38:42 +00002525std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2526 os << "["
2527 << " source=" << rhs.GetSource()
2528 << " destination=" << rhs.GetDestination()
2529 << " type=" << rhs.GetType()
2530 << " instruction=";
2531 if (rhs.GetInstruction() != nullptr) {
2532 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2533 } else {
2534 os << "null";
2535 }
2536 os << " ]";
2537 return os;
2538}
2539
Roland Levillain86503782016-02-11 19:07:30 +00002540std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2541 switch (rhs) {
2542 case TypeCheckKind::kUnresolvedCheck:
2543 return os << "unresolved_check";
2544 case TypeCheckKind::kExactCheck:
2545 return os << "exact_check";
2546 case TypeCheckKind::kClassHierarchyCheck:
2547 return os << "class_hierarchy_check";
2548 case TypeCheckKind::kAbstractClassCheck:
2549 return os << "abstract_class_check";
2550 case TypeCheckKind::kInterfaceCheck:
2551 return os << "interface_check";
2552 case TypeCheckKind::kArrayObjectCheck:
2553 return os << "array_object_check";
2554 case TypeCheckKind::kArrayCheck:
2555 return os << "array_check";
2556 default:
2557 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2558 UNREACHABLE();
2559 }
2560}
2561
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002562} // namespace art