blob: fff61f5727fcdd8fc2697b7e8c8a090d9c0a8ba3 [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
Roland Levillainccc07a92014-09-16 14:48:16 +0100848void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
849 HInstruction* replacement) {
850 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400851 if (initial->IsControlFlow()) {
852 // We can only replace a control flow instruction with another control flow instruction.
853 DCHECK(replacement->IsControlFlow());
854 DCHECK_EQ(replacement->GetId(), -1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100855 DCHECK_EQ(replacement->GetType(), DataType::Type::kVoid);
Mark Mendell805b3b52015-09-18 14:10:29 -0400856 DCHECK_EQ(initial->GetBlock(), this);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100857 DCHECK_EQ(initial->GetType(), DataType::Type::kVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100858 DCHECK(initial->GetUses().empty());
859 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400860 replacement->SetBlock(this);
861 replacement->SetId(GetGraph()->GetNextInstructionId());
862 instructions_.InsertInstructionBefore(replacement, initial);
863 UpdateInputsUsers(replacement);
864 } else {
865 InsertInstructionBefore(replacement, initial);
866 initial->ReplaceWith(replacement);
867 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100868 RemoveInstruction(initial);
869}
870
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100871static void Add(HInstructionList* instruction_list,
872 HBasicBlock* block,
873 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000874 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000875 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100876 instruction->SetBlock(block);
877 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100878 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100879 instruction_list->AddInstruction(instruction);
880}
881
882void HBasicBlock::AddInstruction(HInstruction* instruction) {
883 Add(&instructions_, this, instruction);
884}
885
886void HBasicBlock::AddPhi(HPhi* phi) {
887 Add(&phis_, this, phi);
888}
889
David Brazdilc3d743f2015-04-22 13:40:50 +0100890void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
891 DCHECK(!cursor->IsPhi());
892 DCHECK(!instruction->IsPhi());
893 DCHECK_EQ(instruction->GetId(), -1);
894 DCHECK_NE(cursor->GetId(), -1);
895 DCHECK_EQ(cursor->GetBlock(), this);
896 DCHECK(!instruction->IsControlFlow());
897 instruction->SetBlock(this);
898 instruction->SetId(GetGraph()->GetNextInstructionId());
899 UpdateInputsUsers(instruction);
900 instructions_.InsertInstructionBefore(instruction, cursor);
901}
902
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100903void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
904 DCHECK(!cursor->IsPhi());
905 DCHECK(!instruction->IsPhi());
906 DCHECK_EQ(instruction->GetId(), -1);
907 DCHECK_NE(cursor->GetId(), -1);
908 DCHECK_EQ(cursor->GetBlock(), this);
909 DCHECK(!instruction->IsControlFlow());
910 DCHECK(!cursor->IsControlFlow());
911 instruction->SetBlock(this);
912 instruction->SetId(GetGraph()->GetNextInstructionId());
913 UpdateInputsUsers(instruction);
914 instructions_.InsertInstructionAfter(instruction, cursor);
915}
916
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100917void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
918 DCHECK_EQ(phi->GetId(), -1);
919 DCHECK_NE(cursor->GetId(), -1);
920 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100921 phi->SetBlock(this);
922 phi->SetId(GetGraph()->GetNextInstructionId());
923 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100924 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100925}
926
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100927static void Remove(HInstructionList* instruction_list,
928 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000929 HInstruction* instruction,
930 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100931 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100932 instruction->SetBlock(nullptr);
933 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000934 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100935 DCHECK(instruction->GetUses().empty());
936 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000937 RemoveAsUser(instruction);
938 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100939}
940
David Brazdil1abb4192015-02-17 18:33:36 +0000941void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100942 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000943 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100944}
945
David Brazdil1abb4192015-02-17 18:33:36 +0000946void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
947 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100948}
949
David Brazdilc7508e92015-04-27 13:28:57 +0100950void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
951 if (instruction->IsPhi()) {
952 RemovePhi(instruction->AsPhi(), ensure_safety);
953 } else {
954 RemoveInstruction(instruction, ensure_safety);
955 }
956}
957
Vladimir Marko69d310e2017-10-09 14:12:23 +0100958void HEnvironment::CopyFrom(ArrayRef<HInstruction* const> locals) {
Vladimir Marko71bf8092015-09-15 15:33:14 +0100959 for (size_t i = 0; i < locals.size(); i++) {
960 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100961 SetRawEnvAt(i, instruction);
962 if (instruction != nullptr) {
963 instruction->AddEnvUseAt(this, i);
964 }
965 }
966}
967
David Brazdiled596192015-01-23 10:39:45 +0000968void HEnvironment::CopyFrom(HEnvironment* env) {
969 for (size_t i = 0; i < env->Size(); i++) {
970 HInstruction* instruction = env->GetInstructionAt(i);
971 SetRawEnvAt(i, instruction);
972 if (instruction != nullptr) {
973 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100974 }
David Brazdiled596192015-01-23 10:39:45 +0000975 }
976}
977
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700978void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
979 HBasicBlock* loop_header) {
980 DCHECK(loop_header->IsLoopHeader());
981 for (size_t i = 0; i < env->Size(); i++) {
982 HInstruction* instruction = env->GetInstructionAt(i);
983 SetRawEnvAt(i, instruction);
984 if (instruction == nullptr) {
985 continue;
986 }
987 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
988 // At the end of the loop pre-header, the corresponding value for instruction
989 // is the first input of the phi.
990 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700991 SetRawEnvAt(i, initial);
992 initial->AddEnvUseAt(this, i);
993 } else {
994 instruction->AddEnvUseAt(this, i);
995 }
996 }
997}
998
David Brazdil1abb4192015-02-17 18:33:36 +0000999void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +01001000 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
1001 HInstruction* user = env_use.GetInstruction();
1002 auto before_env_use_node = env_use.GetBeforeUseNode();
1003 user->env_uses_.erase_after(before_env_use_node);
1004 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001005}
1006
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001007HInstruction::InstructionKind HInstruction::GetKind() const {
1008 return GetKindInternal();
1009}
1010
Calin Juravle77520bc2015-01-12 18:45:46 +00001011HInstruction* HInstruction::GetNextDisregardingMoves() const {
1012 HInstruction* next = GetNext();
1013 while (next != nullptr && next->IsParallelMove()) {
1014 next = next->GetNext();
1015 }
1016 return next;
1017}
1018
1019HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1020 HInstruction* previous = GetPrevious();
1021 while (previous != nullptr && previous->IsParallelMove()) {
1022 previous = previous->GetPrevious();
1023 }
1024 return previous;
1025}
1026
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001027void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001028 if (first_instruction_ == nullptr) {
1029 DCHECK(last_instruction_ == nullptr);
1030 first_instruction_ = last_instruction_ = instruction;
1031 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001032 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001033 last_instruction_->next_ = instruction;
1034 instruction->previous_ = last_instruction_;
1035 last_instruction_ = instruction;
1036 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001037}
1038
David Brazdilc3d743f2015-04-22 13:40:50 +01001039void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1040 DCHECK(Contains(cursor));
1041 if (cursor == first_instruction_) {
1042 cursor->previous_ = instruction;
1043 instruction->next_ = cursor;
1044 first_instruction_ = instruction;
1045 } else {
1046 instruction->previous_ = cursor->previous_;
1047 instruction->next_ = cursor;
1048 cursor->previous_ = instruction;
1049 instruction->previous_->next_ = instruction;
1050 }
1051}
1052
1053void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1054 DCHECK(Contains(cursor));
1055 if (cursor == last_instruction_) {
1056 cursor->next_ = instruction;
1057 instruction->previous_ = cursor;
1058 last_instruction_ = instruction;
1059 } else {
1060 instruction->next_ = cursor->next_;
1061 instruction->previous_ = cursor;
1062 cursor->next_ = instruction;
1063 instruction->next_->previous_ = instruction;
1064 }
1065}
1066
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001067void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1068 if (instruction->previous_ != nullptr) {
1069 instruction->previous_->next_ = instruction->next_;
1070 }
1071 if (instruction->next_ != nullptr) {
1072 instruction->next_->previous_ = instruction->previous_;
1073 }
1074 if (instruction == first_instruction_) {
1075 first_instruction_ = instruction->next_;
1076 }
1077 if (instruction == last_instruction_) {
1078 last_instruction_ = instruction->previous_;
1079 }
1080}
1081
Roland Levillain6b469232014-09-25 10:10:38 +01001082bool HInstructionList::Contains(HInstruction* instruction) const {
1083 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1084 if (it.Current() == instruction) {
1085 return true;
1086 }
1087 }
1088 return false;
1089}
1090
Roland Levillainccc07a92014-09-16 14:48:16 +01001091bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1092 const HInstruction* instruction2) const {
1093 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1094 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1095 if (it.Current() == instruction1) {
1096 return true;
1097 }
1098 if (it.Current() == instruction2) {
1099 return false;
1100 }
1101 }
1102 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1103 return true;
1104}
1105
Roland Levillain6c82d402014-10-13 16:10:27 +01001106bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1107 if (other_instruction == this) {
1108 // An instruction does not strictly dominate itself.
1109 return false;
1110 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001111 HBasicBlock* block = GetBlock();
1112 HBasicBlock* other_block = other_instruction->GetBlock();
1113 if (block != other_block) {
1114 return GetBlock()->Dominates(other_instruction->GetBlock());
1115 } else {
1116 // If both instructions are in the same block, ensure this
1117 // instruction comes before `other_instruction`.
1118 if (IsPhi()) {
1119 if (!other_instruction->IsPhi()) {
1120 // Phis appear before non phi-instructions so this instruction
1121 // dominates `other_instruction`.
1122 return true;
1123 } else {
1124 // There is no order among phis.
1125 LOG(FATAL) << "There is no dominance between phis of a same block.";
1126 return false;
1127 }
1128 } else {
1129 // `this` is not a phi.
1130 if (other_instruction->IsPhi()) {
1131 // Phis appear before non phi-instructions so this instruction
1132 // does not dominate `other_instruction`.
1133 return false;
1134 } else {
1135 // Check whether this instruction comes before
1136 // `other_instruction` in the instruction list.
1137 return block->GetInstructions().FoundBefore(this, other_instruction);
1138 }
1139 }
1140 }
1141}
1142
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001143void HInstruction::RemoveEnvironment() {
1144 RemoveEnvironmentUses(this);
1145 environment_ = nullptr;
1146}
1147
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001148void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001149 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001150 // Note: fixup_end remains valid across splice_after().
1151 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1152 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1153 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001154
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001155 // Note: env_fixup_end remains valid across splice_after().
1156 auto env_fixup_end =
1157 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1158 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1159 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001160
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001161 DCHECK(uses_.empty());
1162 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001163}
1164
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001165void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1166 const HUseList<HInstruction*>& uses = GetUses();
1167 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1168 HInstruction* user = it->GetUser();
1169 size_t index = it->GetIndex();
1170 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1171 ++it;
1172 if (dominator->StrictlyDominates(user)) {
1173 user->ReplaceInput(replacement, index);
1174 }
1175 }
1176}
1177
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001178void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001179 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001180 if (input_use.GetInstruction() == replacement) {
1181 // Nothing to do.
1182 return;
1183 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001184 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001185 // Note: fixup_end remains valid across splice_after().
1186 auto fixup_end =
1187 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1188 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1189 input_use.GetInstruction()->uses_,
1190 before_use_node);
1191 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1192 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001193}
1194
Nicolas Geoffray39468442014-09-02 15:17:15 +01001195size_t HInstruction::EnvironmentSize() const {
1196 return HasEnvironment() ? environment_->Size() : 0;
1197}
1198
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001199void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001200 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001201 inputs_.push_back(HUserRecord<HInstruction*>(input));
1202 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001203}
1204
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001205void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1206 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1207 input->AddUseAt(this, index);
1208 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1209 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1210 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1211 inputs_[i].GetUseNode()->SetIndex(i);
1212 }
1213}
1214
1215void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001216 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001217 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001218 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1219 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1220 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1221 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001222 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001223}
1224
Igor Murashkind01745e2017-04-05 16:40:31 -07001225void HVariableInputSizeInstruction::RemoveAllInputs() {
1226 RemoveAsUserOfAllInputs();
1227 DCHECK(!HasNonEnvironmentUses());
1228
1229 inputs_.clear();
1230 DCHECK_EQ(0u, InputCount());
1231}
1232
Igor Murashkin6ef45672017-08-08 13:59:55 -07001233size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001234 DCHECK(instruction->GetBlock() != nullptr);
1235 // Removing constructor fences only makes sense for instructions with an object return type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001236 DCHECK_EQ(DataType::Type::kReference, instruction->GetType());
Igor Murashkind01745e2017-04-05 16:40:31 -07001237
Igor Murashkin6ef45672017-08-08 13:59:55 -07001238 // Return how many instructions were removed for statistic purposes.
1239 size_t remove_count = 0;
1240
Igor Murashkind01745e2017-04-05 16:40:31 -07001241 // Efficient implementation that simultaneously (in one pass):
1242 // * Scans the uses list for all constructor fences.
1243 // * Deletes that constructor fence from the uses list of `instruction`.
1244 // * Deletes `instruction` from the constructor fence's inputs.
1245 // * Deletes the constructor fence if it now has 0 inputs.
1246
1247 const HUseList<HInstruction*>& uses = instruction->GetUses();
1248 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1249 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1250 const HUseListNode<HInstruction*>& use_node = *it;
1251 HInstruction* const use_instruction = use_node.GetUser();
1252
1253 // Advance the iterator immediately once we fetch the use_node.
1254 // Warning: If the input is removed, the current iterator becomes invalid.
1255 ++it;
1256
1257 if (use_instruction->IsConstructorFence()) {
1258 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1259 size_t input_index = use_node.GetIndex();
1260
1261 // Process the candidate instruction for removal
1262 // from the graph.
1263
1264 // Constructor fence instructions are never
1265 // used by other instructions.
1266 //
1267 // If we wanted to make this more generic, it
1268 // could be a runtime if statement.
1269 DCHECK(!ctor_fence->HasUses());
1270
1271 // A constructor fence's return type is "kPrimVoid"
1272 // and therefore it can't have any environment uses.
1273 DCHECK(!ctor_fence->HasEnvironmentUses());
1274
1275 // Remove the inputs first, otherwise removing the instruction
1276 // will try to remove its uses while we are already removing uses
1277 // and this operation will fail.
1278 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1279
1280 // Removing the input will also remove the `use_node`.
1281 // (Do not look at `use_node` after this, it will be a dangling reference).
1282 ctor_fence->RemoveInputAt(input_index);
1283
1284 // Once all inputs are removed, the fence is considered dead and
1285 // is removed.
1286 if (ctor_fence->InputCount() == 0u) {
1287 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
Igor Murashkin6ef45672017-08-08 13:59:55 -07001288 ++remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001289 }
1290 }
1291 }
1292
1293 if (kIsDebugBuild) {
1294 // Post-condition checks:
1295 // * None of the uses of `instruction` are a constructor fence.
1296 // * The `instruction` itself did not get removed from a block.
1297 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1298 CHECK(!use_node.GetUser()->IsConstructorFence());
1299 }
1300 CHECK(instruction->GetBlock() != nullptr);
1301 }
Igor Murashkin6ef45672017-08-08 13:59:55 -07001302
1303 return remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001304}
1305
Igor Murashkindd018df2017-08-09 10:38:31 -07001306void HConstructorFence::Merge(HConstructorFence* other) {
1307 // Do not delete yourself from the graph.
1308 DCHECK(this != other);
1309 // Don't try to merge with an instruction not associated with a block.
1310 DCHECK(other->GetBlock() != nullptr);
1311 // A constructor fence's return type is "kPrimVoid"
1312 // and therefore it cannot have any environment uses.
1313 DCHECK(!other->HasEnvironmentUses());
1314
1315 auto has_input = [](HInstruction* haystack, HInstruction* needle) {
1316 // Check if `haystack` has `needle` as any of its inputs.
1317 for (size_t input_count = 0; input_count < haystack->InputCount(); ++input_count) {
1318 if (haystack->InputAt(input_count) == needle) {
1319 return true;
1320 }
1321 }
1322 return false;
1323 };
1324
1325 // Add any inputs from `other` into `this` if it wasn't already an input.
1326 for (size_t input_count = 0; input_count < other->InputCount(); ++input_count) {
1327 HInstruction* other_input = other->InputAt(input_count);
1328 if (!has_input(this, other_input)) {
1329 AddInput(other_input);
1330 }
1331 }
1332
1333 other->GetBlock()->RemoveInstruction(other);
1334}
1335
1336HInstruction* HConstructorFence::GetAssociatedAllocation(bool ignore_inputs) {
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001337 HInstruction* new_instance_inst = GetPrevious();
1338 // Check if the immediately preceding instruction is a new-instance/new-array.
1339 // Otherwise this fence is for protecting final fields.
1340 if (new_instance_inst != nullptr &&
1341 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
Igor Murashkindd018df2017-08-09 10:38:31 -07001342 if (ignore_inputs) {
1343 // If inputs are ignored, simply check if the predecessor is
1344 // *any* HNewInstance/HNewArray.
1345 //
1346 // Inputs are normally only ignored for prepare_for_register_allocation,
1347 // at which point *any* prior HNewInstance/Array can be considered
1348 // associated.
1349 return new_instance_inst;
1350 } else {
1351 // Normal case: There must be exactly 1 input and the previous instruction
1352 // must be that input.
1353 if (InputCount() == 1u && InputAt(0) == new_instance_inst) {
1354 return new_instance_inst;
1355 }
1356 }
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001357 }
Igor Murashkindd018df2017-08-09 10:38:31 -07001358 return nullptr;
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001359}
1360
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001361#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001362void H##name::Accept(HGraphVisitor* visitor) { \
1363 visitor->Visit##name(this); \
1364}
1365
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001366FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001367
1368#undef DEFINE_ACCEPT
1369
1370void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001371 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1372 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001373 if (block != nullptr) {
1374 VisitBasicBlock(block);
1375 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001376 }
1377}
1378
Roland Levillain633021e2014-10-01 14:12:25 +01001379void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001380 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1381 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001382 }
1383}
1384
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001385void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001386 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001387 it.Current()->Accept(this);
1388 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001389 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001390 it.Current()->Accept(this);
1391 }
1392}
1393
Mark Mendelle82549b2015-05-06 10:55:34 -04001394HConstant* HTypeConversion::TryStaticEvaluation() const {
1395 HGraph* graph = GetBlock()->GetGraph();
1396 if (GetInput()->IsIntConstant()) {
1397 int32_t value = GetInput()->AsIntConstant()->GetValue();
1398 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001399 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001400 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001401 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001402 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001403 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001404 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001405 default:
1406 return nullptr;
1407 }
1408 } else if (GetInput()->IsLongConstant()) {
1409 int64_t value = GetInput()->AsLongConstant()->GetValue();
1410 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001411 case DataType::Type::kInt32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001412 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001413 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001414 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001415 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001416 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001417 default:
1418 return nullptr;
1419 }
1420 } else if (GetInput()->IsFloatConstant()) {
1421 float value = GetInput()->AsFloatConstant()->GetValue();
1422 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001423 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001424 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001425 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001426 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001427 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001428 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001429 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1430 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001431 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001432 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001433 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001434 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001435 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001436 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001437 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1438 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001439 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001440 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001441 default:
1442 return nullptr;
1443 }
1444 } else if (GetInput()->IsDoubleConstant()) {
1445 double value = GetInput()->AsDoubleConstant()->GetValue();
1446 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001447 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001448 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001449 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001450 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001451 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001452 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001453 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1454 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001455 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001456 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001457 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001458 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001459 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001460 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001461 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1462 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001463 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001464 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001465 default:
1466 return nullptr;
1467 }
1468 }
1469 return nullptr;
1470}
1471
Roland Levillain9240d6a2014-10-20 16:47:04 +01001472HConstant* HUnaryOperation::TryStaticEvaluation() const {
1473 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001474 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001475 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001476 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001477 } else if (kEnableFloatingPointStaticEvaluation) {
1478 if (GetInput()->IsFloatConstant()) {
1479 return Evaluate(GetInput()->AsFloatConstant());
1480 } else if (GetInput()->IsDoubleConstant()) {
1481 return Evaluate(GetInput()->AsDoubleConstant());
1482 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001483 }
1484 return nullptr;
1485}
1486
1487HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001488 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1489 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001490 } else if (GetLeft()->IsLongConstant()) {
1491 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001492 // The binop(long, int) case is only valid for shifts and rotations.
1493 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001494 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1495 } else if (GetRight()->IsLongConstant()) {
1496 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001497 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001498 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001499 // The binop(null, null) case is only valid for equal and not-equal conditions.
1500 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001501 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001502 } else if (kEnableFloatingPointStaticEvaluation) {
1503 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1504 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1505 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1506 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1507 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001508 }
1509 return nullptr;
1510}
Dave Allison20dfc792014-06-16 20:44:29 -07001511
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001512HConstant* HBinaryOperation::GetConstantRight() const {
1513 if (GetRight()->IsConstant()) {
1514 return GetRight()->AsConstant();
1515 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1516 return GetLeft()->AsConstant();
1517 } else {
1518 return nullptr;
1519 }
1520}
1521
1522// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001523// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001524HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1525 HInstruction* most_constant_right = GetConstantRight();
1526 if (most_constant_right == nullptr) {
1527 return nullptr;
1528 } else if (most_constant_right == GetLeft()) {
1529 return GetRight();
1530 } else {
1531 return GetLeft();
1532 }
1533}
1534
Roland Levillain31dd3d62016-02-16 12:21:02 +00001535std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1536 switch (rhs) {
1537 case ComparisonBias::kNoBias:
1538 return os << "no_bias";
1539 case ComparisonBias::kGtBias:
1540 return os << "gt_bias";
1541 case ComparisonBias::kLtBias:
1542 return os << "lt_bias";
1543 default:
1544 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1545 UNREACHABLE();
1546 }
1547}
1548
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001549bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1550 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001551}
1552
Vladimir Marko372f10e2016-05-17 16:30:10 +01001553bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001554 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001555 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001556 if (!InstructionDataEquals(other)) return false;
1557 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001558 HConstInputsRef inputs = GetInputs();
1559 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001560 if (inputs.size() != other_inputs.size()) return false;
1561 for (size_t i = 0; i != inputs.size(); ++i) {
1562 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001563 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001564
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001565 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001566 return true;
1567}
1568
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001569std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1570#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1571 switch (rhs) {
1572 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1573 default:
1574 os << "Unknown instruction kind " << static_cast<int>(rhs);
1575 break;
1576 }
1577#undef DECLARE_CASE
1578 return os;
1579}
1580
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001581void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1582 if (do_checks) {
1583 DCHECK(!IsPhi());
1584 DCHECK(!IsControlFlow());
1585 DCHECK(CanBeMoved() ||
1586 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1587 IsShouldDeoptimizeFlag());
1588 DCHECK(!cursor->IsPhi());
1589 }
David Brazdild6c205e2016-06-07 14:20:52 +01001590
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001591 next_->previous_ = previous_;
1592 if (previous_ != nullptr) {
1593 previous_->next_ = next_;
1594 }
1595 if (block_->instructions_.first_instruction_ == this) {
1596 block_->instructions_.first_instruction_ = next_;
1597 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001598 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001599
1600 previous_ = cursor->previous_;
1601 if (previous_ != nullptr) {
1602 previous_->next_ = this;
1603 }
1604 next_ = cursor;
1605 cursor->previous_ = this;
1606 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001607
1608 if (block_->instructions_.first_instruction_ == cursor) {
1609 block_->instructions_.first_instruction_ = this;
1610 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001611}
1612
Vladimir Markofb337ea2015-11-25 15:25:10 +00001613void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1614 DCHECK(!CanThrow());
1615 DCHECK(!HasSideEffects());
1616 DCHECK(!HasEnvironmentUses());
1617 DCHECK(HasNonEnvironmentUses());
1618 DCHECK(!IsPhi()); // Makes no sense for Phi.
1619 DCHECK_EQ(InputCount(), 0u);
1620
1621 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001622 auto uses_it = GetUses().begin();
1623 auto uses_end = GetUses().end();
1624 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1625 ++uses_it;
1626 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1627 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001628 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001629 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001630 // This instruction has uses in two or more blocks. Find the common dominator.
1631 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001632 for (; uses_it != uses_end; ++uses_it) {
1633 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001634 }
1635 target_block = finder.Get();
1636 DCHECK(target_block != nullptr);
1637 }
1638 // Move to the first dominator not in a loop.
1639 while (target_block->IsInLoop()) {
1640 target_block = target_block->GetDominator();
1641 DCHECK(target_block != nullptr);
1642 }
1643
1644 // Find insertion position.
1645 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001646 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1647 if (use.GetUser()->GetBlock() == target_block &&
1648 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1649 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001650 }
1651 }
1652 if (insert_pos == nullptr) {
1653 // No user in `target_block`, insert before the control flow instruction.
1654 insert_pos = target_block->GetLastInstruction();
1655 DCHECK(insert_pos->IsControlFlow());
1656 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1657 if (insert_pos->IsIf()) {
1658 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1659 if (if_input == insert_pos->GetPrevious()) {
1660 insert_pos = if_input;
1661 }
1662 }
1663 }
1664 MoveBefore(insert_pos);
1665}
1666
David Brazdilfc6a86a2015-06-26 10:33:45 +00001667HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001668 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001669 DCHECK_EQ(cursor->GetBlock(), this);
1670
Vladimir Markoca6fff82017-10-03 14:49:14 +01001671 HBasicBlock* new_block =
1672 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001673 new_block->instructions_.first_instruction_ = cursor;
1674 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1675 instructions_.last_instruction_ = cursor->previous_;
1676 if (cursor->previous_ == nullptr) {
1677 instructions_.first_instruction_ = nullptr;
1678 } else {
1679 cursor->previous_->next_ = nullptr;
1680 cursor->previous_ = nullptr;
1681 }
1682
1683 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001684 AddInstruction(new (GetGraph()->GetAllocator()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001685
Vladimir Marko60584552015-09-03 13:35:12 +00001686 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001687 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001688 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001689 new_block->successors_.swap(successors_);
1690 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001691 AddSuccessor(new_block);
1692
David Brazdil56e1acc2015-06-30 15:41:36 +01001693 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001694 return new_block;
1695}
1696
David Brazdild7558da2015-09-22 13:04:14 +01001697HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001698 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001699 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1700
Vladimir Markoca6fff82017-10-03 14:49:14 +01001701 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
David Brazdild7558da2015-09-22 13:04:14 +01001702
1703 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001704 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1705 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001706 new_block->predecessors_.swap(predecessors_);
1707 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001708 AddPredecessor(new_block);
1709
1710 GetGraph()->AddBlock(new_block);
1711 return new_block;
1712}
1713
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001714HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1715 DCHECK_EQ(cursor->GetBlock(), this);
1716
Vladimir Markoca6fff82017-10-03 14:49:14 +01001717 HBasicBlock* new_block =
1718 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001719 new_block->instructions_.first_instruction_ = cursor;
1720 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1721 instructions_.last_instruction_ = cursor->previous_;
1722 if (cursor->previous_ == nullptr) {
1723 instructions_.first_instruction_ = nullptr;
1724 } else {
1725 cursor->previous_->next_ = nullptr;
1726 cursor->previous_ = nullptr;
1727 }
1728
1729 new_block->instructions_.SetBlockOfInstructions(new_block);
1730
1731 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001732 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1733 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001734 new_block->successors_.swap(successors_);
1735 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001736
1737 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1738 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001739 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001740 new_block->dominated_blocks_.swap(dominated_blocks_);
1741 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001742 return new_block;
1743}
1744
1745HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001746 DCHECK(!cursor->IsControlFlow());
1747 DCHECK_NE(instructions_.last_instruction_, cursor);
1748 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001749
Vladimir Markoca6fff82017-10-03 14:49:14 +01001750 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001751 new_block->instructions_.first_instruction_ = cursor->GetNext();
1752 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1753 cursor->next_->previous_ = nullptr;
1754 cursor->next_ = nullptr;
1755 instructions_.last_instruction_ = cursor;
1756
1757 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001758 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001759 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001760 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001761 new_block->successors_.swap(successors_);
1762 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001763
Vladimir Marko60584552015-09-03 13:35:12 +00001764 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001765 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001766 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001767 new_block->dominated_blocks_.swap(dominated_blocks_);
1768 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001769 return new_block;
1770}
1771
David Brazdilec16f792015-08-19 15:04:01 +01001772const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001773 if (EndsWithTryBoundary()) {
1774 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1775 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001776 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001777 return try_boundary;
1778 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001779 DCHECK(IsTryBlock());
1780 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001781 return nullptr;
1782 }
David Brazdilec16f792015-08-19 15:04:01 +01001783 } else if (IsTryBlock()) {
1784 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001785 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001786 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001787 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001788}
1789
David Brazdild7558da2015-09-22 13:04:14 +01001790bool HBasicBlock::HasThrowingInstructions() const {
1791 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1792 if (it.Current()->CanThrow()) {
1793 return true;
1794 }
1795 }
1796 return false;
1797}
1798
David Brazdilfc6a86a2015-06-26 10:33:45 +00001799static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1800 return block.GetPhis().IsEmpty()
1801 && !block.GetInstructions().IsEmpty()
1802 && block.GetFirstInstruction() == block.GetLastInstruction();
1803}
1804
David Brazdil46e2a392015-03-16 17:31:52 +00001805bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001806 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1807}
1808
Mads Ager16e52892017-07-14 13:11:37 +02001809bool HBasicBlock::IsSingleReturn() const {
1810 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
1811}
1812
Mingyao Yang46721ef2017-10-05 14:45:17 -07001813bool HBasicBlock::IsSingleReturnOrReturnVoidAllowingPhis() const {
1814 return (GetFirstInstruction() == GetLastInstruction()) &&
1815 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
1816}
1817
David Brazdilfc6a86a2015-06-26 10:33:45 +00001818bool HBasicBlock::IsSingleTryBoundary() const {
1819 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001820}
1821
David Brazdil8d5b8b22015-03-24 10:51:52 +00001822bool HBasicBlock::EndsWithControlFlowInstruction() const {
1823 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1824}
1825
David Brazdilb2bd1c52015-03-25 11:17:37 +00001826bool HBasicBlock::EndsWithIf() const {
1827 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1828}
1829
David Brazdilffee3d32015-07-06 11:48:53 +01001830bool HBasicBlock::EndsWithTryBoundary() const {
1831 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1832}
1833
David Brazdilb2bd1c52015-03-25 11:17:37 +00001834bool HBasicBlock::HasSinglePhi() const {
1835 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1836}
1837
David Brazdild26a4112015-11-10 11:07:31 +00001838ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1839 if (EndsWithTryBoundary()) {
1840 // The normal-flow successor of HTryBoundary is always stored at index zero.
1841 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1842 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1843 } else {
1844 // All successors of blocks not ending with TryBoundary are normal.
1845 return ArrayRef<HBasicBlock* const>(successors_);
1846 }
1847}
1848
1849ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1850 if (EndsWithTryBoundary()) {
1851 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1852 } else {
1853 // Blocks not ending with TryBoundary do not have exceptional successors.
1854 return ArrayRef<HBasicBlock* const>();
1855 }
1856}
1857
David Brazdilffee3d32015-07-06 11:48:53 +01001858bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001859 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1860 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1861
1862 size_t length = handlers1.size();
1863 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001864 return false;
1865 }
1866
David Brazdilb618ade2015-07-29 10:31:29 +01001867 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001868 for (size_t i = 0; i < length; ++i) {
1869 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001870 return false;
1871 }
1872 }
1873 return true;
1874}
1875
David Brazdil2d7352b2015-04-20 14:52:42 +01001876size_t HInstructionList::CountSize() const {
1877 size_t size = 0;
1878 HInstruction* current = first_instruction_;
1879 for (; current != nullptr; current = current->GetNext()) {
1880 size++;
1881 }
1882 return size;
1883}
1884
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001885void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1886 for (HInstruction* current = first_instruction_;
1887 current != nullptr;
1888 current = current->GetNext()) {
1889 current->SetBlock(block);
1890 }
1891}
1892
1893void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1894 DCHECK(Contains(cursor));
1895 if (!instruction_list.IsEmpty()) {
1896 if (cursor == last_instruction_) {
1897 last_instruction_ = instruction_list.last_instruction_;
1898 } else {
1899 cursor->next_->previous_ = instruction_list.last_instruction_;
1900 }
1901 instruction_list.last_instruction_->next_ = cursor->next_;
1902 cursor->next_ = instruction_list.first_instruction_;
1903 instruction_list.first_instruction_->previous_ = cursor;
1904 }
1905}
1906
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001907void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1908 DCHECK(Contains(cursor));
1909 if (!instruction_list.IsEmpty()) {
1910 if (cursor == first_instruction_) {
1911 first_instruction_ = instruction_list.first_instruction_;
1912 } else {
1913 cursor->previous_->next_ = instruction_list.first_instruction_;
1914 }
1915 instruction_list.last_instruction_->next_ = cursor;
1916 instruction_list.first_instruction_->previous_ = cursor->previous_;
1917 cursor->previous_ = instruction_list.last_instruction_;
1918 }
1919}
1920
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001921void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001922 if (IsEmpty()) {
1923 first_instruction_ = instruction_list.first_instruction_;
1924 last_instruction_ = instruction_list.last_instruction_;
1925 } else {
1926 AddAfter(last_instruction_, instruction_list);
1927 }
1928}
1929
David Brazdil04ff4e82015-12-10 13:54:52 +00001930// Should be called on instructions in a dead block in post order. This method
1931// assumes `insn` has been removed from all users with the exception of catch
1932// phis because of missing exceptional edges in the graph. It removes the
1933// instruction from catch phi uses, together with inputs of other catch phis in
1934// the catch block at the same index, as these must be dead too.
1935static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1936 DCHECK(!insn->HasEnvironmentUses());
1937 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001938 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1939 size_t use_index = use.GetIndex();
1940 HBasicBlock* user_block = use.GetUser()->GetBlock();
1941 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001942 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1943 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1944 }
1945 }
1946}
1947
David Brazdil2d7352b2015-04-20 14:52:42 +01001948void HBasicBlock::DisconnectAndDelete() {
1949 // Dominators must be removed after all the blocks they dominate. This way
1950 // a loop header is removed last, a requirement for correct loop information
1951 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001952 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001953
David Brazdil9eeebf62016-03-24 11:18:15 +00001954 // The following steps gradually remove the block from all its dependants in
1955 // post order (b/27683071).
1956
1957 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1958 // We need to do this before step (4) which destroys the predecessor list.
1959 HBasicBlock* loop_update_start = this;
1960 if (IsLoopHeader()) {
1961 HLoopInformation* loop_info = GetLoopInformation();
1962 // All other blocks in this loop should have been removed because the header
1963 // was their dominator.
1964 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1965 DCHECK(!loop_info->IsIrreducible());
1966 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1967 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1968 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001969 }
1970
David Brazdil9eeebf62016-03-24 11:18:15 +00001971 // (2) Disconnect the block from its successors and update their phis.
1972 for (HBasicBlock* successor : successors_) {
1973 // Delete this block from the list of predecessors.
1974 size_t this_index = successor->GetPredecessorIndexOf(this);
1975 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1976
1977 // Check that `successor` has other predecessors, otherwise `this` is the
1978 // dominator of `successor` which violates the order DCHECKed at the top.
1979 DCHECK(!successor->predecessors_.empty());
1980
1981 // Remove this block's entries in the successor's phis. Skip exceptional
1982 // successors because catch phi inputs do not correspond to predecessor
1983 // blocks but throwing instructions. The inputs of the catch phis will be
1984 // updated in step (3).
1985 if (!successor->IsCatchBlock()) {
1986 if (successor->predecessors_.size() == 1u) {
1987 // The successor has just one predecessor left. Replace phis with the only
1988 // remaining input.
1989 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1990 HPhi* phi = phi_it.Current()->AsPhi();
1991 phi->ReplaceWith(phi->InputAt(1 - this_index));
1992 successor->RemovePhi(phi);
1993 }
1994 } else {
1995 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1996 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1997 }
1998 }
1999 }
2000 }
2001 successors_.clear();
2002
2003 // (3) Remove instructions and phis. Instructions should have no remaining uses
2004 // except in catch phis. If an instruction is used by a catch phi at `index`,
2005 // remove `index`-th input of all phis in the catch block since they are
2006 // guaranteed dead. Note that we may miss dead inputs this way but the
2007 // graph will always remain consistent.
2008 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2009 HInstruction* insn = it.Current();
2010 RemoveUsesOfDeadInstruction(insn);
2011 RemoveInstruction(insn);
2012 }
2013 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
2014 HPhi* insn = it.Current()->AsPhi();
2015 RemoveUsesOfDeadInstruction(insn);
2016 RemovePhi(insn);
2017 }
2018
2019 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002020 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00002021 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00002022 // We should not see any back edges as they would have been removed by step (3).
2023 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
2024
David Brazdil2d7352b2015-04-20 14:52:42 +01002025 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002026 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
2027 // This block is the only normal-flow successor of the TryBoundary which
2028 // makes `predecessor` dead. Since DCE removes blocks in post order,
2029 // exception handlers of this TryBoundary were already visited and any
2030 // remaining handlers therefore must be live. We remove `predecessor` from
2031 // their list of predecessors.
2032 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
2033 while (predecessor->GetSuccessors().size() > 1) {
2034 HBasicBlock* handler = predecessor->GetSuccessors()[1];
2035 DCHECK(handler->IsCatchBlock());
2036 predecessor->RemoveSuccessor(handler);
2037 handler->RemovePredecessor(predecessor);
2038 }
2039 }
2040
David Brazdil2d7352b2015-04-20 14:52:42 +01002041 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04002042 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
2043 if (num_pred_successors == 1u) {
2044 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002045 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
2046 // successor. Replace those with a HGoto.
2047 DCHECK(last_instruction->IsIf() ||
2048 last_instruction->IsPackedSwitch() ||
2049 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002050 predecessor->RemoveInstruction(last_instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002051 predecessor->AddInstruction(new (graph_->GetAllocator()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002052 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002053 // The predecessor has no remaining successors and therefore must be dead.
2054 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00002055 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04002056 predecessor->RemoveInstruction(last_instruction);
2057 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002058 // There are multiple successors left. The removed block might be a successor
2059 // of a PackedSwitch which will be completely removed (perhaps replaced with
2060 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2061 // case, leave `last_instruction` as is for now.
2062 DCHECK(last_instruction->IsPackedSwitch() ||
2063 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002064 }
David Brazdil46e2a392015-03-16 17:31:52 +00002065 }
Vladimir Marko60584552015-09-03 13:35:12 +00002066 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002067
David Brazdil9eeebf62016-03-24 11:18:15 +00002068 // (5) Remove the block from all loops it is included in. Skip the inner-most
2069 // loop if this is the loop header (see definition of `loop_update_start`)
2070 // because the loop header's predecessor list has been destroyed in step (4).
2071 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2072 HLoopInformation* loop_info = it.Current();
2073 loop_info->Remove(this);
2074 if (loop_info->IsBackEdge(*this)) {
2075 // If this was the last back edge of the loop, we deliberately leave the
2076 // loop in an inconsistent state and will fail GraphChecker unless the
2077 // entire loop is removed during the pass.
2078 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002079 }
2080 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002081
David Brazdil9eeebf62016-03-24 11:18:15 +00002082 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002083 dominator_->RemoveDominatedBlock(this);
2084 SetDominator(nullptr);
2085
David Brazdil9eeebf62016-03-24 11:18:15 +00002086 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002087 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002088 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002089}
2090
Aart Bik6b69e0a2017-01-11 10:20:43 -08002091void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2092 DCHECK(EndsWithControlFlowInstruction());
2093 RemoveInstruction(GetLastInstruction());
2094 instructions_.Add(other->GetInstructions());
2095 other->instructions_.SetBlockOfInstructions(this);
2096 other->instructions_.Clear();
2097}
2098
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002099void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002100 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002101 DCHECK(ContainsElement(dominated_blocks_, other));
2102 DCHECK_EQ(GetSingleSuccessor(), other);
2103 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002104 DCHECK(other->GetPhis().IsEmpty());
2105
David Brazdil2d7352b2015-04-20 14:52:42 +01002106 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002107 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002108
David Brazdil2d7352b2015-04-20 14:52:42 +01002109 // Remove `other` from the loops it is included in.
2110 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2111 HLoopInformation* loop_info = it.Current();
2112 loop_info->Remove(other);
2113 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002114 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002115 }
2116 }
2117
2118 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002119 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002120 for (HBasicBlock* successor : other->GetSuccessors()) {
2121 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002122 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002123 successors_.swap(other->successors_);
2124 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002125
David Brazdil2d7352b2015-04-20 14:52:42 +01002126 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002127 RemoveDominatedBlock(other);
2128 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002129 dominated->SetDominator(this);
2130 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002131 dominated_blocks_.insert(
2132 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002133 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002134 other->dominator_ = nullptr;
2135
2136 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002137 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002138
2139 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002140 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002141 other->SetGraph(nullptr);
2142}
2143
2144void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2145 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002146 DCHECK(GetDominatedBlocks().empty());
2147 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002148 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002149 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002150 DCHECK(other->GetPhis().IsEmpty());
2151 DCHECK(!other->IsInLoop());
2152
2153 // Move instructions from `other` to `this`.
2154 instructions_.Add(other->GetInstructions());
2155 other->instructions_.SetBlockOfInstructions(this);
2156
2157 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002158 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002159 for (HBasicBlock* successor : other->GetSuccessors()) {
2160 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002161 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002162 successors_.swap(other->successors_);
2163 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002164
2165 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002166 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002167 dominated->SetDominator(this);
2168 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002169 dominated_blocks_.insert(
2170 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002171 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002172 other->dominator_ = nullptr;
2173 other->graph_ = nullptr;
2174}
2175
2176void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002177 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002178 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002179 predecessor->ReplaceSuccessor(this, other);
2180 }
Vladimir Marko60584552015-09-03 13:35:12 +00002181 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002182 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002183 successor->ReplacePredecessor(this, other);
2184 }
Vladimir Marko60584552015-09-03 13:35:12 +00002185 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2186 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002187 }
2188 GetDominator()->ReplaceDominatedBlock(this, other);
2189 other->SetDominator(GetDominator());
2190 dominator_ = nullptr;
2191 graph_ = nullptr;
2192}
2193
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002194void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002195 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002196 DCHECK(block->GetSuccessors().empty());
2197 DCHECK(block->GetPredecessors().empty());
2198 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002199 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002200 DCHECK(block->GetInstructions().IsEmpty());
2201 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002202
David Brazdilc7af85d2015-05-26 12:05:55 +01002203 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002204 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002205 }
2206
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002207 RemoveElement(reverse_post_order_, block);
2208 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002209 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002210}
2211
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002212void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2213 HBasicBlock* reference,
2214 bool replace_if_back_edge) {
2215 if (block->IsLoopHeader()) {
2216 // Clear the information of which blocks are contained in that loop. Since the
2217 // information is stored as a bit vector based on block ids, we have to update
2218 // it, as those block ids were specific to the callee graph and we are now adding
2219 // these blocks to the caller graph.
2220 block->GetLoopInformation()->ClearAllBlocks();
2221 }
2222
2223 // If not already in a loop, update the loop information.
2224 if (!block->IsInLoop()) {
2225 block->SetLoopInformation(reference->GetLoopInformation());
2226 }
2227
2228 // If the block is in a loop, update all its outward loops.
2229 HLoopInformation* loop_info = block->GetLoopInformation();
2230 if (loop_info != nullptr) {
2231 for (HLoopInformationOutwardIterator loop_it(*block);
2232 !loop_it.Done();
2233 loop_it.Advance()) {
2234 loop_it.Current()->Add(block);
2235 }
2236 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2237 loop_info->ReplaceBackEdge(reference, block);
2238 }
2239 }
2240
2241 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2242 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2243 ? reference->GetTryCatchInformation()
2244 : nullptr;
2245 block->SetTryCatchInformation(try_catch_info);
2246}
2247
Calin Juravle2e768302015-07-28 14:41:11 +00002248HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002249 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002250 // Update the environments in this graph to have the invoke's environment
2251 // as parent.
2252 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002253 // Skip the entry block, we do not need to update the entry's suspend check.
2254 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002255 for (HInstructionIterator instr_it(block->GetInstructions());
2256 !instr_it.Done();
2257 instr_it.Advance()) {
2258 HInstruction* current = instr_it.Current();
2259 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002260 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002261 current->GetEnvironment()->SetAndCopyParentChain(
Vladimir Markoca6fff82017-10-03 14:49:14 +01002262 outer_graph->GetAllocator(), invoke->GetEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002263 }
2264 }
2265 }
2266 }
2267 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002268
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002269 if (HasBoundsChecks()) {
2270 outer_graph->SetHasBoundsChecks(true);
2271 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002272 if (HasLoops()) {
2273 outer_graph->SetHasLoops(true);
2274 }
2275 if (HasIrreducibleLoops()) {
2276 outer_graph->SetHasIrreducibleLoops(true);
2277 }
2278 if (HasTryCatch()) {
2279 outer_graph->SetHasTryCatch(true);
2280 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002281 if (HasSIMD()) {
2282 outer_graph->SetHasSIMD(true);
2283 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002284
Calin Juravle2e768302015-07-28 14:41:11 +00002285 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002286 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002287 // Inliner already made sure we don't inline methods that always throw.
2288 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002289 // Simple case of an entry block, a body block, and an exit block.
2290 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002291 HBasicBlock* body = GetBlocks()[1];
2292 DCHECK(GetBlocks()[0]->IsEntryBlock());
2293 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002294 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002295 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002296 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002297
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002298 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2299 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002300 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002301
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002302 // Replace the invoke with the return value of the inlined graph.
2303 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002304 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002305 } else {
2306 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002307 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002308
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002309 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002310 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002311 // Need to inline multiple blocks. We split `invoke`'s block
2312 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002313 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002314 // with the second half.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002315 ArenaAllocator* allocator = outer_graph->GetAllocator();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002316 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002317 // Note that we split before the invoke only to simplify polymorphic inlining.
2318 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002319
Vladimir Markoec7802a2015-10-01 20:57:57 +01002320 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002321 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002322 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002323 exit_block_->ReplaceWith(to);
2324
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002325 // Update the meta information surrounding blocks:
2326 // (1) the graph they are now in,
2327 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002328 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002329 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002330 // Note that we do not need to update catch phi inputs because they
2331 // correspond to the register file of the outer method which the inlinee
2332 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002333
2334 // We don't add the entry block, the exit block, and the first block, which
2335 // has been merged with `at`.
2336 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2337
2338 // We add the `to` block.
2339 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002340 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002341 + kNumberOfNewBlocksInCaller;
2342
2343 // Find the location of `at` in the outer graph's reverse post order. The new
2344 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002345 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002346 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2347
David Brazdil95177982015-10-30 12:56:58 -05002348 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2349 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002350 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002351 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002352 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002353 DCHECK(current->GetGraph() == this);
2354 current->SetGraph(outer_graph);
2355 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002356 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002357 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002358 }
2359 }
2360
David Brazdil95177982015-10-30 12:56:58 -05002361 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002362 to->SetGraph(outer_graph);
2363 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002364 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002365 // Only `to` can become a back edge, as the inlined blocks
2366 // are predecessors of `to`.
2367 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002368
David Brazdil3f523062016-02-29 16:53:33 +00002369 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002370 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2371 // to now get the outer graph exit block as successor. Note that the inliner
2372 // currently doesn't support inlining methods with try/catch.
2373 HPhi* return_value_phi = nullptr;
2374 bool rerun_dominance = false;
2375 bool rerun_loop_analysis = false;
2376 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2377 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002378 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002379 if (last->IsThrow()) {
2380 DCHECK(!at->IsTryBlock());
2381 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2382 --pred;
2383 // We need to re-run dominance information, as the exit block now has
2384 // a new dominator.
2385 rerun_dominance = true;
2386 if (predecessor->GetLoopInformation() != nullptr) {
2387 // The exit block and blocks post dominated by the exit block do not belong
2388 // to any loop. Because we do not compute the post dominators, we need to re-run
2389 // loop analysis to get the loop information correct.
2390 rerun_loop_analysis = true;
2391 }
2392 } else {
2393 if (last->IsReturnVoid()) {
2394 DCHECK(return_value == nullptr);
2395 DCHECK(return_value_phi == nullptr);
2396 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002397 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002398 if (return_value_phi != nullptr) {
2399 return_value_phi->AddInput(last->InputAt(0));
2400 } else if (return_value == nullptr) {
2401 return_value = last->InputAt(0);
2402 } else {
2403 // There will be multiple returns.
2404 return_value_phi = new (allocator) HPhi(
2405 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2406 to->AddPhi(return_value_phi);
2407 return_value_phi->AddInput(return_value);
2408 return_value_phi->AddInput(last->InputAt(0));
2409 return_value = return_value_phi;
2410 }
David Brazdil3f523062016-02-29 16:53:33 +00002411 }
2412 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2413 predecessor->RemoveInstruction(last);
2414 }
2415 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002416 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002417 DCHECK(!outer_graph->HasIrreducibleLoops())
2418 << "Recomputing loop information in graphs with irreducible loops "
2419 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002420 outer_graph->ClearLoopInformation();
2421 outer_graph->ClearDominanceInformation();
2422 outer_graph->BuildDominatorTree();
2423 } else if (rerun_dominance) {
2424 outer_graph->ClearDominanceInformation();
2425 outer_graph->ComputeDominanceInformation();
2426 }
David Brazdil3f523062016-02-29 16:53:33 +00002427 }
David Brazdil05144f42015-04-16 15:18:00 +01002428
2429 // Walk over the entry block and:
2430 // - Move constants from the entry block to the outer_graph's entry block,
2431 // - Replace HParameterValue instructions with their real value.
2432 // - Remove suspend checks, that hold an environment.
2433 // We must do this after the other blocks have been inlined, otherwise ids of
2434 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002435 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002436 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2437 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002438 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002439 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002440 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002441 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002442 replacement = outer_graph->GetIntConstant(
2443 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002444 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002445 replacement = outer_graph->GetLongConstant(
2446 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002447 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002448 replacement = outer_graph->GetFloatConstant(
2449 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002450 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002451 replacement = outer_graph->GetDoubleConstant(
2452 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002453 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002454 if (kIsDebugBuild
2455 && invoke->IsInvokeStaticOrDirect()
2456 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2457 // Ensure we do not use the last input of `invoke`, as it
2458 // contains a clinit check which is not an actual argument.
2459 size_t last_input_index = invoke->InputCount() - 1;
2460 DCHECK(parameter_index != last_input_index);
2461 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002462 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002463 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002464 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002465 } else {
2466 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2467 entry_block_->RemoveInstruction(current);
2468 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002469 if (replacement != nullptr) {
2470 current->ReplaceWith(replacement);
2471 // If the current is the return value then we need to update the latter.
2472 if (current == return_value) {
2473 DCHECK_EQ(entry_block_, return_value->GetBlock());
2474 return_value = replacement;
2475 }
2476 }
2477 }
2478
Calin Juravle2e768302015-07-28 14:41:11 +00002479 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002480}
2481
Mingyao Yang3584bce2015-05-19 16:01:59 -07002482/*
2483 * Loop will be transformed to:
2484 * old_pre_header
2485 * |
2486 * if_block
2487 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002488 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002489 * \ /
2490 * new_pre_header
2491 * |
2492 * header
2493 */
2494void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2495 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002496 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002497
Aart Bik3fc7f352015-11-20 22:03:03 -08002498 // Need extra block to avoid critical edge.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002499 HBasicBlock* if_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2500 HBasicBlock* true_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2501 HBasicBlock* false_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2502 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002503 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002504 AddBlock(true_block);
2505 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002506 AddBlock(new_pre_header);
2507
Aart Bik3fc7f352015-11-20 22:03:03 -08002508 header->ReplacePredecessor(old_pre_header, new_pre_header);
2509 old_pre_header->successors_.clear();
2510 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002511
Aart Bik3fc7f352015-11-20 22:03:03 -08002512 old_pre_header->AddSuccessor(if_block);
2513 if_block->AddSuccessor(true_block); // True successor
2514 if_block->AddSuccessor(false_block); // False successor
2515 true_block->AddSuccessor(new_pre_header);
2516 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002517
Aart Bik3fc7f352015-11-20 22:03:03 -08002518 old_pre_header->dominated_blocks_.push_back(if_block);
2519 if_block->SetDominator(old_pre_header);
2520 if_block->dominated_blocks_.push_back(true_block);
2521 true_block->SetDominator(if_block);
2522 if_block->dominated_blocks_.push_back(false_block);
2523 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002524 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002525 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002526 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002527 header->SetDominator(new_pre_header);
2528
Aart Bik3fc7f352015-11-20 22:03:03 -08002529 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002530 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002531 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002532 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002533 reverse_post_order_[index_of_header++] = true_block;
2534 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002535 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002536
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002537 // The pre_header can never be a back edge of a loop.
2538 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2539 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2540 UpdateLoopAndTryInformationOfNewBlock(
2541 if_block, old_pre_header, /* replace_if_back_edge */ false);
2542 UpdateLoopAndTryInformationOfNewBlock(
2543 true_block, old_pre_header, /* replace_if_back_edge */ false);
2544 UpdateLoopAndTryInformationOfNewBlock(
2545 false_block, old_pre_header, /* replace_if_back_edge */ false);
2546 UpdateLoopAndTryInformationOfNewBlock(
2547 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002548}
2549
Aart Bikf8f5a162017-02-06 15:35:29 -08002550HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2551 HBasicBlock* body,
2552 HBasicBlock* exit) {
2553 DCHECK(header->IsLoopHeader());
2554 HLoopInformation* loop = header->GetLoopInformation();
2555
2556 // Add new loop blocks.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002557 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2558 HBasicBlock* new_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2559 HBasicBlock* new_body = new (allocator_) HBasicBlock(this, header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002560 AddBlock(new_pre_header);
2561 AddBlock(new_header);
2562 AddBlock(new_body);
2563
2564 // Set up control flow.
2565 header->ReplaceSuccessor(exit, new_pre_header);
2566 new_pre_header->AddSuccessor(new_header);
2567 new_header->AddSuccessor(exit);
2568 new_header->AddSuccessor(new_body);
2569 new_body->AddSuccessor(new_header);
2570
2571 // Set up dominators.
2572 header->ReplaceDominatedBlock(exit, new_pre_header);
2573 new_pre_header->SetDominator(header);
2574 new_pre_header->dominated_blocks_.push_back(new_header);
2575 new_header->SetDominator(new_pre_header);
2576 new_header->dominated_blocks_.push_back(new_body);
2577 new_body->SetDominator(new_header);
2578 new_header->dominated_blocks_.push_back(exit);
2579 exit->SetDominator(new_header);
2580
2581 // Fix reverse post order.
2582 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2583 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2584 reverse_post_order_[++index_of_header] = new_pre_header;
2585 reverse_post_order_[++index_of_header] = new_header;
2586 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2587 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2588 reverse_post_order_[index_of_body] = new_body;
2589
Aart Bikb07d1bc2017-04-05 10:03:15 -07002590 // Add gotos and suspend check (client must add conditional in header).
Vladimir Markoca6fff82017-10-03 14:49:14 +01002591 new_pre_header->AddInstruction(new (allocator_) HGoto());
2592 HSuspendCheck* suspend_check = new (allocator_) HSuspendCheck(header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002593 new_header->AddInstruction(suspend_check);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002594 new_body->AddInstruction(new (allocator_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002595 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2596 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002597
2598 // Update loop information.
2599 new_header->AddBackEdge(new_body);
2600 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2601 new_header->GetLoopInformation()->Populate();
2602 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2603 HLoopInformationOutwardIterator it(*new_header);
2604 for (it.Advance(); !it.Done(); it.Advance()) {
2605 it.Current()->Add(new_pre_header);
2606 it.Current()->Add(new_header);
2607 it.Current()->Add(new_body);
2608 }
2609 return new_pre_header;
2610}
2611
David Brazdilf5552582015-12-27 13:36:12 +00002612static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002613 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002614 if (rti.IsValid()) {
2615 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2616 << " upper_bound_rti: " << upper_bound_rti
2617 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002618 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2619 << " upper_bound_rti: " << upper_bound_rti
2620 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002621 }
2622}
2623
Calin Juravle2e768302015-07-28 14:41:11 +00002624void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2625 if (kIsDebugBuild) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002626 DCHECK_EQ(GetType(), DataType::Type::kReference);
Calin Juravle2e768302015-07-28 14:41:11 +00002627 ScopedObjectAccess soa(Thread::Current());
2628 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2629 if (IsBoundType()) {
2630 // Having the test here spares us from making the method virtual just for
2631 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002632 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002633 }
2634 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002635 reference_type_handle_ = rti.GetTypeHandle();
2636 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002637}
2638
David Brazdilf5552582015-12-27 13:36:12 +00002639void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2640 if (kIsDebugBuild) {
2641 ScopedObjectAccess soa(Thread::Current());
2642 DCHECK(upper_bound.IsValid());
2643 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2644 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2645 }
2646 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002647 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002648}
2649
Vladimir Markoa1de9182016-02-25 11:37:38 +00002650ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002651 if (kIsDebugBuild) {
2652 ScopedObjectAccess soa(Thread::Current());
2653 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002654 if (!is_exact) {
2655 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2656 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2657 }
Calin Juravle2e768302015-07-28 14:41:11 +00002658 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002659 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002660}
2661
Calin Juravleacf735c2015-02-12 15:25:22 +00002662std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2663 ScopedObjectAccess soa(Thread::Current());
2664 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002665 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002666 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002667 << " is_exact=" << rhs.IsExact()
2668 << " ]";
2669 return os;
2670}
2671
Mark Mendellc4701932015-04-10 13:18:51 -04002672bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2673 // For now, assume that instructions in different blocks may use the
2674 // environment.
2675 // TODO: Use the control flow to decide if this is true.
2676 if (GetBlock() != other->GetBlock()) {
2677 return true;
2678 }
2679
2680 // We know that we are in the same block. Walk from 'this' to 'other',
2681 // checking to see if there is any instruction with an environment.
2682 HInstruction* current = this;
2683 for (; current != other && current != nullptr; current = current->GetNext()) {
2684 // This is a conservative check, as the instruction result may not be in
2685 // the referenced environment.
2686 if (current->HasEnvironment()) {
2687 return true;
2688 }
2689 }
2690
2691 // We should have been called with 'this' before 'other' in the block.
2692 // Just confirm this.
2693 DCHECK(current != nullptr);
2694 return false;
2695}
2696
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002697void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002698 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2699 IntrinsicSideEffects side_effects,
2700 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002701 intrinsic_ = intrinsic;
2702 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002703
Aart Bik5d75afe2015-12-14 11:57:01 -08002704 // Adjust method's side effects from intrinsic table.
2705 switch (side_effects) {
2706 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2707 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2708 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2709 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2710 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002711
2712 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2713 opt.SetDoesNotNeedDexCache();
2714 opt.SetDoesNotNeedEnvironment();
2715 } else {
2716 // If we need an environment, that means there will be a call, which can trigger GC.
2717 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2718 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002719 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002720 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002721}
2722
David Brazdil6de19382016-01-08 17:37:10 +00002723bool HNewInstance::IsStringAlloc() const {
2724 ScopedObjectAccess soa(Thread::Current());
2725 return GetReferenceTypeInfo().IsStringClass();
2726}
2727
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002728bool HInvoke::NeedsEnvironment() const {
2729 if (!IsIntrinsic()) {
2730 return true;
2731 }
2732 IntrinsicOptimizations opt(*this);
2733 return !opt.GetDoesNotNeedEnvironment();
2734}
2735
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002736const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2737 ArtMethod* caller = GetEnvironment()->GetMethod();
2738 ScopedObjectAccess soa(Thread::Current());
2739 // `caller` is null for a top-level graph representing a method whose declaring
2740 // class was not resolved.
2741 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2742}
2743
Vladimir Markodc151b22015-10-15 18:02:30 +01002744bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002745 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002746 return false;
2747 }
2748 if (!IsIntrinsic()) {
2749 return true;
2750 }
2751 IntrinsicOptimizations opt(*this);
2752 return !opt.GetDoesNotNeedDexCache();
2753}
2754
Vladimir Markof64242a2015-12-01 14:58:23 +00002755std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2756 switch (rhs) {
2757 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002758 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002759 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002760 return os << "Recursive";
2761 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2762 return os << "BootImageLinkTimePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002763 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
Vladimir Marko19d7d502017-05-24 13:04:14 +01002764 return os << "DirectAddress";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002765 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2766 return os << "BssEntry";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002767 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2768 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002769 default:
2770 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2771 UNREACHABLE();
2772 }
2773}
2774
Vladimir Markofbb184a2015-11-13 14:47:00 +00002775std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2776 switch (rhs) {
2777 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2778 return os << "explicit";
2779 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2780 return os << "implicit";
2781 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2782 return os << "none";
2783 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002784 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2785 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002786 }
2787}
2788
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002789bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2790 const HLoadClass* other_load_class = other->AsLoadClass();
2791 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2792 // names rather than type indexes. However, we shall also have to re-think the hash code.
2793 if (type_index_ != other_load_class->type_index_ ||
2794 GetPackedFields() != other_load_class->GetPackedFields()) {
2795 return false;
2796 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002797 switch (GetLoadKind()) {
2798 case LoadKind::kBootImageAddress:
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002799 case LoadKind::kBootImageClassTable:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002800 case LoadKind::kJitTableAddress: {
2801 ScopedObjectAccess soa(Thread::Current());
2802 return GetClass().Get() == other_load_class->GetClass().Get();
2803 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002804 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002805 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002806 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002807 }
2808}
2809
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002810void HLoadClass::SetLoadKind(LoadKind load_kind) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002811 SetPackedField<LoadKindField>(load_kind);
2812
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002813 if (load_kind != LoadKind::kRuntimeCall &&
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002814 load_kind != LoadKind::kReferrersClass) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002815 RemoveAsUserOfInput(0u);
2816 SetRawInputAt(0u, nullptr);
2817 }
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002818
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002819 if (!NeedsEnvironment()) {
2820 RemoveEnvironment();
2821 SetSideEffects(SideEffects::None());
2822 }
2823}
2824
2825std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2826 switch (rhs) {
2827 case HLoadClass::LoadKind::kReferrersClass:
2828 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002829 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2830 return os << "BootImageLinkTimePcRelative";
2831 case HLoadClass::LoadKind::kBootImageAddress:
2832 return os << "BootImageAddress";
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002833 case HLoadClass::LoadKind::kBootImageClassTable:
2834 return os << "BootImageClassTable";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002835 case HLoadClass::LoadKind::kBssEntry:
2836 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002837 case HLoadClass::LoadKind::kJitTableAddress:
2838 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002839 case HLoadClass::LoadKind::kRuntimeCall:
2840 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002841 default:
2842 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2843 UNREACHABLE();
2844 }
2845}
2846
Vladimir Marko372f10e2016-05-17 16:30:10 +01002847bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2848 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002849 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2850 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002851 if (string_index_ != other_load_string->string_index_ ||
2852 GetPackedFields() != other_load_string->GetPackedFields()) {
2853 return false;
2854 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002855 switch (GetLoadKind()) {
2856 case LoadKind::kBootImageAddress:
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002857 case LoadKind::kBootImageInternTable:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002858 case LoadKind::kJitTableAddress: {
2859 ScopedObjectAccess soa(Thread::Current());
2860 return GetString().Get() == other_load_string->GetString().Get();
2861 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002862 default:
2863 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002864 }
2865}
2866
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002867void HLoadString::SetLoadKind(LoadKind load_kind) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002868 // Once sharpened, the load kind should not be changed again.
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002869 DCHECK_EQ(GetLoadKind(), LoadKind::kRuntimeCall);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002870 SetPackedField<LoadKindField>(load_kind);
2871
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002872 if (load_kind != LoadKind::kRuntimeCall) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002873 RemoveAsUserOfInput(0u);
2874 SetRawInputAt(0u, nullptr);
2875 }
2876 if (!NeedsEnvironment()) {
2877 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002878 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002879 }
2880}
2881
2882std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2883 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002884 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2885 return os << "BootImageLinkTimePcRelative";
2886 case HLoadString::LoadKind::kBootImageAddress:
2887 return os << "BootImageAddress";
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002888 case HLoadString::LoadKind::kBootImageInternTable:
2889 return os << "BootImageInternTable";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002890 case HLoadString::LoadKind::kBssEntry:
2891 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002892 case HLoadString::LoadKind::kJitTableAddress:
2893 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002894 case HLoadString::LoadKind::kRuntimeCall:
2895 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002896 default:
2897 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2898 UNREACHABLE();
2899 }
2900}
2901
Mark Mendellc4701932015-04-10 13:18:51 -04002902void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002903 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2904 HEnvironment* user = use.GetUser();
2905 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002906 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002907 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002908}
2909
Roland Levillainc9b21f82016-03-23 16:36:59 +00002910// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002911HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01002912 ArenaAllocator* allocator = GetAllocator();
Mark Mendellf6529172015-11-17 11:16:56 -05002913
2914 if (cond->IsCondition() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002915 !DataType::IsFloatingPointType(cond->InputAt(0)->GetType())) {
Mark Mendellf6529172015-11-17 11:16:56 -05002916 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2917 HInstruction* lhs = cond->InputAt(0);
2918 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002919 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002920 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2921 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2922 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2923 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2924 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2925 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2926 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2927 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2928 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2929 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2930 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002931 default:
2932 LOG(FATAL) << "Unexpected condition";
2933 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002934 }
2935 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2936 return replacement;
2937 } else if (cond->IsIntConstant()) {
2938 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002939 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002940 return GetIntConstant(1);
2941 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002942 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002943 return GetIntConstant(0);
2944 }
2945 } else {
2946 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2947 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2948 return replacement;
2949 }
2950}
2951
Roland Levillainc9285912015-12-18 10:38:42 +00002952std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2953 os << "["
2954 << " source=" << rhs.GetSource()
2955 << " destination=" << rhs.GetDestination()
2956 << " type=" << rhs.GetType()
2957 << " instruction=";
2958 if (rhs.GetInstruction() != nullptr) {
2959 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2960 } else {
2961 os << "null";
2962 }
2963 os << " ]";
2964 return os;
2965}
2966
Roland Levillain86503782016-02-11 19:07:30 +00002967std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2968 switch (rhs) {
2969 case TypeCheckKind::kUnresolvedCheck:
2970 return os << "unresolved_check";
2971 case TypeCheckKind::kExactCheck:
2972 return os << "exact_check";
2973 case TypeCheckKind::kClassHierarchyCheck:
2974 return os << "class_hierarchy_check";
2975 case TypeCheckKind::kAbstractClassCheck:
2976 return os << "abstract_class_check";
2977 case TypeCheckKind::kInterfaceCheck:
2978 return os << "interface_check";
2979 case TypeCheckKind::kArrayObjectCheck:
2980 return os << "array_object_check";
2981 case TypeCheckKind::kArrayCheck:
2982 return os << "array_check";
2983 default:
2984 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2985 UNREACHABLE();
2986 }
2987}
2988
Andreas Gampe26de38b2016-07-27 17:53:11 -07002989std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2990 switch (kind) {
2991 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002992 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002993 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002994 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002995 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002996 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002997 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002998 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002999 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003000 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003001
3002 default:
3003 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
3004 UNREACHABLE();
3005 }
3006}
3007
Nicolas Geoffray818f2102014-02-18 16:43:35 +00003008} // namespace art