blob: b90ff590dd8ef87a727491dbb7718dfaa153b825 [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
Andreas Gampec6ea7d02017-02-01 16:46:28 -080020#include "art_method-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "base/bit_utils.h"
22#include "base/bit_vector-inl.h"
23#include "base/stl_util.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080024#include "class_linker-inl.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040025#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000026#include "common_dominator.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010027#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010028#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070029#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070030#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000031
32namespace art {
33
Roland Levillain31dd3d62016-02-16 12:21:02 +000034// Enable floating-point static evaluation during constant folding
35// only if all floating-point operations and constants evaluate in the
36// range and precision of the type used (i.e., 32-bit float, 64-bit
37// double).
38static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
39
Mathieu Chartiere8a3c572016-10-11 16:52:17 -070040void HGraph::InitializeInexactObjectRTI(VariableSizedHandleScope* handles) {
David Brazdilbadd8262016-02-02 16:28:56 +000041 ScopedObjectAccess soa(Thread::Current());
42 // Create the inexact Object reference type and store it in the HGraph.
43 ClassLinker* linker = Runtime::Current()->GetClassLinker();
44 inexact_object_rti_ = ReferenceTypeInfo::Create(
45 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
46 /* is_exact */ false);
47}
48
Nicolas Geoffray818f2102014-02-18 16:43:35 +000049void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010050 block->SetBlockId(blocks_.size());
51 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000052}
53
Nicolas Geoffray804d0932014-05-02 08:46:00 +010054void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010055 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
56 DCHECK_EQ(visited->GetHighestBitSet(), -1);
57
Vladimir Marko69d310e2017-10-09 14:12:23 +010058 // Allocate memory from local ScopedArenaAllocator.
59 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Marko1f8695c2015-09-24 13:11:31 +010060 // Nodes that we're currently visiting, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +010061 ArenaBitVector visiting(
62 &allocator, blocks_.size(), /* expandable */ false, kArenaAllocGraphBuilder);
63 visiting.ClearAllBits();
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +010065 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
66 0u,
67 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010068 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko69d310e2017-10-09 14:12:23 +010069 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010070 constexpr size_t kDefaultWorklistSize = 8;
71 worklist.reserve(kDefaultWorklistSize);
72 visited->SetBit(entry_block_->GetBlockId());
73 visiting.SetBit(entry_block_->GetBlockId());
74 worklist.push_back(entry_block_);
75
76 while (!worklist.empty()) {
77 HBasicBlock* current = worklist.back();
78 uint32_t current_id = current->GetBlockId();
79 if (successors_visited[current_id] == current->GetSuccessors().size()) {
80 visiting.ClearBit(current_id);
81 worklist.pop_back();
82 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010083 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
84 uint32_t successor_id = successor->GetBlockId();
85 if (visiting.IsBitSet(successor_id)) {
86 DCHECK(ContainsElement(worklist, successor));
87 successor->AddBackEdge(current);
88 } else if (!visited->IsBitSet(successor_id)) {
89 visited->SetBit(successor_id);
90 visiting.SetBit(successor_id);
91 worklist.push_back(successor);
92 }
93 }
94 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000095}
96
Artem Serov21c7e6f2017-07-27 16:04:42 +010097// Remove the environment use records of the instruction for users.
98void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010099 for (HEnvironment* environment = instruction->GetEnvironment();
100 environment != nullptr;
101 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000102 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +0000103 if (environment->GetInstructionAt(i) != nullptr) {
104 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000105 }
106 }
107 }
108}
109
Artem Serov21c7e6f2017-07-27 16:04:42 +0100110// Return whether the instruction has an environment and it's used by others.
111bool HasEnvironmentUsedByOthers(HInstruction* instruction) {
112 for (HEnvironment* environment = instruction->GetEnvironment();
113 environment != nullptr;
114 environment = environment->GetParent()) {
115 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
116 HInstruction* user = environment->GetInstructionAt(i);
117 if (user != nullptr) {
118 return true;
119 }
120 }
121 }
122 return false;
123}
124
125// Reset environment records of the instruction itself.
126void ResetEnvironmentInputRecords(HInstruction* instruction) {
127 for (HEnvironment* environment = instruction->GetEnvironment();
128 environment != nullptr;
129 environment = environment->GetParent()) {
130 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
131 DCHECK(environment->GetHolder() == instruction);
132 if (environment->GetInstructionAt(i) != nullptr) {
133 environment->SetRawEnvAt(i, nullptr);
134 }
135 }
136 }
137}
138
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000139static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100140 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000141 RemoveEnvironmentUses(instruction);
142}
143
Roland Levillainfc600dc2014-12-02 17:16:31 +0000144void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100145 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000146 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100147 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000148 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100149 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000150 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
151 RemoveAsUser(it.Current());
152 }
153 }
154 }
155}
156
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100157void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100158 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000159 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100160 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000161 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100162 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000163 for (HBasicBlock* successor : block->GetSuccessors()) {
164 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000165 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100166 // Remove the block from the list of blocks, so that further analyses
167 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100168 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600169 if (block->IsExitBlock()) {
170 SetExitBlock(nullptr);
171 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000172 // Mark the block as removed. This is used by the HGraphBuilder to discard
173 // the block as a branch target.
174 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000175 }
176 }
177}
178
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000179GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Marko69d310e2017-10-09 14:12:23 +0100180 // Allocate memory from local ScopedArenaAllocator.
181 ScopedArenaAllocator allocator(GetArenaStack());
182
183 ArenaBitVector visited(&allocator, blocks_.size(), false, kArenaAllocGraphBuilder);
184 visited.ClearAllBits();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000185
David Brazdil86ea7ee2016-02-16 09:26:07 +0000186 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000187 FindBackEdges(&visited);
188
David Brazdil86ea7ee2016-02-16 09:26:07 +0000189 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000190 // the initial DFS as users from other instructions, so that
191 // users can be safely removed before uses later.
192 RemoveInstructionsAsUsersFromDeadBlocks(visited);
193
David Brazdil86ea7ee2016-02-16 09:26:07 +0000194 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000195 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000196 // predecessors list of live blocks.
197 RemoveDeadBlocks(visited);
198
David Brazdil86ea7ee2016-02-16 09:26:07 +0000199 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100200 // dominators and the reverse post order.
201 SimplifyCFG();
202
David Brazdil86ea7ee2016-02-16 09:26:07 +0000203 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100204 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000205
David Brazdil86ea7ee2016-02-16 09:26:07 +0000206 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000207 // set the loop information on each block.
208 GraphAnalysisResult result = AnalyzeLoops();
209 if (result != kAnalysisSuccess) {
210 return result;
211 }
212
David Brazdil86ea7ee2016-02-16 09:26:07 +0000213 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000214 // which needs the information to build catch block phis from values of
215 // locals at throwing instructions inside try blocks.
216 ComputeTryBlockInformation();
217
218 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100219}
220
221void HGraph::ClearDominanceInformation() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100222 for (HBasicBlock* block : GetReversePostOrder()) {
223 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100224 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100225 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100226}
227
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000228void HGraph::ClearLoopInformation() {
229 SetHasIrreducibleLoops(false);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100230 for (HBasicBlock* block : GetReversePostOrder()) {
231 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000232 }
233}
234
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100235void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000236 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100237 dominator_ = nullptr;
238}
239
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000240HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
241 HInstruction* instruction = GetFirstInstruction();
242 while (instruction->IsParallelMove()) {
243 instruction = instruction->GetNext();
244 }
245 return instruction;
246}
247
David Brazdil3f4a5222016-05-06 12:46:21 +0100248static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
249 DCHECK(ContainsElement(block->GetSuccessors(), successor));
250
251 HBasicBlock* old_dominator = successor->GetDominator();
252 HBasicBlock* new_dominator =
253 (old_dominator == nullptr) ? block
254 : CommonDominator::ForPair(old_dominator, block);
255
256 if (old_dominator == new_dominator) {
257 return false;
258 } else {
259 successor->SetDominator(new_dominator);
260 return true;
261 }
262}
263
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100264void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100265 DCHECK(reverse_post_order_.empty());
266 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100267 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100268
Vladimir Marko69d310e2017-10-09 14:12:23 +0100269 // Allocate memory from local ScopedArenaAllocator.
270 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Markod76d1392015-09-23 16:07:14 +0100271 // Number of visits of a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100272 ScopedArenaVector<size_t> visits(blocks_.size(), 0u, allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100273 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100274 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
275 0u,
276 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100277 // Nodes for which we need to visit successors.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100278 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100279 constexpr size_t kDefaultWorklistSize = 8;
280 worklist.reserve(kDefaultWorklistSize);
281 worklist.push_back(entry_block_);
282
283 while (!worklist.empty()) {
284 HBasicBlock* current = worklist.back();
285 uint32_t current_id = current->GetBlockId();
286 if (successors_visited[current_id] == current->GetSuccessors().size()) {
287 worklist.pop_back();
288 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100289 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100290 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100291
292 // Once all the forward edges have been visited, we know the immediate
293 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100294 if (++visits[successor->GetBlockId()] ==
295 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100296 reverse_post_order_.push_back(successor);
297 worklist.push_back(successor);
298 }
299 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000300 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000301
David Brazdil3f4a5222016-05-06 12:46:21 +0100302 // Check if the graph has back edges not dominated by their respective headers.
303 // If so, we need to update the dominators of those headers and recursively of
304 // their successors. We do that with a fix-point iteration over all blocks.
305 // The algorithm is guaranteed to terminate because it loops only if the sum
306 // of all dominator chains has decreased in the current iteration.
307 bool must_run_fix_point = false;
308 for (HBasicBlock* block : blocks_) {
309 if (block != nullptr &&
310 block->IsLoopHeader() &&
311 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
312 must_run_fix_point = true;
313 break;
314 }
315 }
316 if (must_run_fix_point) {
317 bool update_occurred = true;
318 while (update_occurred) {
319 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100320 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100321 for (HBasicBlock* successor : block->GetSuccessors()) {
322 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
323 }
324 }
325 }
326 }
327
328 // Make sure that there are no remaining blocks whose dominator information
329 // needs to be updated.
330 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100331 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100332 for (HBasicBlock* successor : block->GetSuccessors()) {
333 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
334 }
335 }
336 }
337
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000338 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000339 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100340 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000341 if (!block->IsEntryBlock()) {
342 block->GetDominator()->AddDominatedBlock(block);
343 }
344 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000345}
346
David Brazdilfc6a86a2015-06-26 10:33:45 +0000347HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100348 HBasicBlock* new_block = new (allocator_) HBasicBlock(this, successor->GetDexPc());
David Brazdil3e187382015-06-26 09:59:52 +0000349 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000350 // Use `InsertBetween` to ensure the predecessor index and successor index of
351 // `block` and `successor` are preserved.
352 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000353 return new_block;
354}
355
356void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
357 // Insert a new node between `block` and `successor` to split the
358 // critical edge.
359 HBasicBlock* new_block = SplitEdge(block, successor);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100360 new_block->AddInstruction(new (allocator_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100361 if (successor->IsLoopHeader()) {
362 // If we split at a back edge boundary, make the new block the back edge.
363 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000364 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100365 info->RemoveBackEdge(block);
366 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100367 }
368 }
369}
370
Artem Serovc73ee372017-07-31 15:08:40 +0100371// Reorder phi inputs to match reordering of the block's predecessors.
372static void FixPhisAfterPredecessorsReodering(HBasicBlock* block, size_t first, size_t second) {
373 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
374 HPhi* phi = it.Current()->AsPhi();
375 HInstruction* first_instr = phi->InputAt(first);
376 HInstruction* second_instr = phi->InputAt(second);
377 phi->ReplaceInput(first_instr, second);
378 phi->ReplaceInput(second_instr, first);
379 }
380}
381
382// Make sure that the first predecessor of a loop header is the incoming block.
383void HGraph::OrderLoopHeaderPredecessors(HBasicBlock* header) {
384 DCHECK(header->IsLoopHeader());
385 HLoopInformation* info = header->GetLoopInformation();
386 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
387 HBasicBlock* to_swap = header->GetPredecessors()[0];
388 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
389 HBasicBlock* predecessor = header->GetPredecessors()[pred];
390 if (!info->IsBackEdge(*predecessor)) {
391 header->predecessors_[pred] = to_swap;
392 header->predecessors_[0] = predecessor;
393 FixPhisAfterPredecessorsReodering(header, 0, pred);
394 break;
395 }
396 }
397 }
398}
399
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100400void HGraph::SimplifyLoop(HBasicBlock* header) {
401 HLoopInformation* info = header->GetLoopInformation();
402
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100403 // Make sure the loop has only one pre header. This simplifies SSA building by having
404 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000405 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
406 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000407 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000408 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100409 HBasicBlock* pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100410 AddBlock(pre_header);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100411 pre_header->AddInstruction(new (allocator_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100412
Vladimir Marko60584552015-09-03 13:35:12 +0000413 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100414 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100415 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100416 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100417 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100418 }
419 }
420 pre_header->AddSuccessor(header);
421 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100422
Artem Serovc73ee372017-07-31 15:08:40 +0100423 OrderLoopHeaderPredecessors(header);
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100424
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100425 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000426 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
427 // Called from DeadBlockElimination. Update SuspendCheck pointer.
428 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100429 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100430}
431
David Brazdilffee3d32015-07-06 11:48:53 +0100432void HGraph::ComputeTryBlockInformation() {
433 // Iterate in reverse post order to propagate try membership information from
434 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100435 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100436 if (block->IsEntryBlock() || block->IsCatchBlock()) {
437 // Catch blocks after simplification have only exceptional predecessors
438 // and hence are never in tries.
439 continue;
440 }
441
442 // Infer try membership from the first predecessor. Having simplified loops,
443 // the first predecessor can never be a back edge and therefore it must have
444 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100445 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100446 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100447 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000448 if (try_entry != nullptr &&
449 (block->GetTryCatchInformation() == nullptr ||
450 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
451 // We are either setting try block membership for the first time or it
452 // has changed.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100453 block->SetTryCatchInformation(new (allocator_) TryCatchInformation(*try_entry));
David Brazdilec16f792015-08-19 15:04:01 +0100454 }
David Brazdilffee3d32015-07-06 11:48:53 +0100455 }
456}
457
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100458void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000459// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100460 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000461 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100462 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
463 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
464 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
465 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100466 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000467 if (block->GetSuccessors().size() > 1) {
468 // Only split normal-flow edges. We cannot split exceptional edges as they
469 // are synthesized (approximate real control flow), and we do not need to
470 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000471 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
472 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
473 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100474 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000475 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000476 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
477 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000478 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000479 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100480 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000481 // SplitCriticalEdge could have invalidated the `normal_successors`
482 // ArrayRef. We must re-acquire it.
483 normal_successors = block->GetNormalSuccessors();
484 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
485 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100486 }
487 }
488 }
489 if (block->IsLoopHeader()) {
490 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000491 } else if (!block->IsEntryBlock() &&
492 block->GetFirstInstruction() != nullptr &&
493 block->GetFirstInstruction()->IsSuspendCheck()) {
494 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000495 // a loop got dismantled. Just remove the suspend check.
496 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100497 }
498 }
499}
500
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000501GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100502 // We iterate post order to ensure we visit inner loops before outer loops.
503 // `PopulateRecursive` needs this guarantee to know whether a natural loop
504 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100505 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100506 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100507 if (block->IsCatchBlock()) {
508 // TODO: Dealing with exceptional back edges could be tricky because
509 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000510 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100511 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000512 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100513 }
514 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000515 return kAnalysisSuccess;
516}
517
518void HLoopInformation::Dump(std::ostream& os) {
519 os << "header: " << header_->GetBlockId() << std::endl;
520 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
521 for (HBasicBlock* block : back_edges_) {
522 os << "back edge: " << block->GetBlockId() << std::endl;
523 }
524 for (HBasicBlock* block : header_->GetPredecessors()) {
525 os << "predecessor: " << block->GetBlockId() << std::endl;
526 }
527 for (uint32_t idx : blocks_.Indexes()) {
528 os << " in loop: " << idx << std::endl;
529 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100530}
531
David Brazdil8d5b8b22015-03-24 10:51:52 +0000532void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000533 // New constants are inserted before the SuspendCheck at the bottom of the
534 // entry block. Note that this method can be called from the graph builder and
535 // the entry block therefore may not end with SuspendCheck->Goto yet.
536 HInstruction* insert_before = nullptr;
537
538 HInstruction* gota = entry_block_->GetLastInstruction();
539 if (gota != nullptr && gota->IsGoto()) {
540 HInstruction* suspend_check = gota->GetPrevious();
541 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
542 insert_before = suspend_check;
543 } else {
544 insert_before = gota;
545 }
546 }
547
548 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000549 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000550 } else {
551 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000552 }
553}
554
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600555HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100556 // For simplicity, don't bother reviving the cached null constant if it is
557 // not null and not in a block. Otherwise, we need to clear the instruction
558 // id and/or any invariants the graph is assuming when adding new instructions.
559 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100560 cached_null_constant_ = new (allocator_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000561 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000562 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000563 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000564 if (kIsDebugBuild) {
565 ScopedObjectAccess soa(Thread::Current());
566 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
567 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000568 return cached_null_constant_;
569}
570
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100571HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100572 // For simplicity, don't bother reviving the cached current method if it is
573 // not null and not in a block. Otherwise, we need to clear the instruction
574 // id and/or any invariants the graph is assuming when adding new instructions.
575 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100576 cached_current_method_ = new (allocator_) HCurrentMethod(
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100577 Is64BitInstructionSet(instruction_set_) ? DataType::Type::kInt64 : DataType::Type::kInt32,
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600578 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100579 if (entry_block_->GetFirstInstruction() == nullptr) {
580 entry_block_->AddInstruction(cached_current_method_);
581 } else {
582 entry_block_->InsertInstructionBefore(
583 cached_current_method_, entry_block_->GetFirstInstruction());
584 }
585 }
586 return cached_current_method_;
587}
588
Igor Murashkind01745e2017-04-05 16:40:31 -0700589const char* HGraph::GetMethodName() const {
590 const DexFile::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
591 return dex_file_.GetMethodName(method_id);
592}
593
594std::string HGraph::PrettyMethod(bool with_signature) const {
595 return dex_file_.PrettyMethod(method_idx_, with_signature);
596}
597
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100598HConstant* HGraph::GetConstant(DataType::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000599 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100600 case DataType::Type::kBool:
David Brazdil8d5b8b22015-03-24 10:51:52 +0000601 DCHECK(IsUint<1>(value));
602 FALLTHROUGH_INTENDED;
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100603 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100604 case DataType::Type::kInt8:
605 case DataType::Type::kUint16:
606 case DataType::Type::kInt16:
607 case DataType::Type::kInt32:
608 DCHECK(IsInt(DataType::Size(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600609 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000610
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100611 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600612 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000613
614 default:
615 LOG(FATAL) << "Unsupported constant type";
616 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000617 }
David Brazdil46e2a392015-03-16 17:31:52 +0000618}
619
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000620void HGraph::CacheFloatConstant(HFloatConstant* constant) {
621 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
622 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
623 cached_float_constants_.Overwrite(value, constant);
624}
625
626void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
627 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
628 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
629 cached_double_constants_.Overwrite(value, constant);
630}
631
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000632void HLoopInformation::Add(HBasicBlock* block) {
633 blocks_.SetBit(block->GetBlockId());
634}
635
David Brazdil46e2a392015-03-16 17:31:52 +0000636void HLoopInformation::Remove(HBasicBlock* block) {
637 blocks_.ClearBit(block->GetBlockId());
638}
639
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100640void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
641 if (blocks_.IsBitSet(block->GetBlockId())) {
642 return;
643 }
644
645 blocks_.SetBit(block->GetBlockId());
646 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100647 if (block->IsLoopHeader()) {
648 // We're visiting loops in post-order, so inner loops must have been
649 // populated already.
650 DCHECK(block->GetLoopInformation()->IsPopulated());
651 if (block->GetLoopInformation()->IsIrreducible()) {
652 contains_irreducible_loop_ = true;
653 }
654 }
Vladimir Marko60584552015-09-03 13:35:12 +0000655 for (HBasicBlock* predecessor : block->GetPredecessors()) {
656 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100657 }
658}
659
David Brazdilc2e8af92016-04-05 17:15:19 +0100660void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
661 size_t block_id = block->GetBlockId();
662
663 // If `block` is in `finalized`, we know its membership in the loop has been
664 // decided and it does not need to be revisited.
665 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000666 return;
667 }
668
David Brazdilc2e8af92016-04-05 17:15:19 +0100669 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000670 if (block->IsLoopHeader()) {
671 // If we hit a loop header in an irreducible loop, we first check if the
672 // pre header of that loop belongs to the currently analyzed loop. If it does,
673 // then we visit the back edges.
674 // Note that we cannot use GetPreHeader, as the loop may have not been populated
675 // yet.
676 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100677 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000678 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000679 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100680 blocks_.SetBit(block_id);
681 finalized->SetBit(block_id);
682 is_finalized = true;
683
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000684 HLoopInformation* info = block->GetLoopInformation();
685 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100686 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000687 }
688 }
689 } else {
690 // Visit all predecessors. If one predecessor is part of the loop, this
691 // block is also part of this loop.
692 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100693 PopulateIrreducibleRecursive(predecessor, finalized);
694 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000695 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100696 blocks_.SetBit(block_id);
697 finalized->SetBit(block_id);
698 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000699 }
700 }
701 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100702
703 // All predecessors have been recursively visited. Mark finalized if not marked yet.
704 if (!is_finalized) {
705 finalized->SetBit(block_id);
706 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000707}
708
709void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100710 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000711 // Populate this loop: starting with the back edge, recursively add predecessors
712 // that are not already part of that loop. Set the header as part of the loop
713 // to end the recursion.
714 // This is a recursive implementation of the algorithm described in
715 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100716 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000717 blocks_.SetBit(header_->GetBlockId());
718 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100719
David Brazdil3f4a5222016-05-06 12:46:21 +0100720 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100721
722 if (is_irreducible_loop) {
Vladimir Marko69d310e2017-10-09 14:12:23 +0100723 // Allocate memory from local ScopedArenaAllocator.
724 ScopedArenaAllocator allocator(graph->GetArenaStack());
725 ArenaBitVector visited(&allocator,
David Brazdilc2e8af92016-04-05 17:15:19 +0100726 graph->GetBlocks().size(),
727 /* expandable */ false,
728 kArenaAllocGraphBuilder);
Vladimir Marko69d310e2017-10-09 14:12:23 +0100729 visited.ClearAllBits();
David Brazdil5a620592016-05-05 11:27:03 +0100730 // Stop marking blocks at the loop header.
731 visited.SetBit(header_->GetBlockId());
732
David Brazdilc2e8af92016-04-05 17:15:19 +0100733 for (HBasicBlock* back_edge : GetBackEdges()) {
734 PopulateIrreducibleRecursive(back_edge, &visited);
735 }
736 } else {
737 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000738 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100739 }
David Brazdila4b8c212015-05-07 09:59:30 +0100740 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100741
Vladimir Markofd66c502016-04-18 15:37:01 +0100742 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
743 // When compiling in OSR mode, all loops in the compiled method may be entered
744 // from the interpreter. We treat this OSR entry point just like an extra entry
745 // to an irreducible loop, so we need to mark the method's loops as irreducible.
746 // This does not apply to inlined loops which do not act as OSR entry points.
747 if (suspend_check_ == nullptr) {
748 // Just building the graph in OSR mode, this loop is not inlined. We never build an
749 // inner graph in OSR mode as we can do OSR transition only from the outer method.
750 is_irreducible_loop = true;
751 } else {
752 // Look at the suspend check's environment to determine if the loop was inlined.
753 DCHECK(suspend_check_->HasEnvironment());
754 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
755 is_irreducible_loop = true;
756 }
757 }
758 }
759 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100760 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100761 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100762 graph->SetHasIrreducibleLoops(true);
763 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800764 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +0100765}
766
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100767HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000768 HBasicBlock* block = header_->GetPredecessors()[0];
769 DCHECK(irreducible_ || (block == header_->GetDominator()));
770 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100771}
772
773bool HLoopInformation::Contains(const HBasicBlock& block) const {
774 return blocks_.IsBitSet(block.GetBlockId());
775}
776
777bool HLoopInformation::IsIn(const HLoopInformation& other) const {
778 return other.blocks_.IsBitSet(header_->GetBlockId());
779}
780
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800781bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
782 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700783}
784
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100785size_t HLoopInformation::GetLifetimeEnd() const {
786 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100787 for (HBasicBlock* back_edge : GetBackEdges()) {
788 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100789 }
790 return last_position;
791}
792
David Brazdil3f4a5222016-05-06 12:46:21 +0100793bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
794 for (HBasicBlock* back_edge : GetBackEdges()) {
795 DCHECK(back_edge->GetDominator() != nullptr);
796 if (!header_->Dominates(back_edge)) {
797 return true;
798 }
799 }
800 return false;
801}
802
Anton Shaminf89381f2016-05-16 16:44:13 +0600803bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
804 for (HBasicBlock* back_edge : GetBackEdges()) {
805 if (!block->Dominates(back_edge)) {
806 return false;
807 }
808 }
809 return true;
810}
811
David Sehrc757dec2016-11-04 15:48:34 -0700812
813bool HLoopInformation::HasExitEdge() const {
814 // Determine if this loop has at least one exit edge.
815 HBlocksInLoopReversePostOrderIterator it_loop(*this);
816 for (; !it_loop.Done(); it_loop.Advance()) {
817 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
818 if (!Contains(*successor)) {
819 return true;
820 }
821 }
822 }
823 return false;
824}
825
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100826bool HBasicBlock::Dominates(HBasicBlock* other) const {
827 // Walk up the dominator tree from `other`, to find out if `this`
828 // is an ancestor.
829 HBasicBlock* current = other;
830 while (current != nullptr) {
831 if (current == this) {
832 return true;
833 }
834 current = current->GetDominator();
835 }
836 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100837}
838
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100839static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100840 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100841 for (size_t i = 0; i < inputs.size(); ++i) {
842 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100843 }
844 // Environment should be created later.
845 DCHECK(!instruction->HasEnvironment());
846}
847
Artem Serovcced8ba2017-07-19 18:18:09 +0100848void HBasicBlock::ReplaceAndRemovePhiWith(HPhi* initial, HPhi* replacement) {
849 DCHECK(initial->GetBlock() == this);
850 InsertPhiAfter(replacement, initial);
851 initial->ReplaceWith(replacement);
852 RemovePhi(initial);
853}
854
Roland Levillainccc07a92014-09-16 14:48:16 +0100855void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
856 HInstruction* replacement) {
857 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400858 if (initial->IsControlFlow()) {
859 // We can only replace a control flow instruction with another control flow instruction.
860 DCHECK(replacement->IsControlFlow());
861 DCHECK_EQ(replacement->GetId(), -1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100862 DCHECK_EQ(replacement->GetType(), DataType::Type::kVoid);
Mark Mendell805b3b52015-09-18 14:10:29 -0400863 DCHECK_EQ(initial->GetBlock(), this);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100864 DCHECK_EQ(initial->GetType(), DataType::Type::kVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100865 DCHECK(initial->GetUses().empty());
866 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400867 replacement->SetBlock(this);
868 replacement->SetId(GetGraph()->GetNextInstructionId());
869 instructions_.InsertInstructionBefore(replacement, initial);
870 UpdateInputsUsers(replacement);
871 } else {
872 InsertInstructionBefore(replacement, initial);
873 initial->ReplaceWith(replacement);
874 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100875 RemoveInstruction(initial);
876}
877
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100878static void Add(HInstructionList* instruction_list,
879 HBasicBlock* block,
880 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000881 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000882 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100883 instruction->SetBlock(block);
884 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100885 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100886 instruction_list->AddInstruction(instruction);
887}
888
889void HBasicBlock::AddInstruction(HInstruction* instruction) {
890 Add(&instructions_, this, instruction);
891}
892
893void HBasicBlock::AddPhi(HPhi* phi) {
894 Add(&phis_, this, phi);
895}
896
David Brazdilc3d743f2015-04-22 13:40:50 +0100897void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
898 DCHECK(!cursor->IsPhi());
899 DCHECK(!instruction->IsPhi());
900 DCHECK_EQ(instruction->GetId(), -1);
901 DCHECK_NE(cursor->GetId(), -1);
902 DCHECK_EQ(cursor->GetBlock(), this);
903 DCHECK(!instruction->IsControlFlow());
904 instruction->SetBlock(this);
905 instruction->SetId(GetGraph()->GetNextInstructionId());
906 UpdateInputsUsers(instruction);
907 instructions_.InsertInstructionBefore(instruction, cursor);
908}
909
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100910void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
911 DCHECK(!cursor->IsPhi());
912 DCHECK(!instruction->IsPhi());
913 DCHECK_EQ(instruction->GetId(), -1);
914 DCHECK_NE(cursor->GetId(), -1);
915 DCHECK_EQ(cursor->GetBlock(), this);
916 DCHECK(!instruction->IsControlFlow());
917 DCHECK(!cursor->IsControlFlow());
918 instruction->SetBlock(this);
919 instruction->SetId(GetGraph()->GetNextInstructionId());
920 UpdateInputsUsers(instruction);
921 instructions_.InsertInstructionAfter(instruction, cursor);
922}
923
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100924void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
925 DCHECK_EQ(phi->GetId(), -1);
926 DCHECK_NE(cursor->GetId(), -1);
927 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100928 phi->SetBlock(this);
929 phi->SetId(GetGraph()->GetNextInstructionId());
930 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100931 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100932}
933
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100934static void Remove(HInstructionList* instruction_list,
935 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000936 HInstruction* instruction,
937 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100938 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100939 instruction->SetBlock(nullptr);
940 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000941 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100942 DCHECK(instruction->GetUses().empty());
943 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000944 RemoveAsUser(instruction);
945 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100946}
947
David Brazdil1abb4192015-02-17 18:33:36 +0000948void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100949 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000950 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100951}
952
David Brazdil1abb4192015-02-17 18:33:36 +0000953void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
954 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100955}
956
David Brazdilc7508e92015-04-27 13:28:57 +0100957void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
958 if (instruction->IsPhi()) {
959 RemovePhi(instruction->AsPhi(), ensure_safety);
960 } else {
961 RemoveInstruction(instruction, ensure_safety);
962 }
963}
964
Vladimir Marko69d310e2017-10-09 14:12:23 +0100965void HEnvironment::CopyFrom(ArrayRef<HInstruction* const> locals) {
Vladimir Marko71bf8092015-09-15 15:33:14 +0100966 for (size_t i = 0; i < locals.size(); i++) {
967 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100968 SetRawEnvAt(i, instruction);
969 if (instruction != nullptr) {
970 instruction->AddEnvUseAt(this, i);
971 }
972 }
973}
974
David Brazdiled596192015-01-23 10:39:45 +0000975void HEnvironment::CopyFrom(HEnvironment* env) {
976 for (size_t i = 0; i < env->Size(); i++) {
977 HInstruction* instruction = env->GetInstructionAt(i);
978 SetRawEnvAt(i, instruction);
979 if (instruction != nullptr) {
980 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100981 }
David Brazdiled596192015-01-23 10:39:45 +0000982 }
983}
984
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700985void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
986 HBasicBlock* loop_header) {
987 DCHECK(loop_header->IsLoopHeader());
988 for (size_t i = 0; i < env->Size(); i++) {
989 HInstruction* instruction = env->GetInstructionAt(i);
990 SetRawEnvAt(i, instruction);
991 if (instruction == nullptr) {
992 continue;
993 }
994 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
995 // At the end of the loop pre-header, the corresponding value for instruction
996 // is the first input of the phi.
997 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700998 SetRawEnvAt(i, initial);
999 initial->AddEnvUseAt(this, i);
1000 } else {
1001 instruction->AddEnvUseAt(this, i);
1002 }
1003 }
1004}
1005
David Brazdil1abb4192015-02-17 18:33:36 +00001006void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +01001007 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
1008 HInstruction* user = env_use.GetInstruction();
1009 auto before_env_use_node = env_use.GetBeforeUseNode();
1010 user->env_uses_.erase_after(before_env_use_node);
1011 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001012}
1013
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001014HInstruction::InstructionKind HInstruction::GetKind() const {
1015 return GetKindInternal();
1016}
1017
Calin Juravle77520bc2015-01-12 18:45:46 +00001018HInstruction* HInstruction::GetNextDisregardingMoves() const {
1019 HInstruction* next = GetNext();
1020 while (next != nullptr && next->IsParallelMove()) {
1021 next = next->GetNext();
1022 }
1023 return next;
1024}
1025
1026HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1027 HInstruction* previous = GetPrevious();
1028 while (previous != nullptr && previous->IsParallelMove()) {
1029 previous = previous->GetPrevious();
1030 }
1031 return previous;
1032}
1033
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001034void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001035 if (first_instruction_ == nullptr) {
1036 DCHECK(last_instruction_ == nullptr);
1037 first_instruction_ = last_instruction_ = instruction;
1038 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001039 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001040 last_instruction_->next_ = instruction;
1041 instruction->previous_ = last_instruction_;
1042 last_instruction_ = instruction;
1043 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001044}
1045
David Brazdilc3d743f2015-04-22 13:40:50 +01001046void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1047 DCHECK(Contains(cursor));
1048 if (cursor == first_instruction_) {
1049 cursor->previous_ = instruction;
1050 instruction->next_ = cursor;
1051 first_instruction_ = instruction;
1052 } else {
1053 instruction->previous_ = cursor->previous_;
1054 instruction->next_ = cursor;
1055 cursor->previous_ = instruction;
1056 instruction->previous_->next_ = instruction;
1057 }
1058}
1059
1060void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1061 DCHECK(Contains(cursor));
1062 if (cursor == last_instruction_) {
1063 cursor->next_ = instruction;
1064 instruction->previous_ = cursor;
1065 last_instruction_ = instruction;
1066 } else {
1067 instruction->next_ = cursor->next_;
1068 instruction->previous_ = cursor;
1069 cursor->next_ = instruction;
1070 instruction->next_->previous_ = instruction;
1071 }
1072}
1073
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001074void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1075 if (instruction->previous_ != nullptr) {
1076 instruction->previous_->next_ = instruction->next_;
1077 }
1078 if (instruction->next_ != nullptr) {
1079 instruction->next_->previous_ = instruction->previous_;
1080 }
1081 if (instruction == first_instruction_) {
1082 first_instruction_ = instruction->next_;
1083 }
1084 if (instruction == last_instruction_) {
1085 last_instruction_ = instruction->previous_;
1086 }
1087}
1088
Roland Levillain6b469232014-09-25 10:10:38 +01001089bool HInstructionList::Contains(HInstruction* instruction) const {
1090 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1091 if (it.Current() == instruction) {
1092 return true;
1093 }
1094 }
1095 return false;
1096}
1097
Roland Levillainccc07a92014-09-16 14:48:16 +01001098bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1099 const HInstruction* instruction2) const {
1100 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1101 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1102 if (it.Current() == instruction1) {
1103 return true;
1104 }
1105 if (it.Current() == instruction2) {
1106 return false;
1107 }
1108 }
1109 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1110 return true;
1111}
1112
Roland Levillain6c82d402014-10-13 16:10:27 +01001113bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1114 if (other_instruction == this) {
1115 // An instruction does not strictly dominate itself.
1116 return false;
1117 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001118 HBasicBlock* block = GetBlock();
1119 HBasicBlock* other_block = other_instruction->GetBlock();
1120 if (block != other_block) {
1121 return GetBlock()->Dominates(other_instruction->GetBlock());
1122 } else {
1123 // If both instructions are in the same block, ensure this
1124 // instruction comes before `other_instruction`.
1125 if (IsPhi()) {
1126 if (!other_instruction->IsPhi()) {
1127 // Phis appear before non phi-instructions so this instruction
1128 // dominates `other_instruction`.
1129 return true;
1130 } else {
1131 // There is no order among phis.
1132 LOG(FATAL) << "There is no dominance between phis of a same block.";
1133 return false;
1134 }
1135 } else {
1136 // `this` is not a phi.
1137 if (other_instruction->IsPhi()) {
1138 // Phis appear before non phi-instructions so this instruction
1139 // does not dominate `other_instruction`.
1140 return false;
1141 } else {
1142 // Check whether this instruction comes before
1143 // `other_instruction` in the instruction list.
1144 return block->GetInstructions().FoundBefore(this, other_instruction);
1145 }
1146 }
1147 }
1148}
1149
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001150void HInstruction::RemoveEnvironment() {
1151 RemoveEnvironmentUses(this);
1152 environment_ = nullptr;
1153}
1154
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001155void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001156 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001157 // Note: fixup_end remains valid across splice_after().
1158 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1159 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1160 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001161
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001162 // Note: env_fixup_end remains valid across splice_after().
1163 auto env_fixup_end =
1164 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1165 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1166 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001167
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001168 DCHECK(uses_.empty());
1169 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001170}
1171
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001172void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1173 const HUseList<HInstruction*>& uses = GetUses();
1174 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1175 HInstruction* user = it->GetUser();
1176 size_t index = it->GetIndex();
1177 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1178 ++it;
1179 if (dominator->StrictlyDominates(user)) {
1180 user->ReplaceInput(replacement, index);
1181 }
1182 }
1183}
1184
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001185void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001186 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001187 if (input_use.GetInstruction() == replacement) {
1188 // Nothing to do.
1189 return;
1190 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001191 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001192 // Note: fixup_end remains valid across splice_after().
1193 auto fixup_end =
1194 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1195 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1196 input_use.GetInstruction()->uses_,
1197 before_use_node);
1198 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1199 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001200}
1201
Nicolas Geoffray39468442014-09-02 15:17:15 +01001202size_t HInstruction::EnvironmentSize() const {
1203 return HasEnvironment() ? environment_->Size() : 0;
1204}
1205
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001206void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001207 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001208 inputs_.push_back(HUserRecord<HInstruction*>(input));
1209 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001210}
1211
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001212void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1213 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1214 input->AddUseAt(this, index);
1215 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1216 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1217 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1218 inputs_[i].GetUseNode()->SetIndex(i);
1219 }
1220}
1221
1222void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001223 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001224 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001225 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1226 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1227 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1228 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001229 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001230}
1231
Igor Murashkind01745e2017-04-05 16:40:31 -07001232void HVariableInputSizeInstruction::RemoveAllInputs() {
1233 RemoveAsUserOfAllInputs();
1234 DCHECK(!HasNonEnvironmentUses());
1235
1236 inputs_.clear();
1237 DCHECK_EQ(0u, InputCount());
1238}
1239
Igor Murashkin6ef45672017-08-08 13:59:55 -07001240size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001241 DCHECK(instruction->GetBlock() != nullptr);
1242 // Removing constructor fences only makes sense for instructions with an object return type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001243 DCHECK_EQ(DataType::Type::kReference, instruction->GetType());
Igor Murashkind01745e2017-04-05 16:40:31 -07001244
Igor Murashkin6ef45672017-08-08 13:59:55 -07001245 // Return how many instructions were removed for statistic purposes.
1246 size_t remove_count = 0;
1247
Igor Murashkind01745e2017-04-05 16:40:31 -07001248 // Efficient implementation that simultaneously (in one pass):
1249 // * Scans the uses list for all constructor fences.
1250 // * Deletes that constructor fence from the uses list of `instruction`.
1251 // * Deletes `instruction` from the constructor fence's inputs.
1252 // * Deletes the constructor fence if it now has 0 inputs.
1253
1254 const HUseList<HInstruction*>& uses = instruction->GetUses();
1255 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1256 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1257 const HUseListNode<HInstruction*>& use_node = *it;
1258 HInstruction* const use_instruction = use_node.GetUser();
1259
1260 // Advance the iterator immediately once we fetch the use_node.
1261 // Warning: If the input is removed, the current iterator becomes invalid.
1262 ++it;
1263
1264 if (use_instruction->IsConstructorFence()) {
1265 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1266 size_t input_index = use_node.GetIndex();
1267
1268 // Process the candidate instruction for removal
1269 // from the graph.
1270
1271 // Constructor fence instructions are never
1272 // used by other instructions.
1273 //
1274 // If we wanted to make this more generic, it
1275 // could be a runtime if statement.
1276 DCHECK(!ctor_fence->HasUses());
1277
1278 // A constructor fence's return type is "kPrimVoid"
1279 // and therefore it can't have any environment uses.
1280 DCHECK(!ctor_fence->HasEnvironmentUses());
1281
1282 // Remove the inputs first, otherwise removing the instruction
1283 // will try to remove its uses while we are already removing uses
1284 // and this operation will fail.
1285 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1286
1287 // Removing the input will also remove the `use_node`.
1288 // (Do not look at `use_node` after this, it will be a dangling reference).
1289 ctor_fence->RemoveInputAt(input_index);
1290
1291 // Once all inputs are removed, the fence is considered dead and
1292 // is removed.
1293 if (ctor_fence->InputCount() == 0u) {
1294 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
Igor Murashkin6ef45672017-08-08 13:59:55 -07001295 ++remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001296 }
1297 }
1298 }
1299
1300 if (kIsDebugBuild) {
1301 // Post-condition checks:
1302 // * None of the uses of `instruction` are a constructor fence.
1303 // * The `instruction` itself did not get removed from a block.
1304 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1305 CHECK(!use_node.GetUser()->IsConstructorFence());
1306 }
1307 CHECK(instruction->GetBlock() != nullptr);
1308 }
Igor Murashkin6ef45672017-08-08 13:59:55 -07001309
1310 return remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001311}
1312
Igor Murashkindd018df2017-08-09 10:38:31 -07001313void HConstructorFence::Merge(HConstructorFence* other) {
1314 // Do not delete yourself from the graph.
1315 DCHECK(this != other);
1316 // Don't try to merge with an instruction not associated with a block.
1317 DCHECK(other->GetBlock() != nullptr);
1318 // A constructor fence's return type is "kPrimVoid"
1319 // and therefore it cannot have any environment uses.
1320 DCHECK(!other->HasEnvironmentUses());
1321
1322 auto has_input = [](HInstruction* haystack, HInstruction* needle) {
1323 // Check if `haystack` has `needle` as any of its inputs.
1324 for (size_t input_count = 0; input_count < haystack->InputCount(); ++input_count) {
1325 if (haystack->InputAt(input_count) == needle) {
1326 return true;
1327 }
1328 }
1329 return false;
1330 };
1331
1332 // Add any inputs from `other` into `this` if it wasn't already an input.
1333 for (size_t input_count = 0; input_count < other->InputCount(); ++input_count) {
1334 HInstruction* other_input = other->InputAt(input_count);
1335 if (!has_input(this, other_input)) {
1336 AddInput(other_input);
1337 }
1338 }
1339
1340 other->GetBlock()->RemoveInstruction(other);
1341}
1342
1343HInstruction* HConstructorFence::GetAssociatedAllocation(bool ignore_inputs) {
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001344 HInstruction* new_instance_inst = GetPrevious();
1345 // Check if the immediately preceding instruction is a new-instance/new-array.
1346 // Otherwise this fence is for protecting final fields.
1347 if (new_instance_inst != nullptr &&
1348 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
Igor Murashkindd018df2017-08-09 10:38:31 -07001349 if (ignore_inputs) {
1350 // If inputs are ignored, simply check if the predecessor is
1351 // *any* HNewInstance/HNewArray.
1352 //
1353 // Inputs are normally only ignored for prepare_for_register_allocation,
1354 // at which point *any* prior HNewInstance/Array can be considered
1355 // associated.
1356 return new_instance_inst;
1357 } else {
1358 // Normal case: There must be exactly 1 input and the previous instruction
1359 // must be that input.
1360 if (InputCount() == 1u && InputAt(0) == new_instance_inst) {
1361 return new_instance_inst;
1362 }
1363 }
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001364 }
Igor Murashkindd018df2017-08-09 10:38:31 -07001365 return nullptr;
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001366}
1367
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001368#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001369void H##name::Accept(HGraphVisitor* visitor) { \
1370 visitor->Visit##name(this); \
1371}
1372
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001373FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001374
1375#undef DEFINE_ACCEPT
1376
1377void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001378 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1379 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001380 if (block != nullptr) {
1381 VisitBasicBlock(block);
1382 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001383 }
1384}
1385
Roland Levillain633021e2014-10-01 14:12:25 +01001386void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001387 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1388 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001389 }
1390}
1391
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001392void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001393 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001394 it.Current()->Accept(this);
1395 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001396 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001397 it.Current()->Accept(this);
1398 }
1399}
1400
Mark Mendelle82549b2015-05-06 10:55:34 -04001401HConstant* HTypeConversion::TryStaticEvaluation() const {
1402 HGraph* graph = GetBlock()->GetGraph();
1403 if (GetInput()->IsIntConstant()) {
1404 int32_t value = GetInput()->AsIntConstant()->GetValue();
1405 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001406 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001407 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001408 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001409 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001410 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001411 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001412 default:
1413 return nullptr;
1414 }
1415 } else if (GetInput()->IsLongConstant()) {
1416 int64_t value = GetInput()->AsLongConstant()->GetValue();
1417 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001418 case DataType::Type::kInt32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001419 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001420 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001421 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001422 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001423 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001424 default:
1425 return nullptr;
1426 }
1427 } else if (GetInput()->IsFloatConstant()) {
1428 float value = GetInput()->AsFloatConstant()->GetValue();
1429 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001430 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001431 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001432 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001433 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001434 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001435 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001436 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1437 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001438 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001439 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001440 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001441 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001442 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001443 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001444 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1445 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001446 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001447 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001448 default:
1449 return nullptr;
1450 }
1451 } else if (GetInput()->IsDoubleConstant()) {
1452 double value = GetInput()->AsDoubleConstant()->GetValue();
1453 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001454 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001455 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001456 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001457 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001458 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001459 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001460 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1461 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001462 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001463 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001464 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001465 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001466 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001467 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001468 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1469 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001470 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001471 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001472 default:
1473 return nullptr;
1474 }
1475 }
1476 return nullptr;
1477}
1478
Roland Levillain9240d6a2014-10-20 16:47:04 +01001479HConstant* HUnaryOperation::TryStaticEvaluation() const {
1480 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001481 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001482 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001483 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001484 } else if (kEnableFloatingPointStaticEvaluation) {
1485 if (GetInput()->IsFloatConstant()) {
1486 return Evaluate(GetInput()->AsFloatConstant());
1487 } else if (GetInput()->IsDoubleConstant()) {
1488 return Evaluate(GetInput()->AsDoubleConstant());
1489 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001490 }
1491 return nullptr;
1492}
1493
1494HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001495 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1496 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001497 } else if (GetLeft()->IsLongConstant()) {
1498 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001499 // The binop(long, int) case is only valid for shifts and rotations.
1500 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001501 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1502 } else if (GetRight()->IsLongConstant()) {
1503 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001504 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001505 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001506 // The binop(null, null) case is only valid for equal and not-equal conditions.
1507 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001508 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001509 } else if (kEnableFloatingPointStaticEvaluation) {
1510 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1511 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1512 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1513 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1514 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001515 }
1516 return nullptr;
1517}
Dave Allison20dfc792014-06-16 20:44:29 -07001518
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001519HConstant* HBinaryOperation::GetConstantRight() const {
1520 if (GetRight()->IsConstant()) {
1521 return GetRight()->AsConstant();
1522 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1523 return GetLeft()->AsConstant();
1524 } else {
1525 return nullptr;
1526 }
1527}
1528
1529// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001530// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001531HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1532 HInstruction* most_constant_right = GetConstantRight();
1533 if (most_constant_right == nullptr) {
1534 return nullptr;
1535 } else if (most_constant_right == GetLeft()) {
1536 return GetRight();
1537 } else {
1538 return GetLeft();
1539 }
1540}
1541
Roland Levillain31dd3d62016-02-16 12:21:02 +00001542std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1543 switch (rhs) {
1544 case ComparisonBias::kNoBias:
1545 return os << "no_bias";
1546 case ComparisonBias::kGtBias:
1547 return os << "gt_bias";
1548 case ComparisonBias::kLtBias:
1549 return os << "lt_bias";
1550 default:
1551 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1552 UNREACHABLE();
1553 }
1554}
1555
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001556bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1557 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001558}
1559
Vladimir Marko372f10e2016-05-17 16:30:10 +01001560bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001561 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001562 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001563 if (!InstructionDataEquals(other)) return false;
1564 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001565 HConstInputsRef inputs = GetInputs();
1566 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001567 if (inputs.size() != other_inputs.size()) return false;
1568 for (size_t i = 0; i != inputs.size(); ++i) {
1569 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001570 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001571
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001572 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001573 return true;
1574}
1575
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001576std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1577#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1578 switch (rhs) {
1579 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1580 default:
1581 os << "Unknown instruction kind " << static_cast<int>(rhs);
1582 break;
1583 }
1584#undef DECLARE_CASE
1585 return os;
1586}
1587
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001588void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1589 if (do_checks) {
1590 DCHECK(!IsPhi());
1591 DCHECK(!IsControlFlow());
1592 DCHECK(CanBeMoved() ||
1593 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1594 IsShouldDeoptimizeFlag());
1595 DCHECK(!cursor->IsPhi());
1596 }
David Brazdild6c205e2016-06-07 14:20:52 +01001597
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001598 next_->previous_ = previous_;
1599 if (previous_ != nullptr) {
1600 previous_->next_ = next_;
1601 }
1602 if (block_->instructions_.first_instruction_ == this) {
1603 block_->instructions_.first_instruction_ = next_;
1604 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001605 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001606
1607 previous_ = cursor->previous_;
1608 if (previous_ != nullptr) {
1609 previous_->next_ = this;
1610 }
1611 next_ = cursor;
1612 cursor->previous_ = this;
1613 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001614
1615 if (block_->instructions_.first_instruction_ == cursor) {
1616 block_->instructions_.first_instruction_ = this;
1617 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001618}
1619
Vladimir Markofb337ea2015-11-25 15:25:10 +00001620void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1621 DCHECK(!CanThrow());
1622 DCHECK(!HasSideEffects());
1623 DCHECK(!HasEnvironmentUses());
1624 DCHECK(HasNonEnvironmentUses());
1625 DCHECK(!IsPhi()); // Makes no sense for Phi.
1626 DCHECK_EQ(InputCount(), 0u);
1627
1628 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001629 auto uses_it = GetUses().begin();
1630 auto uses_end = GetUses().end();
1631 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1632 ++uses_it;
1633 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1634 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001635 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001636 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001637 // This instruction has uses in two or more blocks. Find the common dominator.
1638 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001639 for (; uses_it != uses_end; ++uses_it) {
1640 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001641 }
1642 target_block = finder.Get();
1643 DCHECK(target_block != nullptr);
1644 }
1645 // Move to the first dominator not in a loop.
1646 while (target_block->IsInLoop()) {
1647 target_block = target_block->GetDominator();
1648 DCHECK(target_block != nullptr);
1649 }
1650
1651 // Find insertion position.
1652 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001653 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1654 if (use.GetUser()->GetBlock() == target_block &&
1655 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1656 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001657 }
1658 }
1659 if (insert_pos == nullptr) {
1660 // No user in `target_block`, insert before the control flow instruction.
1661 insert_pos = target_block->GetLastInstruction();
1662 DCHECK(insert_pos->IsControlFlow());
1663 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1664 if (insert_pos->IsIf()) {
1665 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1666 if (if_input == insert_pos->GetPrevious()) {
1667 insert_pos = if_input;
1668 }
1669 }
1670 }
1671 MoveBefore(insert_pos);
1672}
1673
David Brazdilfc6a86a2015-06-26 10:33:45 +00001674HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001675 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001676 DCHECK_EQ(cursor->GetBlock(), this);
1677
Vladimir Markoca6fff82017-10-03 14:49:14 +01001678 HBasicBlock* new_block =
1679 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001680 new_block->instructions_.first_instruction_ = cursor;
1681 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1682 instructions_.last_instruction_ = cursor->previous_;
1683 if (cursor->previous_ == nullptr) {
1684 instructions_.first_instruction_ = nullptr;
1685 } else {
1686 cursor->previous_->next_ = nullptr;
1687 cursor->previous_ = nullptr;
1688 }
1689
1690 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001691 AddInstruction(new (GetGraph()->GetAllocator()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001692
Vladimir Marko60584552015-09-03 13:35:12 +00001693 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001694 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001695 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001696 new_block->successors_.swap(successors_);
1697 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001698 AddSuccessor(new_block);
1699
David Brazdil56e1acc2015-06-30 15:41:36 +01001700 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001701 return new_block;
1702}
1703
David Brazdild7558da2015-09-22 13:04:14 +01001704HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001705 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001706 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1707
Vladimir Markoca6fff82017-10-03 14:49:14 +01001708 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
David Brazdild7558da2015-09-22 13:04:14 +01001709
1710 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001711 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1712 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001713 new_block->predecessors_.swap(predecessors_);
1714 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001715 AddPredecessor(new_block);
1716
1717 GetGraph()->AddBlock(new_block);
1718 return new_block;
1719}
1720
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001721HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1722 DCHECK_EQ(cursor->GetBlock(), this);
1723
Vladimir Markoca6fff82017-10-03 14:49:14 +01001724 HBasicBlock* new_block =
1725 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001726 new_block->instructions_.first_instruction_ = cursor;
1727 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1728 instructions_.last_instruction_ = cursor->previous_;
1729 if (cursor->previous_ == nullptr) {
1730 instructions_.first_instruction_ = nullptr;
1731 } else {
1732 cursor->previous_->next_ = nullptr;
1733 cursor->previous_ = nullptr;
1734 }
1735
1736 new_block->instructions_.SetBlockOfInstructions(new_block);
1737
1738 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001739 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1740 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001741 new_block->successors_.swap(successors_);
1742 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001743
1744 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1745 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001746 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001747 new_block->dominated_blocks_.swap(dominated_blocks_);
1748 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001749 return new_block;
1750}
1751
1752HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001753 DCHECK(!cursor->IsControlFlow());
1754 DCHECK_NE(instructions_.last_instruction_, cursor);
1755 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001756
Vladimir Markoca6fff82017-10-03 14:49:14 +01001757 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001758 new_block->instructions_.first_instruction_ = cursor->GetNext();
1759 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1760 cursor->next_->previous_ = nullptr;
1761 cursor->next_ = nullptr;
1762 instructions_.last_instruction_ = cursor;
1763
1764 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001765 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001766 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001767 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001768 new_block->successors_.swap(successors_);
1769 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001770
Vladimir Marko60584552015-09-03 13:35:12 +00001771 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001772 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001773 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001774 new_block->dominated_blocks_.swap(dominated_blocks_);
1775 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001776 return new_block;
1777}
1778
David Brazdilec16f792015-08-19 15:04:01 +01001779const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001780 if (EndsWithTryBoundary()) {
1781 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1782 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001783 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001784 return try_boundary;
1785 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001786 DCHECK(IsTryBlock());
1787 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001788 return nullptr;
1789 }
David Brazdilec16f792015-08-19 15:04:01 +01001790 } else if (IsTryBlock()) {
1791 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001792 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001793 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001794 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001795}
1796
David Brazdild7558da2015-09-22 13:04:14 +01001797bool HBasicBlock::HasThrowingInstructions() const {
1798 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1799 if (it.Current()->CanThrow()) {
1800 return true;
1801 }
1802 }
1803 return false;
1804}
1805
David Brazdilfc6a86a2015-06-26 10:33:45 +00001806static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1807 return block.GetPhis().IsEmpty()
1808 && !block.GetInstructions().IsEmpty()
1809 && block.GetFirstInstruction() == block.GetLastInstruction();
1810}
1811
David Brazdil46e2a392015-03-16 17:31:52 +00001812bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001813 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1814}
1815
Mads Ager16e52892017-07-14 13:11:37 +02001816bool HBasicBlock::IsSingleReturn() const {
1817 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
1818}
1819
David Brazdilfc6a86a2015-06-26 10:33:45 +00001820bool HBasicBlock::IsSingleTryBoundary() const {
1821 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001822}
1823
David Brazdil8d5b8b22015-03-24 10:51:52 +00001824bool HBasicBlock::EndsWithControlFlowInstruction() const {
1825 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1826}
1827
David Brazdilb2bd1c52015-03-25 11:17:37 +00001828bool HBasicBlock::EndsWithIf() const {
1829 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1830}
1831
David Brazdilffee3d32015-07-06 11:48:53 +01001832bool HBasicBlock::EndsWithTryBoundary() const {
1833 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1834}
1835
David Brazdilb2bd1c52015-03-25 11:17:37 +00001836bool HBasicBlock::HasSinglePhi() const {
1837 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1838}
1839
David Brazdild26a4112015-11-10 11:07:31 +00001840ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1841 if (EndsWithTryBoundary()) {
1842 // The normal-flow successor of HTryBoundary is always stored at index zero.
1843 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1844 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1845 } else {
1846 // All successors of blocks not ending with TryBoundary are normal.
1847 return ArrayRef<HBasicBlock* const>(successors_);
1848 }
1849}
1850
1851ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1852 if (EndsWithTryBoundary()) {
1853 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1854 } else {
1855 // Blocks not ending with TryBoundary do not have exceptional successors.
1856 return ArrayRef<HBasicBlock* const>();
1857 }
1858}
1859
David Brazdilffee3d32015-07-06 11:48:53 +01001860bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001861 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1862 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1863
1864 size_t length = handlers1.size();
1865 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001866 return false;
1867 }
1868
David Brazdilb618ade2015-07-29 10:31:29 +01001869 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001870 for (size_t i = 0; i < length; ++i) {
1871 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001872 return false;
1873 }
1874 }
1875 return true;
1876}
1877
David Brazdil2d7352b2015-04-20 14:52:42 +01001878size_t HInstructionList::CountSize() const {
1879 size_t size = 0;
1880 HInstruction* current = first_instruction_;
1881 for (; current != nullptr; current = current->GetNext()) {
1882 size++;
1883 }
1884 return size;
1885}
1886
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001887void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1888 for (HInstruction* current = first_instruction_;
1889 current != nullptr;
1890 current = current->GetNext()) {
1891 current->SetBlock(block);
1892 }
1893}
1894
1895void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1896 DCHECK(Contains(cursor));
1897 if (!instruction_list.IsEmpty()) {
1898 if (cursor == last_instruction_) {
1899 last_instruction_ = instruction_list.last_instruction_;
1900 } else {
1901 cursor->next_->previous_ = instruction_list.last_instruction_;
1902 }
1903 instruction_list.last_instruction_->next_ = cursor->next_;
1904 cursor->next_ = instruction_list.first_instruction_;
1905 instruction_list.first_instruction_->previous_ = cursor;
1906 }
1907}
1908
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001909void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1910 DCHECK(Contains(cursor));
1911 if (!instruction_list.IsEmpty()) {
1912 if (cursor == first_instruction_) {
1913 first_instruction_ = instruction_list.first_instruction_;
1914 } else {
1915 cursor->previous_->next_ = instruction_list.first_instruction_;
1916 }
1917 instruction_list.last_instruction_->next_ = cursor;
1918 instruction_list.first_instruction_->previous_ = cursor->previous_;
1919 cursor->previous_ = instruction_list.last_instruction_;
1920 }
1921}
1922
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001923void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001924 if (IsEmpty()) {
1925 first_instruction_ = instruction_list.first_instruction_;
1926 last_instruction_ = instruction_list.last_instruction_;
1927 } else {
1928 AddAfter(last_instruction_, instruction_list);
1929 }
1930}
1931
David Brazdil04ff4e82015-12-10 13:54:52 +00001932// Should be called on instructions in a dead block in post order. This method
1933// assumes `insn` has been removed from all users with the exception of catch
1934// phis because of missing exceptional edges in the graph. It removes the
1935// instruction from catch phi uses, together with inputs of other catch phis in
1936// the catch block at the same index, as these must be dead too.
1937static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1938 DCHECK(!insn->HasEnvironmentUses());
1939 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001940 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1941 size_t use_index = use.GetIndex();
1942 HBasicBlock* user_block = use.GetUser()->GetBlock();
1943 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001944 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1945 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1946 }
1947 }
1948}
1949
David Brazdil2d7352b2015-04-20 14:52:42 +01001950void HBasicBlock::DisconnectAndDelete() {
1951 // Dominators must be removed after all the blocks they dominate. This way
1952 // a loop header is removed last, a requirement for correct loop information
1953 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001954 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001955
David Brazdil9eeebf62016-03-24 11:18:15 +00001956 // The following steps gradually remove the block from all its dependants in
1957 // post order (b/27683071).
1958
1959 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1960 // We need to do this before step (4) which destroys the predecessor list.
1961 HBasicBlock* loop_update_start = this;
1962 if (IsLoopHeader()) {
1963 HLoopInformation* loop_info = GetLoopInformation();
1964 // All other blocks in this loop should have been removed because the header
1965 // was their dominator.
1966 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1967 DCHECK(!loop_info->IsIrreducible());
1968 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1969 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1970 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001971 }
1972
David Brazdil9eeebf62016-03-24 11:18:15 +00001973 // (2) Disconnect the block from its successors and update their phis.
1974 for (HBasicBlock* successor : successors_) {
1975 // Delete this block from the list of predecessors.
1976 size_t this_index = successor->GetPredecessorIndexOf(this);
1977 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1978
1979 // Check that `successor` has other predecessors, otherwise `this` is the
1980 // dominator of `successor` which violates the order DCHECKed at the top.
1981 DCHECK(!successor->predecessors_.empty());
1982
1983 // Remove this block's entries in the successor's phis. Skip exceptional
1984 // successors because catch phi inputs do not correspond to predecessor
1985 // blocks but throwing instructions. The inputs of the catch phis will be
1986 // updated in step (3).
1987 if (!successor->IsCatchBlock()) {
1988 if (successor->predecessors_.size() == 1u) {
1989 // The successor has just one predecessor left. Replace phis with the only
1990 // remaining input.
1991 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1992 HPhi* phi = phi_it.Current()->AsPhi();
1993 phi->ReplaceWith(phi->InputAt(1 - this_index));
1994 successor->RemovePhi(phi);
1995 }
1996 } else {
1997 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1998 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1999 }
2000 }
2001 }
2002 }
2003 successors_.clear();
2004
2005 // (3) Remove instructions and phis. Instructions should have no remaining uses
2006 // except in catch phis. If an instruction is used by a catch phi at `index`,
2007 // remove `index`-th input of all phis in the catch block since they are
2008 // guaranteed dead. Note that we may miss dead inputs this way but the
2009 // graph will always remain consistent.
2010 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2011 HInstruction* insn = it.Current();
2012 RemoveUsesOfDeadInstruction(insn);
2013 RemoveInstruction(insn);
2014 }
2015 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
2016 HPhi* insn = it.Current()->AsPhi();
2017 RemoveUsesOfDeadInstruction(insn);
2018 RemovePhi(insn);
2019 }
2020
2021 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002022 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00002023 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00002024 // We should not see any back edges as they would have been removed by step (3).
2025 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
2026
David Brazdil2d7352b2015-04-20 14:52:42 +01002027 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002028 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
2029 // This block is the only normal-flow successor of the TryBoundary which
2030 // makes `predecessor` dead. Since DCE removes blocks in post order,
2031 // exception handlers of this TryBoundary were already visited and any
2032 // remaining handlers therefore must be live. We remove `predecessor` from
2033 // their list of predecessors.
2034 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
2035 while (predecessor->GetSuccessors().size() > 1) {
2036 HBasicBlock* handler = predecessor->GetSuccessors()[1];
2037 DCHECK(handler->IsCatchBlock());
2038 predecessor->RemoveSuccessor(handler);
2039 handler->RemovePredecessor(predecessor);
2040 }
2041 }
2042
David Brazdil2d7352b2015-04-20 14:52:42 +01002043 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04002044 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
2045 if (num_pred_successors == 1u) {
2046 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002047 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
2048 // successor. Replace those with a HGoto.
2049 DCHECK(last_instruction->IsIf() ||
2050 last_instruction->IsPackedSwitch() ||
2051 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002052 predecessor->RemoveInstruction(last_instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002053 predecessor->AddInstruction(new (graph_->GetAllocator()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002054 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002055 // The predecessor has no remaining successors and therefore must be dead.
2056 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00002057 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04002058 predecessor->RemoveInstruction(last_instruction);
2059 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002060 // There are multiple successors left. The removed block might be a successor
2061 // of a PackedSwitch which will be completely removed (perhaps replaced with
2062 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2063 // case, leave `last_instruction` as is for now.
2064 DCHECK(last_instruction->IsPackedSwitch() ||
2065 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002066 }
David Brazdil46e2a392015-03-16 17:31:52 +00002067 }
Vladimir Marko60584552015-09-03 13:35:12 +00002068 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002069
David Brazdil9eeebf62016-03-24 11:18:15 +00002070 // (5) Remove the block from all loops it is included in. Skip the inner-most
2071 // loop if this is the loop header (see definition of `loop_update_start`)
2072 // because the loop header's predecessor list has been destroyed in step (4).
2073 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2074 HLoopInformation* loop_info = it.Current();
2075 loop_info->Remove(this);
2076 if (loop_info->IsBackEdge(*this)) {
2077 // If this was the last back edge of the loop, we deliberately leave the
2078 // loop in an inconsistent state and will fail GraphChecker unless the
2079 // entire loop is removed during the pass.
2080 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002081 }
2082 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002083
David Brazdil9eeebf62016-03-24 11:18:15 +00002084 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002085 dominator_->RemoveDominatedBlock(this);
2086 SetDominator(nullptr);
2087
David Brazdil9eeebf62016-03-24 11:18:15 +00002088 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002089 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002090 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002091}
2092
Aart Bik6b69e0a2017-01-11 10:20:43 -08002093void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2094 DCHECK(EndsWithControlFlowInstruction());
2095 RemoveInstruction(GetLastInstruction());
2096 instructions_.Add(other->GetInstructions());
2097 other->instructions_.SetBlockOfInstructions(this);
2098 other->instructions_.Clear();
2099}
2100
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002101void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002102 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002103 DCHECK(ContainsElement(dominated_blocks_, other));
2104 DCHECK_EQ(GetSingleSuccessor(), other);
2105 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002106 DCHECK(other->GetPhis().IsEmpty());
2107
David Brazdil2d7352b2015-04-20 14:52:42 +01002108 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002109 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002110
David Brazdil2d7352b2015-04-20 14:52:42 +01002111 // Remove `other` from the loops it is included in.
2112 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2113 HLoopInformation* loop_info = it.Current();
2114 loop_info->Remove(other);
2115 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002116 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002117 }
2118 }
2119
2120 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002121 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002122 for (HBasicBlock* successor : other->GetSuccessors()) {
2123 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002124 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002125 successors_.swap(other->successors_);
2126 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002127
David Brazdil2d7352b2015-04-20 14:52:42 +01002128 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002129 RemoveDominatedBlock(other);
2130 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002131 dominated->SetDominator(this);
2132 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002133 dominated_blocks_.insert(
2134 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002135 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002136 other->dominator_ = nullptr;
2137
2138 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002139 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002140
2141 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002142 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002143 other->SetGraph(nullptr);
2144}
2145
2146void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2147 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002148 DCHECK(GetDominatedBlocks().empty());
2149 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002150 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002151 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002152 DCHECK(other->GetPhis().IsEmpty());
2153 DCHECK(!other->IsInLoop());
2154
2155 // Move instructions from `other` to `this`.
2156 instructions_.Add(other->GetInstructions());
2157 other->instructions_.SetBlockOfInstructions(this);
2158
2159 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002160 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002161 for (HBasicBlock* successor : other->GetSuccessors()) {
2162 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002163 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002164 successors_.swap(other->successors_);
2165 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002166
2167 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002168 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002169 dominated->SetDominator(this);
2170 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002171 dominated_blocks_.insert(
2172 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002173 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002174 other->dominator_ = nullptr;
2175 other->graph_ = nullptr;
2176}
2177
2178void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002179 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002180 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002181 predecessor->ReplaceSuccessor(this, other);
2182 }
Vladimir Marko60584552015-09-03 13:35:12 +00002183 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002184 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002185 successor->ReplacePredecessor(this, other);
2186 }
Vladimir Marko60584552015-09-03 13:35:12 +00002187 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2188 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002189 }
2190 GetDominator()->ReplaceDominatedBlock(this, other);
2191 other->SetDominator(GetDominator());
2192 dominator_ = nullptr;
2193 graph_ = nullptr;
2194}
2195
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002196void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002197 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002198 DCHECK(block->GetSuccessors().empty());
2199 DCHECK(block->GetPredecessors().empty());
2200 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002201 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002202 DCHECK(block->GetInstructions().IsEmpty());
2203 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002204
David Brazdilc7af85d2015-05-26 12:05:55 +01002205 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002206 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002207 }
2208
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002209 RemoveElement(reverse_post_order_, block);
2210 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002211 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002212}
2213
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002214void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2215 HBasicBlock* reference,
2216 bool replace_if_back_edge) {
2217 if (block->IsLoopHeader()) {
2218 // Clear the information of which blocks are contained in that loop. Since the
2219 // information is stored as a bit vector based on block ids, we have to update
2220 // it, as those block ids were specific to the callee graph and we are now adding
2221 // these blocks to the caller graph.
2222 block->GetLoopInformation()->ClearAllBlocks();
2223 }
2224
2225 // If not already in a loop, update the loop information.
2226 if (!block->IsInLoop()) {
2227 block->SetLoopInformation(reference->GetLoopInformation());
2228 }
2229
2230 // If the block is in a loop, update all its outward loops.
2231 HLoopInformation* loop_info = block->GetLoopInformation();
2232 if (loop_info != nullptr) {
2233 for (HLoopInformationOutwardIterator loop_it(*block);
2234 !loop_it.Done();
2235 loop_it.Advance()) {
2236 loop_it.Current()->Add(block);
2237 }
2238 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2239 loop_info->ReplaceBackEdge(reference, block);
2240 }
2241 }
2242
2243 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2244 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2245 ? reference->GetTryCatchInformation()
2246 : nullptr;
2247 block->SetTryCatchInformation(try_catch_info);
2248}
2249
Calin Juravle2e768302015-07-28 14:41:11 +00002250HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002251 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002252 // Update the environments in this graph to have the invoke's environment
2253 // as parent.
2254 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002255 // Skip the entry block, we do not need to update the entry's suspend check.
2256 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002257 for (HInstructionIterator instr_it(block->GetInstructions());
2258 !instr_it.Done();
2259 instr_it.Advance()) {
2260 HInstruction* current = instr_it.Current();
2261 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002262 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002263 current->GetEnvironment()->SetAndCopyParentChain(
Vladimir Markoca6fff82017-10-03 14:49:14 +01002264 outer_graph->GetAllocator(), invoke->GetEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002265 }
2266 }
2267 }
2268 }
2269 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002270
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002271 if (HasBoundsChecks()) {
2272 outer_graph->SetHasBoundsChecks(true);
2273 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002274 if (HasLoops()) {
2275 outer_graph->SetHasLoops(true);
2276 }
2277 if (HasIrreducibleLoops()) {
2278 outer_graph->SetHasIrreducibleLoops(true);
2279 }
2280 if (HasTryCatch()) {
2281 outer_graph->SetHasTryCatch(true);
2282 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002283 if (HasSIMD()) {
2284 outer_graph->SetHasSIMD(true);
2285 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002286
Calin Juravle2e768302015-07-28 14:41:11 +00002287 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002288 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002289 // Inliner already made sure we don't inline methods that always throw.
2290 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002291 // Simple case of an entry block, a body block, and an exit block.
2292 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002293 HBasicBlock* body = GetBlocks()[1];
2294 DCHECK(GetBlocks()[0]->IsEntryBlock());
2295 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002296 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002297 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002298 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002299
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002300 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2301 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002302 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002303
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002304 // Replace the invoke with the return value of the inlined graph.
2305 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002306 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002307 } else {
2308 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002309 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002310
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002311 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002312 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002313 // Need to inline multiple blocks. We split `invoke`'s block
2314 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002315 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002316 // with the second half.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002317 ArenaAllocator* allocator = outer_graph->GetAllocator();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002318 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002319 // Note that we split before the invoke only to simplify polymorphic inlining.
2320 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002321
Vladimir Markoec7802a2015-10-01 20:57:57 +01002322 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002323 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002324 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002325 exit_block_->ReplaceWith(to);
2326
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002327 // Update the meta information surrounding blocks:
2328 // (1) the graph they are now in,
2329 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002330 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002331 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002332 // Note that we do not need to update catch phi inputs because they
2333 // correspond to the register file of the outer method which the inlinee
2334 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002335
2336 // We don't add the entry block, the exit block, and the first block, which
2337 // has been merged with `at`.
2338 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2339
2340 // We add the `to` block.
2341 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002342 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002343 + kNumberOfNewBlocksInCaller;
2344
2345 // Find the location of `at` in the outer graph's reverse post order. The new
2346 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002347 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002348 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2349
David Brazdil95177982015-10-30 12:56:58 -05002350 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2351 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002352 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002353 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002354 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002355 DCHECK(current->GetGraph() == this);
2356 current->SetGraph(outer_graph);
2357 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002358 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002359 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002360 }
2361 }
2362
David Brazdil95177982015-10-30 12:56:58 -05002363 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002364 to->SetGraph(outer_graph);
2365 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002366 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002367 // Only `to` can become a back edge, as the inlined blocks
2368 // are predecessors of `to`.
2369 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002370
David Brazdil3f523062016-02-29 16:53:33 +00002371 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002372 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2373 // to now get the outer graph exit block as successor. Note that the inliner
2374 // currently doesn't support inlining methods with try/catch.
2375 HPhi* return_value_phi = nullptr;
2376 bool rerun_dominance = false;
2377 bool rerun_loop_analysis = false;
2378 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2379 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002380 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002381 if (last->IsThrow()) {
2382 DCHECK(!at->IsTryBlock());
2383 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2384 --pred;
2385 // We need to re-run dominance information, as the exit block now has
2386 // a new dominator.
2387 rerun_dominance = true;
2388 if (predecessor->GetLoopInformation() != nullptr) {
2389 // The exit block and blocks post dominated by the exit block do not belong
2390 // to any loop. Because we do not compute the post dominators, we need to re-run
2391 // loop analysis to get the loop information correct.
2392 rerun_loop_analysis = true;
2393 }
2394 } else {
2395 if (last->IsReturnVoid()) {
2396 DCHECK(return_value == nullptr);
2397 DCHECK(return_value_phi == nullptr);
2398 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002399 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002400 if (return_value_phi != nullptr) {
2401 return_value_phi->AddInput(last->InputAt(0));
2402 } else if (return_value == nullptr) {
2403 return_value = last->InputAt(0);
2404 } else {
2405 // There will be multiple returns.
2406 return_value_phi = new (allocator) HPhi(
2407 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2408 to->AddPhi(return_value_phi);
2409 return_value_phi->AddInput(return_value);
2410 return_value_phi->AddInput(last->InputAt(0));
2411 return_value = return_value_phi;
2412 }
David Brazdil3f523062016-02-29 16:53:33 +00002413 }
2414 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2415 predecessor->RemoveInstruction(last);
2416 }
2417 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002418 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002419 DCHECK(!outer_graph->HasIrreducibleLoops())
2420 << "Recomputing loop information in graphs with irreducible loops "
2421 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002422 outer_graph->ClearLoopInformation();
2423 outer_graph->ClearDominanceInformation();
2424 outer_graph->BuildDominatorTree();
2425 } else if (rerun_dominance) {
2426 outer_graph->ClearDominanceInformation();
2427 outer_graph->ComputeDominanceInformation();
2428 }
David Brazdil3f523062016-02-29 16:53:33 +00002429 }
David Brazdil05144f42015-04-16 15:18:00 +01002430
2431 // Walk over the entry block and:
2432 // - Move constants from the entry block to the outer_graph's entry block,
2433 // - Replace HParameterValue instructions with their real value.
2434 // - Remove suspend checks, that hold an environment.
2435 // We must do this after the other blocks have been inlined, otherwise ids of
2436 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002437 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002438 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2439 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002440 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002441 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002442 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002443 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002444 replacement = outer_graph->GetIntConstant(
2445 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002446 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002447 replacement = outer_graph->GetLongConstant(
2448 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002449 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002450 replacement = outer_graph->GetFloatConstant(
2451 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002452 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002453 replacement = outer_graph->GetDoubleConstant(
2454 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002455 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002456 if (kIsDebugBuild
2457 && invoke->IsInvokeStaticOrDirect()
2458 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2459 // Ensure we do not use the last input of `invoke`, as it
2460 // contains a clinit check which is not an actual argument.
2461 size_t last_input_index = invoke->InputCount() - 1;
2462 DCHECK(parameter_index != last_input_index);
2463 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002464 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002465 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002466 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002467 } else {
2468 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2469 entry_block_->RemoveInstruction(current);
2470 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002471 if (replacement != nullptr) {
2472 current->ReplaceWith(replacement);
2473 // If the current is the return value then we need to update the latter.
2474 if (current == return_value) {
2475 DCHECK_EQ(entry_block_, return_value->GetBlock());
2476 return_value = replacement;
2477 }
2478 }
2479 }
2480
Calin Juravle2e768302015-07-28 14:41:11 +00002481 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002482}
2483
Mingyao Yang3584bce2015-05-19 16:01:59 -07002484/*
2485 * Loop will be transformed to:
2486 * old_pre_header
2487 * |
2488 * if_block
2489 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002490 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002491 * \ /
2492 * new_pre_header
2493 * |
2494 * header
2495 */
2496void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2497 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002498 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002499
Aart Bik3fc7f352015-11-20 22:03:03 -08002500 // Need extra block to avoid critical edge.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002501 HBasicBlock* if_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2502 HBasicBlock* true_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2503 HBasicBlock* false_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2504 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002505 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002506 AddBlock(true_block);
2507 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002508 AddBlock(new_pre_header);
2509
Aart Bik3fc7f352015-11-20 22:03:03 -08002510 header->ReplacePredecessor(old_pre_header, new_pre_header);
2511 old_pre_header->successors_.clear();
2512 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002513
Aart Bik3fc7f352015-11-20 22:03:03 -08002514 old_pre_header->AddSuccessor(if_block);
2515 if_block->AddSuccessor(true_block); // True successor
2516 if_block->AddSuccessor(false_block); // False successor
2517 true_block->AddSuccessor(new_pre_header);
2518 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002519
Aart Bik3fc7f352015-11-20 22:03:03 -08002520 old_pre_header->dominated_blocks_.push_back(if_block);
2521 if_block->SetDominator(old_pre_header);
2522 if_block->dominated_blocks_.push_back(true_block);
2523 true_block->SetDominator(if_block);
2524 if_block->dominated_blocks_.push_back(false_block);
2525 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002526 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002527 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002528 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002529 header->SetDominator(new_pre_header);
2530
Aart Bik3fc7f352015-11-20 22:03:03 -08002531 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002532 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002533 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002534 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002535 reverse_post_order_[index_of_header++] = true_block;
2536 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002537 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002538
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002539 // The pre_header can never be a back edge of a loop.
2540 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2541 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2542 UpdateLoopAndTryInformationOfNewBlock(
2543 if_block, old_pre_header, /* replace_if_back_edge */ false);
2544 UpdateLoopAndTryInformationOfNewBlock(
2545 true_block, old_pre_header, /* replace_if_back_edge */ false);
2546 UpdateLoopAndTryInformationOfNewBlock(
2547 false_block, old_pre_header, /* replace_if_back_edge */ false);
2548 UpdateLoopAndTryInformationOfNewBlock(
2549 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002550}
2551
Aart Bikf8f5a162017-02-06 15:35:29 -08002552HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2553 HBasicBlock* body,
2554 HBasicBlock* exit) {
2555 DCHECK(header->IsLoopHeader());
2556 HLoopInformation* loop = header->GetLoopInformation();
2557
2558 // Add new loop blocks.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002559 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2560 HBasicBlock* new_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2561 HBasicBlock* new_body = new (allocator_) HBasicBlock(this, header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002562 AddBlock(new_pre_header);
2563 AddBlock(new_header);
2564 AddBlock(new_body);
2565
2566 // Set up control flow.
2567 header->ReplaceSuccessor(exit, new_pre_header);
2568 new_pre_header->AddSuccessor(new_header);
2569 new_header->AddSuccessor(exit);
2570 new_header->AddSuccessor(new_body);
2571 new_body->AddSuccessor(new_header);
2572
2573 // Set up dominators.
2574 header->ReplaceDominatedBlock(exit, new_pre_header);
2575 new_pre_header->SetDominator(header);
2576 new_pre_header->dominated_blocks_.push_back(new_header);
2577 new_header->SetDominator(new_pre_header);
2578 new_header->dominated_blocks_.push_back(new_body);
2579 new_body->SetDominator(new_header);
2580 new_header->dominated_blocks_.push_back(exit);
2581 exit->SetDominator(new_header);
2582
2583 // Fix reverse post order.
2584 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2585 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2586 reverse_post_order_[++index_of_header] = new_pre_header;
2587 reverse_post_order_[++index_of_header] = new_header;
2588 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2589 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2590 reverse_post_order_[index_of_body] = new_body;
2591
Aart Bikb07d1bc2017-04-05 10:03:15 -07002592 // Add gotos and suspend check (client must add conditional in header).
Vladimir Markoca6fff82017-10-03 14:49:14 +01002593 new_pre_header->AddInstruction(new (allocator_) HGoto());
2594 HSuspendCheck* suspend_check = new (allocator_) HSuspendCheck(header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002595 new_header->AddInstruction(suspend_check);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002596 new_body->AddInstruction(new (allocator_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002597 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2598 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002599
2600 // Update loop information.
2601 new_header->AddBackEdge(new_body);
2602 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2603 new_header->GetLoopInformation()->Populate();
2604 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2605 HLoopInformationOutwardIterator it(*new_header);
2606 for (it.Advance(); !it.Done(); it.Advance()) {
2607 it.Current()->Add(new_pre_header);
2608 it.Current()->Add(new_header);
2609 it.Current()->Add(new_body);
2610 }
2611 return new_pre_header;
2612}
2613
David Brazdilf5552582015-12-27 13:36:12 +00002614static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002615 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002616 if (rti.IsValid()) {
2617 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2618 << " upper_bound_rti: " << upper_bound_rti
2619 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002620 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2621 << " upper_bound_rti: " << upper_bound_rti
2622 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002623 }
2624}
2625
Calin Juravle2e768302015-07-28 14:41:11 +00002626void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2627 if (kIsDebugBuild) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002628 DCHECK_EQ(GetType(), DataType::Type::kReference);
Calin Juravle2e768302015-07-28 14:41:11 +00002629 ScopedObjectAccess soa(Thread::Current());
2630 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2631 if (IsBoundType()) {
2632 // Having the test here spares us from making the method virtual just for
2633 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002634 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002635 }
2636 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002637 reference_type_handle_ = rti.GetTypeHandle();
2638 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002639}
2640
David Brazdilf5552582015-12-27 13:36:12 +00002641void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2642 if (kIsDebugBuild) {
2643 ScopedObjectAccess soa(Thread::Current());
2644 DCHECK(upper_bound.IsValid());
2645 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2646 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2647 }
2648 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002649 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002650}
2651
Vladimir Markoa1de9182016-02-25 11:37:38 +00002652ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002653 if (kIsDebugBuild) {
2654 ScopedObjectAccess soa(Thread::Current());
2655 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002656 if (!is_exact) {
2657 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2658 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2659 }
Calin Juravle2e768302015-07-28 14:41:11 +00002660 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002661 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002662}
2663
Calin Juravleacf735c2015-02-12 15:25:22 +00002664std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2665 ScopedObjectAccess soa(Thread::Current());
2666 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002667 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002668 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002669 << " is_exact=" << rhs.IsExact()
2670 << " ]";
2671 return os;
2672}
2673
Mark Mendellc4701932015-04-10 13:18:51 -04002674bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2675 // For now, assume that instructions in different blocks may use the
2676 // environment.
2677 // TODO: Use the control flow to decide if this is true.
2678 if (GetBlock() != other->GetBlock()) {
2679 return true;
2680 }
2681
2682 // We know that we are in the same block. Walk from 'this' to 'other',
2683 // checking to see if there is any instruction with an environment.
2684 HInstruction* current = this;
2685 for (; current != other && current != nullptr; current = current->GetNext()) {
2686 // This is a conservative check, as the instruction result may not be in
2687 // the referenced environment.
2688 if (current->HasEnvironment()) {
2689 return true;
2690 }
2691 }
2692
2693 // We should have been called with 'this' before 'other' in the block.
2694 // Just confirm this.
2695 DCHECK(current != nullptr);
2696 return false;
2697}
2698
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002699void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002700 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2701 IntrinsicSideEffects side_effects,
2702 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002703 intrinsic_ = intrinsic;
2704 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002705
Aart Bik5d75afe2015-12-14 11:57:01 -08002706 // Adjust method's side effects from intrinsic table.
2707 switch (side_effects) {
2708 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2709 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2710 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2711 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2712 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002713
2714 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2715 opt.SetDoesNotNeedDexCache();
2716 opt.SetDoesNotNeedEnvironment();
2717 } else {
2718 // If we need an environment, that means there will be a call, which can trigger GC.
2719 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2720 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002721 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002722 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002723}
2724
David Brazdil6de19382016-01-08 17:37:10 +00002725bool HNewInstance::IsStringAlloc() const {
2726 ScopedObjectAccess soa(Thread::Current());
2727 return GetReferenceTypeInfo().IsStringClass();
2728}
2729
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002730bool HInvoke::NeedsEnvironment() const {
2731 if (!IsIntrinsic()) {
2732 return true;
2733 }
2734 IntrinsicOptimizations opt(*this);
2735 return !opt.GetDoesNotNeedEnvironment();
2736}
2737
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002738const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2739 ArtMethod* caller = GetEnvironment()->GetMethod();
2740 ScopedObjectAccess soa(Thread::Current());
2741 // `caller` is null for a top-level graph representing a method whose declaring
2742 // class was not resolved.
2743 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2744}
2745
Vladimir Markodc151b22015-10-15 18:02:30 +01002746bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002747 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002748 return false;
2749 }
2750 if (!IsIntrinsic()) {
2751 return true;
2752 }
2753 IntrinsicOptimizations opt(*this);
2754 return !opt.GetDoesNotNeedDexCache();
2755}
2756
Vladimir Markof64242a2015-12-01 14:58:23 +00002757std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2758 switch (rhs) {
2759 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002760 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002761 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002762 return os << "Recursive";
2763 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2764 return os << "BootImageLinkTimePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002765 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
Vladimir Marko19d7d502017-05-24 13:04:14 +01002766 return os << "DirectAddress";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002767 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2768 return os << "BssEntry";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002769 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2770 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002771 default:
2772 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2773 UNREACHABLE();
2774 }
2775}
2776
Vladimir Markofbb184a2015-11-13 14:47:00 +00002777std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2778 switch (rhs) {
2779 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2780 return os << "explicit";
2781 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2782 return os << "implicit";
2783 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2784 return os << "none";
2785 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002786 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2787 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002788 }
2789}
2790
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002791bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2792 const HLoadClass* other_load_class = other->AsLoadClass();
2793 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2794 // names rather than type indexes. However, we shall also have to re-think the hash code.
2795 if (type_index_ != other_load_class->type_index_ ||
2796 GetPackedFields() != other_load_class->GetPackedFields()) {
2797 return false;
2798 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002799 switch (GetLoadKind()) {
2800 case LoadKind::kBootImageAddress:
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002801 case LoadKind::kBootImageClassTable:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002802 case LoadKind::kJitTableAddress: {
2803 ScopedObjectAccess soa(Thread::Current());
2804 return GetClass().Get() == other_load_class->GetClass().Get();
2805 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002806 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002807 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002808 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002809 }
2810}
2811
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002812void HLoadClass::SetLoadKind(LoadKind load_kind) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002813 SetPackedField<LoadKindField>(load_kind);
2814
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002815 if (load_kind != LoadKind::kRuntimeCall &&
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002816 load_kind != LoadKind::kReferrersClass) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002817 RemoveAsUserOfInput(0u);
2818 SetRawInputAt(0u, nullptr);
2819 }
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002820
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002821 if (!NeedsEnvironment()) {
2822 RemoveEnvironment();
2823 SetSideEffects(SideEffects::None());
2824 }
2825}
2826
2827std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2828 switch (rhs) {
2829 case HLoadClass::LoadKind::kReferrersClass:
2830 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002831 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2832 return os << "BootImageLinkTimePcRelative";
2833 case HLoadClass::LoadKind::kBootImageAddress:
2834 return os << "BootImageAddress";
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002835 case HLoadClass::LoadKind::kBootImageClassTable:
2836 return os << "BootImageClassTable";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002837 case HLoadClass::LoadKind::kBssEntry:
2838 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002839 case HLoadClass::LoadKind::kJitTableAddress:
2840 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002841 case HLoadClass::LoadKind::kRuntimeCall:
2842 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002843 default:
2844 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2845 UNREACHABLE();
2846 }
2847}
2848
Vladimir Marko372f10e2016-05-17 16:30:10 +01002849bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2850 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002851 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2852 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002853 if (string_index_ != other_load_string->string_index_ ||
2854 GetPackedFields() != other_load_string->GetPackedFields()) {
2855 return false;
2856 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002857 switch (GetLoadKind()) {
2858 case LoadKind::kBootImageAddress:
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002859 case LoadKind::kBootImageInternTable:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002860 case LoadKind::kJitTableAddress: {
2861 ScopedObjectAccess soa(Thread::Current());
2862 return GetString().Get() == other_load_string->GetString().Get();
2863 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002864 default:
2865 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002866 }
2867}
2868
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002869void HLoadString::SetLoadKind(LoadKind load_kind) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002870 // Once sharpened, the load kind should not be changed again.
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002871 DCHECK_EQ(GetLoadKind(), LoadKind::kRuntimeCall);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002872 SetPackedField<LoadKindField>(load_kind);
2873
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002874 if (load_kind != LoadKind::kRuntimeCall) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002875 RemoveAsUserOfInput(0u);
2876 SetRawInputAt(0u, nullptr);
2877 }
2878 if (!NeedsEnvironment()) {
2879 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002880 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002881 }
2882}
2883
2884std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2885 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002886 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2887 return os << "BootImageLinkTimePcRelative";
2888 case HLoadString::LoadKind::kBootImageAddress:
2889 return os << "BootImageAddress";
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002890 case HLoadString::LoadKind::kBootImageInternTable:
2891 return os << "BootImageInternTable";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002892 case HLoadString::LoadKind::kBssEntry:
2893 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002894 case HLoadString::LoadKind::kJitTableAddress:
2895 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002896 case HLoadString::LoadKind::kRuntimeCall:
2897 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002898 default:
2899 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2900 UNREACHABLE();
2901 }
2902}
2903
Mark Mendellc4701932015-04-10 13:18:51 -04002904void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002905 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2906 HEnvironment* user = use.GetUser();
2907 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002908 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002909 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002910}
2911
Artem Serovcced8ba2017-07-19 18:18:09 +01002912HInstruction* ReplaceInstrOrPhiByClone(HInstruction* instr) {
2913 HInstruction* clone = instr->Clone(instr->GetBlock()->GetGraph()->GetAllocator());
2914 HBasicBlock* block = instr->GetBlock();
2915
2916 if (instr->IsPhi()) {
2917 HPhi* phi = instr->AsPhi();
2918 DCHECK(!phi->HasEnvironment());
2919 HPhi* phi_clone = clone->AsPhi();
2920 block->ReplaceAndRemovePhiWith(phi, phi_clone);
2921 } else {
2922 block->ReplaceAndRemoveInstructionWith(instr, clone);
2923 if (instr->HasEnvironment()) {
2924 clone->CopyEnvironmentFrom(instr->GetEnvironment());
2925 HLoopInformation* loop_info = block->GetLoopInformation();
2926 if (instr->IsSuspendCheck() && loop_info != nullptr) {
2927 loop_info->SetSuspendCheck(clone->AsSuspendCheck());
2928 }
2929 }
2930 }
2931 return clone;
2932}
2933
Roland Levillainc9b21f82016-03-23 16:36:59 +00002934// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002935HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01002936 ArenaAllocator* allocator = GetAllocator();
Mark Mendellf6529172015-11-17 11:16:56 -05002937
2938 if (cond->IsCondition() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002939 !DataType::IsFloatingPointType(cond->InputAt(0)->GetType())) {
Mark Mendellf6529172015-11-17 11:16:56 -05002940 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2941 HInstruction* lhs = cond->InputAt(0);
2942 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002943 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002944 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2945 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2946 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2947 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2948 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2949 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2950 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2951 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2952 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2953 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2954 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002955 default:
2956 LOG(FATAL) << "Unexpected condition";
2957 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002958 }
2959 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2960 return replacement;
2961 } else if (cond->IsIntConstant()) {
2962 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002963 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002964 return GetIntConstant(1);
2965 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002966 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002967 return GetIntConstant(0);
2968 }
2969 } else {
2970 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2971 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2972 return replacement;
2973 }
2974}
2975
Roland Levillainc9285912015-12-18 10:38:42 +00002976std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2977 os << "["
2978 << " source=" << rhs.GetSource()
2979 << " destination=" << rhs.GetDestination()
2980 << " type=" << rhs.GetType()
2981 << " instruction=";
2982 if (rhs.GetInstruction() != nullptr) {
2983 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2984 } else {
2985 os << "null";
2986 }
2987 os << " ]";
2988 return os;
2989}
2990
Roland Levillain86503782016-02-11 19:07:30 +00002991std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2992 switch (rhs) {
2993 case TypeCheckKind::kUnresolvedCheck:
2994 return os << "unresolved_check";
2995 case TypeCheckKind::kExactCheck:
2996 return os << "exact_check";
2997 case TypeCheckKind::kClassHierarchyCheck:
2998 return os << "class_hierarchy_check";
2999 case TypeCheckKind::kAbstractClassCheck:
3000 return os << "abstract_class_check";
3001 case TypeCheckKind::kInterfaceCheck:
3002 return os << "interface_check";
3003 case TypeCheckKind::kArrayObjectCheck:
3004 return os << "array_object_check";
3005 case TypeCheckKind::kArrayCheck:
3006 return os << "array_check";
3007 default:
3008 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
3009 UNREACHABLE();
3010 }
3011}
3012
Andreas Gampe26de38b2016-07-27 17:53:11 -07003013std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
3014 switch (kind) {
3015 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003016 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003017 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003018 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003019 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003020 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003021 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003022 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003023 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003024 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003025
3026 default:
3027 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
3028 UNREACHABLE();
3029 }
3030}
3031
Nicolas Geoffray818f2102014-02-18 16:43:35 +00003032} // namespace art