blob: 50cedd2502ac5b988e34b301379670874289c7e7 [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"
Andreas Gampe85f1c572018-11-21 13:52:48 -080023#include "base/logging.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070024#include "base/stl_util.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080025#include "class_linker-inl.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010026#include "class_root-inl.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040027#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000028#include "common_dominator.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010029#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010030#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070031#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070032#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000033
Vladimir Marko0a516052019-10-14 13:00:44 +000034namespace art {
Nicolas Geoffray818f2102014-02-18 16:43:35 +000035
Roland Levillain31dd3d62016-02-16 12:21:02 +000036// Enable floating-point static evaluation during constant folding
37// only if all floating-point operations and constants evaluate in the
38// range and precision of the type used (i.e., 32-bit float, 64-bit
39// double).
40static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
41
Vladimir Marko02ca05a2020-05-12 13:58:51 +010042ReferenceTypeInfo::TypeHandle HandleCache::CreateRootHandle(VariableSizedHandleScope* handles,
43 ClassRoot class_root) {
44 // Mutator lock is required for NewHandle and GetClassRoot().
David Brazdilbadd8262016-02-02 16:28:56 +000045 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko02ca05a2020-05-12 13:58:51 +010046 return handles->NewHandle(GetClassRoot(class_root));
David Brazdilbadd8262016-02-02 16:28:56 +000047}
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(
Andreas Gampe3db70682018-12-26 15:12:03 -080062 &allocator, blocks_.size(), /* expandable= */ false, kArenaAllocGraphBuilder);
Vladimir Marko69d310e2017-10-09 14:12:23 +010063 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 Geoffray2cc9d342019-04-26 14:21:14 +0100149 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
150 RemoveAsUser(it.Current());
151 }
Roland Levillainfc600dc2014-12-02 17:16:31 +0000152 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
153 RemoveAsUser(it.Current());
154 }
155 }
156 }
157}
158
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100159void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100160 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000161 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100162 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000163 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100164 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000165 for (HBasicBlock* successor : block->GetSuccessors()) {
166 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000167 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100168 // Remove the block from the list of blocks, so that further analyses
169 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100170 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600171 if (block->IsExitBlock()) {
172 SetExitBlock(nullptr);
173 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000174 // Mark the block as removed. This is used by the HGraphBuilder to discard
175 // the block as a branch target.
176 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000177 }
178 }
179}
180
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000181GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Marko69d310e2017-10-09 14:12:23 +0100182 // Allocate memory from local ScopedArenaAllocator.
183 ScopedArenaAllocator allocator(GetArenaStack());
184
185 ArenaBitVector visited(&allocator, blocks_.size(), false, kArenaAllocGraphBuilder);
186 visited.ClearAllBits();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000187
David Brazdil86ea7ee2016-02-16 09:26:07 +0000188 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000189 FindBackEdges(&visited);
190
David Brazdil86ea7ee2016-02-16 09:26:07 +0000191 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000192 // the initial DFS as users from other instructions, so that
193 // users can be safely removed before uses later.
194 RemoveInstructionsAsUsersFromDeadBlocks(visited);
195
David Brazdil86ea7ee2016-02-16 09:26:07 +0000196 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000197 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000198 // predecessors list of live blocks.
199 RemoveDeadBlocks(visited);
200
David Brazdil86ea7ee2016-02-16 09:26:07 +0000201 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100202 // dominators and the reverse post order.
203 SimplifyCFG();
204
David Brazdil86ea7ee2016-02-16 09:26:07 +0000205 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100206 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000207
David Brazdil86ea7ee2016-02-16 09:26:07 +0000208 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000209 // set the loop information on each block.
210 GraphAnalysisResult result = AnalyzeLoops();
211 if (result != kAnalysisSuccess) {
212 return result;
213 }
214
David Brazdil86ea7ee2016-02-16 09:26:07 +0000215 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000216 // which needs the information to build catch block phis from values of
217 // locals at throwing instructions inside try blocks.
218 ComputeTryBlockInformation();
219
220 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100221}
222
223void HGraph::ClearDominanceInformation() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100224 for (HBasicBlock* block : GetReversePostOrder()) {
225 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100226 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100227 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100228}
229
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000230void HGraph::ClearLoopInformation() {
231 SetHasIrreducibleLoops(false);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100232 for (HBasicBlock* block : GetReversePostOrder()) {
233 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000234 }
235}
236
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100237void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000238 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100239 dominator_ = nullptr;
240}
241
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000242HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
243 HInstruction* instruction = GetFirstInstruction();
244 while (instruction->IsParallelMove()) {
245 instruction = instruction->GetNext();
246 }
247 return instruction;
248}
249
David Brazdil3f4a5222016-05-06 12:46:21 +0100250static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
251 DCHECK(ContainsElement(block->GetSuccessors(), successor));
252
253 HBasicBlock* old_dominator = successor->GetDominator();
254 HBasicBlock* new_dominator =
255 (old_dominator == nullptr) ? block
256 : CommonDominator::ForPair(old_dominator, block);
257
258 if (old_dominator == new_dominator) {
259 return false;
260 } else {
261 successor->SetDominator(new_dominator);
262 return true;
263 }
264}
265
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100266void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100267 DCHECK(reverse_post_order_.empty());
268 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100269 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100270
Vladimir Marko69d310e2017-10-09 14:12:23 +0100271 // Allocate memory from local ScopedArenaAllocator.
272 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Markod76d1392015-09-23 16:07:14 +0100273 // Number of visits of a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100274 ScopedArenaVector<size_t> visits(blocks_.size(), 0u, allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100275 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100276 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
277 0u,
278 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100279 // Nodes for which we need to visit successors.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100280 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100281 constexpr size_t kDefaultWorklistSize = 8;
282 worklist.reserve(kDefaultWorklistSize);
283 worklist.push_back(entry_block_);
284
285 while (!worklist.empty()) {
286 HBasicBlock* current = worklist.back();
287 uint32_t current_id = current->GetBlockId();
288 if (successors_visited[current_id] == current->GetSuccessors().size()) {
289 worklist.pop_back();
290 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100291 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100292 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100293
294 // Once all the forward edges have been visited, we know the immediate
295 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100296 if (++visits[successor->GetBlockId()] ==
297 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100298 reverse_post_order_.push_back(successor);
299 worklist.push_back(successor);
300 }
301 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000302 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000303
David Brazdil3f4a5222016-05-06 12:46:21 +0100304 // Check if the graph has back edges not dominated by their respective headers.
305 // If so, we need to update the dominators of those headers and recursively of
306 // their successors. We do that with a fix-point iteration over all blocks.
307 // The algorithm is guaranteed to terminate because it loops only if the sum
308 // of all dominator chains has decreased in the current iteration.
309 bool must_run_fix_point = false;
310 for (HBasicBlock* block : blocks_) {
311 if (block != nullptr &&
312 block->IsLoopHeader() &&
313 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
314 must_run_fix_point = true;
315 break;
316 }
317 }
318 if (must_run_fix_point) {
319 bool update_occurred = true;
320 while (update_occurred) {
321 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100322 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100323 for (HBasicBlock* successor : block->GetSuccessors()) {
324 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
325 }
326 }
327 }
328 }
329
330 // Make sure that there are no remaining blocks whose dominator information
331 // needs to be updated.
332 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100333 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100334 for (HBasicBlock* successor : block->GetSuccessors()) {
335 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
336 }
337 }
338 }
339
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000340 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000341 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100342 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000343 if (!block->IsEntryBlock()) {
344 block->GetDominator()->AddDominatedBlock(block);
345 }
346 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000347}
348
David Brazdilfc6a86a2015-06-26 10:33:45 +0000349HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100350 HBasicBlock* new_block = new (allocator_) HBasicBlock(this, successor->GetDexPc());
David Brazdil3e187382015-06-26 09:59:52 +0000351 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000352 // Use `InsertBetween` to ensure the predecessor index and successor index of
353 // `block` and `successor` are preserved.
354 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000355 return new_block;
356}
357
358void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
359 // Insert a new node between `block` and `successor` to split the
360 // critical edge.
361 HBasicBlock* new_block = SplitEdge(block, successor);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100362 new_block->AddInstruction(new (allocator_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100363 if (successor->IsLoopHeader()) {
364 // If we split at a back edge boundary, make the new block the back edge.
365 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000366 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100367 info->RemoveBackEdge(block);
368 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100369 }
370 }
371}
372
Artem Serovc73ee372017-07-31 15:08:40 +0100373// Reorder phi inputs to match reordering of the block's predecessors.
374static void FixPhisAfterPredecessorsReodering(HBasicBlock* block, size_t first, size_t second) {
375 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
376 HPhi* phi = it.Current()->AsPhi();
377 HInstruction* first_instr = phi->InputAt(first);
378 HInstruction* second_instr = phi->InputAt(second);
379 phi->ReplaceInput(first_instr, second);
380 phi->ReplaceInput(second_instr, first);
381 }
382}
383
384// Make sure that the first predecessor of a loop header is the incoming block.
385void HGraph::OrderLoopHeaderPredecessors(HBasicBlock* header) {
386 DCHECK(header->IsLoopHeader());
387 HLoopInformation* info = header->GetLoopInformation();
388 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
389 HBasicBlock* to_swap = header->GetPredecessors()[0];
390 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
391 HBasicBlock* predecessor = header->GetPredecessors()[pred];
392 if (!info->IsBackEdge(*predecessor)) {
393 header->predecessors_[pred] = to_swap;
394 header->predecessors_[0] = predecessor;
395 FixPhisAfterPredecessorsReodering(header, 0, pred);
396 break;
397 }
398 }
399 }
400}
401
Artem Serov09faaea2017-12-07 14:36:01 +0000402// Transform control flow of the loop to a single preheader format (don't touch the data flow).
403// New_preheader can be already among the header predecessors - this situation will be correctly
404// processed.
405static void FixControlForNewSinglePreheader(HBasicBlock* header, HBasicBlock* new_preheader) {
406 HLoopInformation* loop_info = header->GetLoopInformation();
407 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
408 HBasicBlock* predecessor = header->GetPredecessors()[pred];
409 if (!loop_info->IsBackEdge(*predecessor) && predecessor != new_preheader) {
410 predecessor->ReplaceSuccessor(header, new_preheader);
411 pred--;
412 }
413 }
414}
415
416// == Before == == After ==
417// _________ _________ _________ _________
418// | B0 | | B1 | (old preheaders) | B0 | | B1 |
419// |=========| |=========| |=========| |=========|
420// | i0 = .. | | i1 = .. | | i0 = .. | | i1 = .. |
421// |_________| |_________| |_________| |_________|
422// \ / \ /
423// \ / ___v____________v___
424// \ / (new preheader) | B20 <- B0, B1 |
425// | | |====================|
426// | | | i20 = phi(i0, i1) |
427// | | |____________________|
428// | | |
429// /\ | | /\ /\ | /\
430// / v_______v_________v_______v \ / v___________v_____________v \
431// | | B10 <- B0, B1, B2, B3 | | | | B10 <- B20, B2, B3 | |
432// | |===========================| | (header) | |===========================| |
433// | | i10 = phi(i0, i1, i2, i3) | | | | i10 = phi(i20, i2, i3) | |
434// | |___________________________| | | |___________________________| |
435// | / \ | | / \ |
436// | ... ... | | ... ... |
437// | _________ _________ | | _________ _________ |
438// | | B2 | | B3 | | | | B2 | | B3 | |
439// | |=========| |=========| | (back edges) | |=========| |=========| |
440// | | i2 = .. | | i3 = .. | | | | i2 = .. | | i3 = .. | |
441// | |_________| |_________| | | |_________| |_________| |
442// \ / \ / \ / \ /
443// \___/ \___/ \___/ \___/
444//
445void HGraph::TransformLoopToSinglePreheaderFormat(HBasicBlock* header) {
446 HLoopInformation* loop_info = header->GetLoopInformation();
447
448 HBasicBlock* preheader = new (allocator_) HBasicBlock(this, header->GetDexPc());
449 AddBlock(preheader);
450 preheader->AddInstruction(new (allocator_) HGoto(header->GetDexPc()));
451
452 // If the old header has no Phis then we only need to fix the control flow.
453 if (header->GetPhis().IsEmpty()) {
454 FixControlForNewSinglePreheader(header, preheader);
455 preheader->AddSuccessor(header);
456 return;
457 }
458
459 // Find the first non-back edge block in the header's predecessors list.
460 size_t first_nonbackedge_pred_pos = 0;
461 bool found = false;
462 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
463 HBasicBlock* predecessor = header->GetPredecessors()[pred];
464 if (!loop_info->IsBackEdge(*predecessor)) {
465 first_nonbackedge_pred_pos = pred;
466 found = true;
467 break;
468 }
469 }
470
471 DCHECK(found);
472
473 // Fix the data-flow.
474 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
475 HPhi* header_phi = it.Current()->AsPhi();
476
477 HPhi* preheader_phi = new (GetAllocator()) HPhi(GetAllocator(),
478 header_phi->GetRegNumber(),
479 0,
480 header_phi->GetType());
481 if (header_phi->GetType() == DataType::Type::kReference) {
482 preheader_phi->SetReferenceTypeInfo(header_phi->GetReferenceTypeInfo());
483 }
484 preheader->AddPhi(preheader_phi);
485
486 HInstruction* orig_input = header_phi->InputAt(first_nonbackedge_pred_pos);
487 header_phi->ReplaceInput(preheader_phi, first_nonbackedge_pred_pos);
488 preheader_phi->AddInput(orig_input);
489
490 for (size_t input_pos = first_nonbackedge_pred_pos + 1;
491 input_pos < header_phi->InputCount();
492 input_pos++) {
493 HInstruction* input = header_phi->InputAt(input_pos);
494 HBasicBlock* pred_block = header->GetPredecessors()[input_pos];
495
496 if (loop_info->Contains(*pred_block)) {
497 DCHECK(loop_info->IsBackEdge(*pred_block));
498 } else {
499 preheader_phi->AddInput(input);
500 header_phi->RemoveInputAt(input_pos);
501 input_pos--;
502 }
503 }
504 }
505
506 // Fix the control-flow.
507 HBasicBlock* first_pred = header->GetPredecessors()[first_nonbackedge_pred_pos];
508 preheader->InsertBetween(first_pred, header);
509
510 FixControlForNewSinglePreheader(header, preheader);
511}
512
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100513void HGraph::SimplifyLoop(HBasicBlock* header) {
514 HLoopInformation* info = header->GetLoopInformation();
515
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100516 // Make sure the loop has only one pre header. This simplifies SSA building by having
517 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000518 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
519 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000520 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000521 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Artem Serov09faaea2017-12-07 14:36:01 +0000522 TransformLoopToSinglePreheaderFormat(header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100523 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100524
Artem Serovc73ee372017-07-31 15:08:40 +0100525 OrderLoopHeaderPredecessors(header);
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100526
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100527 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000528 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
529 // Called from DeadBlockElimination. Update SuspendCheck pointer.
530 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100531 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100532}
533
David Brazdilffee3d32015-07-06 11:48:53 +0100534void HGraph::ComputeTryBlockInformation() {
535 // Iterate in reverse post order to propagate try membership information from
536 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100537 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100538 if (block->IsEntryBlock() || block->IsCatchBlock()) {
539 // Catch blocks after simplification have only exceptional predecessors
540 // and hence are never in tries.
541 continue;
542 }
543
544 // Infer try membership from the first predecessor. Having simplified loops,
545 // the first predecessor can never be a back edge and therefore it must have
546 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100547 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100548 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100549 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000550 if (try_entry != nullptr &&
551 (block->GetTryCatchInformation() == nullptr ||
552 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
553 // We are either setting try block membership for the first time or it
554 // has changed.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100555 block->SetTryCatchInformation(new (allocator_) TryCatchInformation(*try_entry));
David Brazdilec16f792015-08-19 15:04:01 +0100556 }
David Brazdilffee3d32015-07-06 11:48:53 +0100557 }
558}
559
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100560void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000561// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100562 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000563 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100564 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
565 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
566 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
567 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100568 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000569 if (block->GetSuccessors().size() > 1) {
570 // Only split normal-flow edges. We cannot split exceptional edges as they
571 // are synthesized (approximate real control flow), and we do not need to
572 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000573 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
574 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
575 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100576 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000577 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000578 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
579 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000580 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000581 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100582 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000583 // SplitCriticalEdge could have invalidated the `normal_successors`
584 // ArrayRef. We must re-acquire it.
585 normal_successors = block->GetNormalSuccessors();
586 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
587 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100588 }
589 }
590 }
591 if (block->IsLoopHeader()) {
592 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000593 } else if (!block->IsEntryBlock() &&
594 block->GetFirstInstruction() != nullptr &&
595 block->GetFirstInstruction()->IsSuspendCheck()) {
596 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000597 // a loop got dismantled. Just remove the suspend check.
598 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100599 }
600 }
601}
602
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000603GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100604 // We iterate post order to ensure we visit inner loops before outer loops.
605 // `PopulateRecursive` needs this guarantee to know whether a natural loop
606 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100607 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100608 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100609 if (block->IsCatchBlock()) {
610 // TODO: Dealing with exceptional back edges could be tricky because
611 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffraydbb9aef2017-11-23 10:44:11 +0000612 VLOG(compiler) << "Not compiled: Exceptional back edges";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000613 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100614 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000615 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100616 }
617 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000618 return kAnalysisSuccess;
619}
620
621void HLoopInformation::Dump(std::ostream& os) {
622 os << "header: " << header_->GetBlockId() << std::endl;
623 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
624 for (HBasicBlock* block : back_edges_) {
625 os << "back edge: " << block->GetBlockId() << std::endl;
626 }
627 for (HBasicBlock* block : header_->GetPredecessors()) {
628 os << "predecessor: " << block->GetBlockId() << std::endl;
629 }
630 for (uint32_t idx : blocks_.Indexes()) {
631 os << " in loop: " << idx << std::endl;
632 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100633}
634
David Brazdil8d5b8b22015-03-24 10:51:52 +0000635void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000636 // New constants are inserted before the SuspendCheck at the bottom of the
637 // entry block. Note that this method can be called from the graph builder and
638 // the entry block therefore may not end with SuspendCheck->Goto yet.
639 HInstruction* insert_before = nullptr;
640
641 HInstruction* gota = entry_block_->GetLastInstruction();
642 if (gota != nullptr && gota->IsGoto()) {
643 HInstruction* suspend_check = gota->GetPrevious();
644 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
645 insert_before = suspend_check;
646 } else {
647 insert_before = gota;
648 }
649 }
650
651 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000652 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000653 } else {
654 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000655 }
656}
657
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600658HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100659 // For simplicity, don't bother reviving the cached null constant if it is
660 // not null and not in a block. Otherwise, we need to clear the instruction
661 // id and/or any invariants the graph is assuming when adding new instructions.
662 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100663 cached_null_constant_ = new (allocator_) HNullConstant(dex_pc);
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100664 cached_null_constant_->SetReferenceTypeInfo(GetInexactObjectRti());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000665 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000666 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000667 if (kIsDebugBuild) {
668 ScopedObjectAccess soa(Thread::Current());
669 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
670 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000671 return cached_null_constant_;
672}
673
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100674HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100675 // For simplicity, don't bother reviving the cached current method if it is
676 // not null and not in a block. Otherwise, we need to clear the instruction
677 // id and/or any invariants the graph is assuming when adding new instructions.
678 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100679 cached_current_method_ = new (allocator_) HCurrentMethod(
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100680 Is64BitInstructionSet(instruction_set_) ? DataType::Type::kInt64 : DataType::Type::kInt32,
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600681 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100682 if (entry_block_->GetFirstInstruction() == nullptr) {
683 entry_block_->AddInstruction(cached_current_method_);
684 } else {
685 entry_block_->InsertInstructionBefore(
686 cached_current_method_, entry_block_->GetFirstInstruction());
687 }
688 }
689 return cached_current_method_;
690}
691
Igor Murashkind01745e2017-04-05 16:40:31 -0700692const char* HGraph::GetMethodName() const {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800693 const dex::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
Igor Murashkind01745e2017-04-05 16:40:31 -0700694 return dex_file_.GetMethodName(method_id);
695}
696
697std::string HGraph::PrettyMethod(bool with_signature) const {
698 return dex_file_.PrettyMethod(method_idx_, with_signature);
699}
700
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100701HConstant* HGraph::GetConstant(DataType::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000702 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100703 case DataType::Type::kBool:
David Brazdil8d5b8b22015-03-24 10:51:52 +0000704 DCHECK(IsUint<1>(value));
705 FALLTHROUGH_INTENDED;
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100706 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100707 case DataType::Type::kInt8:
708 case DataType::Type::kUint16:
709 case DataType::Type::kInt16:
710 case DataType::Type::kInt32:
711 DCHECK(IsInt(DataType::Size(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600712 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000713
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100714 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600715 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000716
717 default:
718 LOG(FATAL) << "Unsupported constant type";
719 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000720 }
David Brazdil46e2a392015-03-16 17:31:52 +0000721}
722
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000723void HGraph::CacheFloatConstant(HFloatConstant* constant) {
724 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
725 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
726 cached_float_constants_.Overwrite(value, constant);
727}
728
729void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
730 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
731 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
732 cached_double_constants_.Overwrite(value, constant);
733}
734
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000735void HLoopInformation::Add(HBasicBlock* block) {
736 blocks_.SetBit(block->GetBlockId());
737}
738
David Brazdil46e2a392015-03-16 17:31:52 +0000739void HLoopInformation::Remove(HBasicBlock* block) {
740 blocks_.ClearBit(block->GetBlockId());
741}
742
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100743void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
744 if (blocks_.IsBitSet(block->GetBlockId())) {
745 return;
746 }
747
748 blocks_.SetBit(block->GetBlockId());
749 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100750 if (block->IsLoopHeader()) {
751 // We're visiting loops in post-order, so inner loops must have been
752 // populated already.
753 DCHECK(block->GetLoopInformation()->IsPopulated());
754 if (block->GetLoopInformation()->IsIrreducible()) {
755 contains_irreducible_loop_ = true;
756 }
757 }
Vladimir Marko60584552015-09-03 13:35:12 +0000758 for (HBasicBlock* predecessor : block->GetPredecessors()) {
759 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100760 }
761}
762
David Brazdilc2e8af92016-04-05 17:15:19 +0100763void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
764 size_t block_id = block->GetBlockId();
765
766 // If `block` is in `finalized`, we know its membership in the loop has been
767 // decided and it does not need to be revisited.
768 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000769 return;
770 }
771
David Brazdilc2e8af92016-04-05 17:15:19 +0100772 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000773 if (block->IsLoopHeader()) {
774 // If we hit a loop header in an irreducible loop, we first check if the
775 // pre header of that loop belongs to the currently analyzed loop. If it does,
776 // then we visit the back edges.
777 // Note that we cannot use GetPreHeader, as the loop may have not been populated
778 // yet.
779 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100780 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000781 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000782 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100783 blocks_.SetBit(block_id);
784 finalized->SetBit(block_id);
785 is_finalized = true;
786
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000787 HLoopInformation* info = block->GetLoopInformation();
788 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100789 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000790 }
791 }
792 } else {
793 // Visit all predecessors. If one predecessor is part of the loop, this
794 // block is also part of this loop.
795 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100796 PopulateIrreducibleRecursive(predecessor, finalized);
797 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000798 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100799 blocks_.SetBit(block_id);
800 finalized->SetBit(block_id);
801 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000802 }
803 }
804 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100805
806 // All predecessors have been recursively visited. Mark finalized if not marked yet.
807 if (!is_finalized) {
808 finalized->SetBit(block_id);
809 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000810}
811
812void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100813 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000814 // Populate this loop: starting with the back edge, recursively add predecessors
815 // that are not already part of that loop. Set the header as part of the loop
816 // to end the recursion.
817 // This is a recursive implementation of the algorithm described in
818 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100819 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000820 blocks_.SetBit(header_->GetBlockId());
821 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100822
David Brazdil3f4a5222016-05-06 12:46:21 +0100823 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100824
825 if (is_irreducible_loop) {
Vladimir Marko69d310e2017-10-09 14:12:23 +0100826 // Allocate memory from local ScopedArenaAllocator.
827 ScopedArenaAllocator allocator(graph->GetArenaStack());
828 ArenaBitVector visited(&allocator,
David Brazdilc2e8af92016-04-05 17:15:19 +0100829 graph->GetBlocks().size(),
Andreas Gampe3db70682018-12-26 15:12:03 -0800830 /* expandable= */ false,
David Brazdilc2e8af92016-04-05 17:15:19 +0100831 kArenaAllocGraphBuilder);
Vladimir Marko69d310e2017-10-09 14:12:23 +0100832 visited.ClearAllBits();
David Brazdil5a620592016-05-05 11:27:03 +0100833 // Stop marking blocks at the loop header.
834 visited.SetBit(header_->GetBlockId());
835
David Brazdilc2e8af92016-04-05 17:15:19 +0100836 for (HBasicBlock* back_edge : GetBackEdges()) {
837 PopulateIrreducibleRecursive(back_edge, &visited);
838 }
839 } else {
840 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000841 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100842 }
David Brazdila4b8c212015-05-07 09:59:30 +0100843 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100844
Vladimir Markofd66c502016-04-18 15:37:01 +0100845 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
846 // When compiling in OSR mode, all loops in the compiled method may be entered
847 // from the interpreter. We treat this OSR entry point just like an extra entry
848 // to an irreducible loop, so we need to mark the method's loops as irreducible.
849 // This does not apply to inlined loops which do not act as OSR entry points.
850 if (suspend_check_ == nullptr) {
851 // Just building the graph in OSR mode, this loop is not inlined. We never build an
852 // inner graph in OSR mode as we can do OSR transition only from the outer method.
853 is_irreducible_loop = true;
854 } else {
855 // Look at the suspend check's environment to determine if the loop was inlined.
856 DCHECK(suspend_check_->HasEnvironment());
857 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
858 is_irreducible_loop = true;
859 }
860 }
861 }
862 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100863 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100864 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100865 graph->SetHasIrreducibleLoops(true);
866 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800867 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +0100868}
869
Artem Serov7f4aff62017-06-21 17:02:18 +0100870void HLoopInformation::PopulateInnerLoopUpwards(HLoopInformation* inner_loop) {
871 DCHECK(inner_loop->GetPreHeader()->GetLoopInformation() == this);
872 blocks_.Union(&inner_loop->blocks_);
873 HLoopInformation* outer_loop = GetPreHeader()->GetLoopInformation();
874 if (outer_loop != nullptr) {
875 outer_loop->PopulateInnerLoopUpwards(this);
876 }
877}
878
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100879HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000880 HBasicBlock* block = header_->GetPredecessors()[0];
881 DCHECK(irreducible_ || (block == header_->GetDominator()));
882 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100883}
884
885bool HLoopInformation::Contains(const HBasicBlock& block) const {
886 return blocks_.IsBitSet(block.GetBlockId());
887}
888
889bool HLoopInformation::IsIn(const HLoopInformation& other) const {
890 return other.blocks_.IsBitSet(header_->GetBlockId());
891}
892
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800893bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
894 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700895}
896
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100897size_t HLoopInformation::GetLifetimeEnd() const {
898 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100899 for (HBasicBlock* back_edge : GetBackEdges()) {
900 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100901 }
902 return last_position;
903}
904
David Brazdil3f4a5222016-05-06 12:46:21 +0100905bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
906 for (HBasicBlock* back_edge : GetBackEdges()) {
907 DCHECK(back_edge->GetDominator() != nullptr);
908 if (!header_->Dominates(back_edge)) {
909 return true;
910 }
911 }
912 return false;
913}
914
Anton Shaminf89381f2016-05-16 16:44:13 +0600915bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
916 for (HBasicBlock* back_edge : GetBackEdges()) {
917 if (!block->Dominates(back_edge)) {
918 return false;
919 }
920 }
921 return true;
922}
923
David Sehrc757dec2016-11-04 15:48:34 -0700924
925bool HLoopInformation::HasExitEdge() const {
926 // Determine if this loop has at least one exit edge.
927 HBlocksInLoopReversePostOrderIterator it_loop(*this);
928 for (; !it_loop.Done(); it_loop.Advance()) {
929 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
930 if (!Contains(*successor)) {
931 return true;
932 }
933 }
934 }
935 return false;
936}
937
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100938bool HBasicBlock::Dominates(HBasicBlock* other) const {
939 // Walk up the dominator tree from `other`, to find out if `this`
940 // is an ancestor.
941 HBasicBlock* current = other;
942 while (current != nullptr) {
943 if (current == this) {
944 return true;
945 }
946 current = current->GetDominator();
947 }
948 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100949}
950
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100951static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100952 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100953 for (size_t i = 0; i < inputs.size(); ++i) {
954 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100955 }
956 // Environment should be created later.
957 DCHECK(!instruction->HasEnvironment());
958}
959
Artem Serovcced8ba2017-07-19 18:18:09 +0100960void HBasicBlock::ReplaceAndRemovePhiWith(HPhi* initial, HPhi* replacement) {
961 DCHECK(initial->GetBlock() == this);
962 InsertPhiAfter(replacement, initial);
963 initial->ReplaceWith(replacement);
964 RemovePhi(initial);
965}
966
Roland Levillainccc07a92014-09-16 14:48:16 +0100967void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
968 HInstruction* replacement) {
969 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400970 if (initial->IsControlFlow()) {
971 // We can only replace a control flow instruction with another control flow instruction.
972 DCHECK(replacement->IsControlFlow());
973 DCHECK_EQ(replacement->GetId(), -1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100974 DCHECK_EQ(replacement->GetType(), DataType::Type::kVoid);
Mark Mendell805b3b52015-09-18 14:10:29 -0400975 DCHECK_EQ(initial->GetBlock(), this);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100976 DCHECK_EQ(initial->GetType(), DataType::Type::kVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100977 DCHECK(initial->GetUses().empty());
978 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400979 replacement->SetBlock(this);
980 replacement->SetId(GetGraph()->GetNextInstructionId());
981 instructions_.InsertInstructionBefore(replacement, initial);
982 UpdateInputsUsers(replacement);
983 } else {
984 InsertInstructionBefore(replacement, initial);
985 initial->ReplaceWith(replacement);
986 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100987 RemoveInstruction(initial);
988}
989
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100990static void Add(HInstructionList* instruction_list,
991 HBasicBlock* block,
992 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000993 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000994 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100995 instruction->SetBlock(block);
996 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100997 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100998 instruction_list->AddInstruction(instruction);
999}
1000
1001void HBasicBlock::AddInstruction(HInstruction* instruction) {
1002 Add(&instructions_, this, instruction);
1003}
1004
1005void HBasicBlock::AddPhi(HPhi* phi) {
1006 Add(&phis_, this, phi);
1007}
1008
David Brazdilc3d743f2015-04-22 13:40:50 +01001009void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1010 DCHECK(!cursor->IsPhi());
1011 DCHECK(!instruction->IsPhi());
1012 DCHECK_EQ(instruction->GetId(), -1);
1013 DCHECK_NE(cursor->GetId(), -1);
1014 DCHECK_EQ(cursor->GetBlock(), this);
1015 DCHECK(!instruction->IsControlFlow());
1016 instruction->SetBlock(this);
1017 instruction->SetId(GetGraph()->GetNextInstructionId());
1018 UpdateInputsUsers(instruction);
1019 instructions_.InsertInstructionBefore(instruction, cursor);
1020}
1021
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +01001022void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1023 DCHECK(!cursor->IsPhi());
1024 DCHECK(!instruction->IsPhi());
1025 DCHECK_EQ(instruction->GetId(), -1);
1026 DCHECK_NE(cursor->GetId(), -1);
1027 DCHECK_EQ(cursor->GetBlock(), this);
1028 DCHECK(!instruction->IsControlFlow());
1029 DCHECK(!cursor->IsControlFlow());
1030 instruction->SetBlock(this);
1031 instruction->SetId(GetGraph()->GetNextInstructionId());
1032 UpdateInputsUsers(instruction);
1033 instructions_.InsertInstructionAfter(instruction, cursor);
1034}
1035
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001036void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
1037 DCHECK_EQ(phi->GetId(), -1);
1038 DCHECK_NE(cursor->GetId(), -1);
1039 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001040 phi->SetBlock(this);
1041 phi->SetId(GetGraph()->GetNextInstructionId());
1042 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +01001043 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001044}
1045
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001046static void Remove(HInstructionList* instruction_list,
1047 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +00001048 HInstruction* instruction,
1049 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001050 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001051 instruction->SetBlock(nullptr);
1052 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +00001053 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001054 DCHECK(instruction->GetUses().empty());
1055 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +00001056 RemoveAsUser(instruction);
1057 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001058}
1059
David Brazdil1abb4192015-02-17 18:33:36 +00001060void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +01001061 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +00001062 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001063}
1064
David Brazdil1abb4192015-02-17 18:33:36 +00001065void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
1066 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001067}
1068
David Brazdilc7508e92015-04-27 13:28:57 +01001069void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
1070 if (instruction->IsPhi()) {
1071 RemovePhi(instruction->AsPhi(), ensure_safety);
1072 } else {
1073 RemoveInstruction(instruction, ensure_safety);
1074 }
1075}
1076
Vladimir Marko69d310e2017-10-09 14:12:23 +01001077void HEnvironment::CopyFrom(ArrayRef<HInstruction* const> locals) {
Vladimir Marko71bf8092015-09-15 15:33:14 +01001078 for (size_t i = 0; i < locals.size(); i++) {
1079 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +01001080 SetRawEnvAt(i, instruction);
1081 if (instruction != nullptr) {
1082 instruction->AddEnvUseAt(this, i);
1083 }
1084 }
1085}
1086
David Brazdiled596192015-01-23 10:39:45 +00001087void HEnvironment::CopyFrom(HEnvironment* env) {
1088 for (size_t i = 0; i < env->Size(); i++) {
1089 HInstruction* instruction = env->GetInstructionAt(i);
1090 SetRawEnvAt(i, instruction);
1091 if (instruction != nullptr) {
1092 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001093 }
David Brazdiled596192015-01-23 10:39:45 +00001094 }
1095}
1096
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001097void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
1098 HBasicBlock* loop_header) {
1099 DCHECK(loop_header->IsLoopHeader());
1100 for (size_t i = 0; i < env->Size(); i++) {
1101 HInstruction* instruction = env->GetInstructionAt(i);
1102 SetRawEnvAt(i, instruction);
1103 if (instruction == nullptr) {
1104 continue;
1105 }
1106 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
1107 // At the end of the loop pre-header, the corresponding value for instruction
1108 // is the first input of the phi.
1109 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001110 SetRawEnvAt(i, initial);
1111 initial->AddEnvUseAt(this, i);
1112 } else {
1113 instruction->AddEnvUseAt(this, i);
1114 }
1115 }
1116}
1117
David Brazdil1abb4192015-02-17 18:33:36 +00001118void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +01001119 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
1120 HInstruction* user = env_use.GetInstruction();
1121 auto before_env_use_node = env_use.GetBeforeUseNode();
1122 user->env_uses_.erase_after(before_env_use_node);
1123 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001124}
1125
Artem Serovca210e32017-12-15 13:43:20 +00001126void HEnvironment::ReplaceInput(HInstruction* replacement, size_t index) {
1127 const HUserRecord<HEnvironment*>& env_use_record = vregs_[index];
1128 HInstruction* orig_instr = env_use_record.GetInstruction();
1129
1130 DCHECK(orig_instr != replacement);
1131
1132 HUseList<HEnvironment*>::iterator before_use_node = env_use_record.GetBeforeUseNode();
1133 // Note: fixup_end remains valid across splice_after().
1134 auto fixup_end = replacement->env_uses_.empty() ? replacement->env_uses_.begin()
1135 : ++replacement->env_uses_.begin();
1136 replacement->env_uses_.splice_after(replacement->env_uses_.before_begin(),
1137 env_use_record.GetInstruction()->env_uses_,
1138 before_use_node);
1139 replacement->FixUpUserRecordsAfterEnvUseInsertion(fixup_end);
1140 orig_instr->FixUpUserRecordsAfterEnvUseRemoval(before_use_node);
1141}
1142
Calin Juravle77520bc2015-01-12 18:45:46 +00001143HInstruction* HInstruction::GetNextDisregardingMoves() const {
1144 HInstruction* next = GetNext();
1145 while (next != nullptr && next->IsParallelMove()) {
1146 next = next->GetNext();
1147 }
1148 return next;
1149}
1150
1151HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1152 HInstruction* previous = GetPrevious();
1153 while (previous != nullptr && previous->IsParallelMove()) {
1154 previous = previous->GetPrevious();
1155 }
1156 return previous;
1157}
1158
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001159void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001160 if (first_instruction_ == nullptr) {
1161 DCHECK(last_instruction_ == nullptr);
1162 first_instruction_ = last_instruction_ = instruction;
1163 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001164 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001165 last_instruction_->next_ = instruction;
1166 instruction->previous_ = last_instruction_;
1167 last_instruction_ = instruction;
1168 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001169}
1170
David Brazdilc3d743f2015-04-22 13:40:50 +01001171void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1172 DCHECK(Contains(cursor));
1173 if (cursor == first_instruction_) {
1174 cursor->previous_ = instruction;
1175 instruction->next_ = cursor;
1176 first_instruction_ = instruction;
1177 } else {
1178 instruction->previous_ = cursor->previous_;
1179 instruction->next_ = cursor;
1180 cursor->previous_ = instruction;
1181 instruction->previous_->next_ = instruction;
1182 }
1183}
1184
1185void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1186 DCHECK(Contains(cursor));
1187 if (cursor == last_instruction_) {
1188 cursor->next_ = instruction;
1189 instruction->previous_ = cursor;
1190 last_instruction_ = instruction;
1191 } else {
1192 instruction->next_ = cursor->next_;
1193 instruction->previous_ = cursor;
1194 cursor->next_ = instruction;
1195 instruction->next_->previous_ = instruction;
1196 }
1197}
1198
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001199void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1200 if (instruction->previous_ != nullptr) {
1201 instruction->previous_->next_ = instruction->next_;
1202 }
1203 if (instruction->next_ != nullptr) {
1204 instruction->next_->previous_ = instruction->previous_;
1205 }
1206 if (instruction == first_instruction_) {
1207 first_instruction_ = instruction->next_;
1208 }
1209 if (instruction == last_instruction_) {
1210 last_instruction_ = instruction->previous_;
1211 }
1212}
1213
Roland Levillain6b469232014-09-25 10:10:38 +01001214bool HInstructionList::Contains(HInstruction* instruction) const {
1215 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1216 if (it.Current() == instruction) {
1217 return true;
1218 }
1219 }
1220 return false;
1221}
1222
Roland Levillainccc07a92014-09-16 14:48:16 +01001223bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1224 const HInstruction* instruction2) const {
1225 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1226 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1227 if (it.Current() == instruction1) {
1228 return true;
1229 }
1230 if (it.Current() == instruction2) {
1231 return false;
1232 }
1233 }
1234 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
Elliott Hughesc1896c92018-11-29 11:33:18 -08001235 UNREACHABLE();
Roland Levillainccc07a92014-09-16 14:48:16 +01001236}
1237
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001238bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
Roland Levillain6c82d402014-10-13 16:10:27 +01001239 if (other_instruction == this) {
1240 // An instruction does not strictly dominate itself.
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001241 return false;
Roland Levillain6c82d402014-10-13 16:10:27 +01001242 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001243 HBasicBlock* block = GetBlock();
1244 HBasicBlock* other_block = other_instruction->GetBlock();
1245 if (block != other_block) {
1246 return GetBlock()->Dominates(other_instruction->GetBlock());
1247 } else {
1248 // If both instructions are in the same block, ensure this
1249 // instruction comes before `other_instruction`.
1250 if (IsPhi()) {
1251 if (!other_instruction->IsPhi()) {
1252 // Phis appear before non phi-instructions so this instruction
1253 // dominates `other_instruction`.
1254 return true;
1255 } else {
1256 // There is no order among phis.
1257 LOG(FATAL) << "There is no dominance between phis of a same block.";
Elliott Hughesc1896c92018-11-29 11:33:18 -08001258 UNREACHABLE();
Roland Levillainccc07a92014-09-16 14:48:16 +01001259 }
1260 } else {
1261 // `this` is not a phi.
1262 if (other_instruction->IsPhi()) {
1263 // Phis appear before non phi-instructions so this instruction
1264 // does not dominate `other_instruction`.
1265 return false;
1266 } else {
1267 // Check whether this instruction comes before
1268 // `other_instruction` in the instruction list.
1269 return block->GetInstructions().FoundBefore(this, other_instruction);
1270 }
1271 }
1272 }
1273}
1274
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001275void HInstruction::RemoveEnvironment() {
1276 RemoveEnvironmentUses(this);
1277 environment_ = nullptr;
1278}
1279
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001280void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001281 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001282 // Note: fixup_end remains valid across splice_after().
1283 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1284 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1285 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001286
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001287 // Note: env_fixup_end remains valid across splice_after().
1288 auto env_fixup_end =
1289 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1290 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1291 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001292
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001293 DCHECK(uses_.empty());
1294 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001295}
1296
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001297void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001298 const HUseList<HInstruction*>& uses = GetUses();
1299 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1300 HInstruction* user = it->GetUser();
1301 size_t index = it->GetIndex();
1302 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1303 ++it;
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001304 if (dominator->StrictlyDominates(user)) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001305 user->ReplaceInput(replacement, index);
Nicolas Geoffray1c8605e2018-08-05 12:05:01 +01001306 } else if (user->IsPhi() && !user->AsPhi()->IsCatchPhi()) {
1307 // If the input flows from a block dominated by `dominator`, we can replace it.
1308 // We do not perform this for catch phis as we don't have control flow support
1309 // for their inputs.
1310 const ArenaVector<HBasicBlock*>& predecessors = user->GetBlock()->GetPredecessors();
1311 HBasicBlock* predecessor = predecessors[index];
1312 if (dominator->GetBlock()->Dominates(predecessor)) {
1313 user->ReplaceInput(replacement, index);
1314 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001315 }
1316 }
1317}
1318
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +01001319void HInstruction::ReplaceEnvUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1320 const HUseList<HEnvironment*>& uses = GetEnvUses();
1321 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1322 HEnvironment* user = it->GetUser();
1323 size_t index = it->GetIndex();
1324 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1325 ++it;
1326 if (dominator->StrictlyDominates(user->GetHolder())) {
1327 user->ReplaceInput(replacement, index);
1328 }
1329 }
1330}
1331
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001332void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001333 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001334 if (input_use.GetInstruction() == replacement) {
1335 // Nothing to do.
1336 return;
1337 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001338 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001339 // Note: fixup_end remains valid across splice_after().
1340 auto fixup_end =
1341 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1342 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1343 input_use.GetInstruction()->uses_,
1344 before_use_node);
1345 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1346 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001347}
1348
Nicolas Geoffray39468442014-09-02 15:17:15 +01001349size_t HInstruction::EnvironmentSize() const {
1350 return HasEnvironment() ? environment_->Size() : 0;
1351}
1352
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001353void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001354 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001355 inputs_.push_back(HUserRecord<HInstruction*>(input));
1356 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001357}
1358
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001359void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1360 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1361 input->AddUseAt(this, index);
1362 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1363 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1364 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1365 inputs_[i].GetUseNode()->SetIndex(i);
1366 }
1367}
1368
1369void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001370 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001371 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001372 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1373 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1374 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1375 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001376 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001377}
1378
Igor Murashkind01745e2017-04-05 16:40:31 -07001379void HVariableInputSizeInstruction::RemoveAllInputs() {
1380 RemoveAsUserOfAllInputs();
1381 DCHECK(!HasNonEnvironmentUses());
1382
1383 inputs_.clear();
1384 DCHECK_EQ(0u, InputCount());
1385}
1386
Igor Murashkin6ef45672017-08-08 13:59:55 -07001387size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001388 DCHECK(instruction->GetBlock() != nullptr);
1389 // Removing constructor fences only makes sense for instructions with an object return type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001390 DCHECK_EQ(DataType::Type::kReference, instruction->GetType());
Igor Murashkind01745e2017-04-05 16:40:31 -07001391
Igor Murashkin6ef45672017-08-08 13:59:55 -07001392 // Return how many instructions were removed for statistic purposes.
1393 size_t remove_count = 0;
1394
Igor Murashkind01745e2017-04-05 16:40:31 -07001395 // Efficient implementation that simultaneously (in one pass):
1396 // * Scans the uses list for all constructor fences.
1397 // * Deletes that constructor fence from the uses list of `instruction`.
1398 // * Deletes `instruction` from the constructor fence's inputs.
1399 // * Deletes the constructor fence if it now has 0 inputs.
1400
1401 const HUseList<HInstruction*>& uses = instruction->GetUses();
1402 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1403 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1404 const HUseListNode<HInstruction*>& use_node = *it;
1405 HInstruction* const use_instruction = use_node.GetUser();
1406
1407 // Advance the iterator immediately once we fetch the use_node.
1408 // Warning: If the input is removed, the current iterator becomes invalid.
1409 ++it;
1410
1411 if (use_instruction->IsConstructorFence()) {
1412 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1413 size_t input_index = use_node.GetIndex();
1414
1415 // Process the candidate instruction for removal
1416 // from the graph.
1417
1418 // Constructor fence instructions are never
1419 // used by other instructions.
1420 //
1421 // If we wanted to make this more generic, it
1422 // could be a runtime if statement.
1423 DCHECK(!ctor_fence->HasUses());
1424
1425 // A constructor fence's return type is "kPrimVoid"
1426 // and therefore it can't have any environment uses.
1427 DCHECK(!ctor_fence->HasEnvironmentUses());
1428
1429 // Remove the inputs first, otherwise removing the instruction
1430 // will try to remove its uses while we are already removing uses
1431 // and this operation will fail.
1432 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1433
1434 // Removing the input will also remove the `use_node`.
1435 // (Do not look at `use_node` after this, it will be a dangling reference).
1436 ctor_fence->RemoveInputAt(input_index);
1437
1438 // Once all inputs are removed, the fence is considered dead and
1439 // is removed.
1440 if (ctor_fence->InputCount() == 0u) {
1441 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
Igor Murashkin6ef45672017-08-08 13:59:55 -07001442 ++remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001443 }
1444 }
1445 }
1446
1447 if (kIsDebugBuild) {
1448 // Post-condition checks:
1449 // * None of the uses of `instruction` are a constructor fence.
1450 // * The `instruction` itself did not get removed from a block.
1451 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1452 CHECK(!use_node.GetUser()->IsConstructorFence());
1453 }
1454 CHECK(instruction->GetBlock() != nullptr);
1455 }
Igor Murashkin6ef45672017-08-08 13:59:55 -07001456
1457 return remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001458}
1459
Igor Murashkindd018df2017-08-09 10:38:31 -07001460void HConstructorFence::Merge(HConstructorFence* other) {
1461 // Do not delete yourself from the graph.
1462 DCHECK(this != other);
1463 // Don't try to merge with an instruction not associated with a block.
1464 DCHECK(other->GetBlock() != nullptr);
1465 // A constructor fence's return type is "kPrimVoid"
1466 // and therefore it cannot have any environment uses.
1467 DCHECK(!other->HasEnvironmentUses());
1468
1469 auto has_input = [](HInstruction* haystack, HInstruction* needle) {
1470 // Check if `haystack` has `needle` as any of its inputs.
1471 for (size_t input_count = 0; input_count < haystack->InputCount(); ++input_count) {
1472 if (haystack->InputAt(input_count) == needle) {
1473 return true;
1474 }
1475 }
1476 return false;
1477 };
1478
1479 // Add any inputs from `other` into `this` if it wasn't already an input.
1480 for (size_t input_count = 0; input_count < other->InputCount(); ++input_count) {
1481 HInstruction* other_input = other->InputAt(input_count);
1482 if (!has_input(this, other_input)) {
1483 AddInput(other_input);
1484 }
1485 }
1486
1487 other->GetBlock()->RemoveInstruction(other);
1488}
1489
1490HInstruction* HConstructorFence::GetAssociatedAllocation(bool ignore_inputs) {
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001491 HInstruction* new_instance_inst = GetPrevious();
1492 // Check if the immediately preceding instruction is a new-instance/new-array.
1493 // Otherwise this fence is for protecting final fields.
1494 if (new_instance_inst != nullptr &&
1495 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
Igor Murashkindd018df2017-08-09 10:38:31 -07001496 if (ignore_inputs) {
1497 // If inputs are ignored, simply check if the predecessor is
1498 // *any* HNewInstance/HNewArray.
1499 //
1500 // Inputs are normally only ignored for prepare_for_register_allocation,
1501 // at which point *any* prior HNewInstance/Array can be considered
1502 // associated.
1503 return new_instance_inst;
1504 } else {
1505 // Normal case: There must be exactly 1 input and the previous instruction
1506 // must be that input.
1507 if (InputCount() == 1u && InputAt(0) == new_instance_inst) {
1508 return new_instance_inst;
1509 }
1510 }
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001511 }
Igor Murashkindd018df2017-08-09 10:38:31 -07001512 return nullptr;
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001513}
1514
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001515#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001516void H##name::Accept(HGraphVisitor* visitor) { \
1517 visitor->Visit##name(this); \
1518}
1519
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001520FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001521
1522#undef DEFINE_ACCEPT
1523
1524void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001525 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1526 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001527 if (block != nullptr) {
1528 VisitBasicBlock(block);
1529 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001530 }
1531}
1532
Roland Levillain633021e2014-10-01 14:12:25 +01001533void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001534 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1535 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001536 }
1537}
1538
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001539void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001540 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001541 it.Current()->Accept(this);
1542 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001543 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001544 it.Current()->Accept(this);
1545 }
1546}
1547
Mark Mendelle82549b2015-05-06 10:55:34 -04001548HConstant* HTypeConversion::TryStaticEvaluation() const {
1549 HGraph* graph = GetBlock()->GetGraph();
1550 if (GetInput()->IsIntConstant()) {
1551 int32_t value = GetInput()->AsIntConstant()->GetValue();
1552 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001553 case DataType::Type::kInt8:
1554 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1555 case DataType::Type::kUint8:
1556 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1557 case DataType::Type::kInt16:
1558 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1559 case DataType::Type::kUint16:
1560 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001561 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001562 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001563 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001564 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001565 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001566 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001567 default:
1568 return nullptr;
1569 }
1570 } else if (GetInput()->IsLongConstant()) {
1571 int64_t value = GetInput()->AsLongConstant()->GetValue();
1572 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001573 case DataType::Type::kInt8:
1574 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1575 case DataType::Type::kUint8:
1576 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1577 case DataType::Type::kInt16:
1578 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1579 case DataType::Type::kUint16:
1580 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001581 case DataType::Type::kInt32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001582 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001583 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001584 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001585 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001586 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001587 default:
1588 return nullptr;
1589 }
1590 } else if (GetInput()->IsFloatConstant()) {
1591 float value = GetInput()->AsFloatConstant()->GetValue();
1592 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001593 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001594 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001595 return graph->GetIntConstant(0, GetDexPc());
Nick Desaulniers706e7782019-10-16 10:02:23 -07001596 if (value >= static_cast<float>(kPrimIntMax))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001597 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001598 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001599 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1600 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001601 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001602 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001603 return graph->GetLongConstant(0, GetDexPc());
Nick Desaulniers706e7782019-10-16 10:02:23 -07001604 if (value >= static_cast<float>(kPrimLongMax))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001605 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001606 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001607 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1608 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001609 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001610 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001611 default:
1612 return nullptr;
1613 }
1614 } else if (GetInput()->IsDoubleConstant()) {
1615 double value = GetInput()->AsDoubleConstant()->GetValue();
1616 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001617 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001618 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001619 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001620 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001621 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001622 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001623 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1624 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001625 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001626 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001627 return graph->GetLongConstant(0, GetDexPc());
Nick Desaulniers706e7782019-10-16 10:02:23 -07001628 if (value >= static_cast<double>(kPrimLongMax))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001629 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001630 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001631 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1632 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001633 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001634 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001635 default:
1636 return nullptr;
1637 }
1638 }
1639 return nullptr;
1640}
1641
Roland Levillain9240d6a2014-10-20 16:47:04 +01001642HConstant* HUnaryOperation::TryStaticEvaluation() const {
1643 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001644 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001645 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001646 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001647 } else if (kEnableFloatingPointStaticEvaluation) {
1648 if (GetInput()->IsFloatConstant()) {
1649 return Evaluate(GetInput()->AsFloatConstant());
1650 } else if (GetInput()->IsDoubleConstant()) {
1651 return Evaluate(GetInput()->AsDoubleConstant());
1652 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001653 }
1654 return nullptr;
1655}
1656
1657HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001658 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1659 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001660 } else if (GetLeft()->IsLongConstant()) {
1661 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001662 // The binop(long, int) case is only valid for shifts and rotations.
1663 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001664 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1665 } else if (GetRight()->IsLongConstant()) {
1666 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001667 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001668 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001669 // The binop(null, null) case is only valid for equal and not-equal conditions.
1670 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001671 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001672 } else if (kEnableFloatingPointStaticEvaluation) {
1673 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1674 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1675 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1676 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1677 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001678 }
1679 return nullptr;
1680}
Dave Allison20dfc792014-06-16 20:44:29 -07001681
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001682HConstant* HBinaryOperation::GetConstantRight() const {
1683 if (GetRight()->IsConstant()) {
1684 return GetRight()->AsConstant();
1685 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1686 return GetLeft()->AsConstant();
1687 } else {
1688 return nullptr;
1689 }
1690}
1691
1692// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001693// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001694HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1695 HInstruction* most_constant_right = GetConstantRight();
1696 if (most_constant_right == nullptr) {
1697 return nullptr;
1698 } else if (most_constant_right == GetLeft()) {
1699 return GetRight();
1700 } else {
1701 return GetLeft();
1702 }
1703}
1704
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001705std::ostream& operator<<(std::ostream& os, ComparisonBias rhs) {
1706 // TODO: Replace with auto-generated operator<<.
Roland Levillain31dd3d62016-02-16 12:21:02 +00001707 switch (rhs) {
1708 case ComparisonBias::kNoBias:
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001709 return os << "none";
Roland Levillain31dd3d62016-02-16 12:21:02 +00001710 case ComparisonBias::kGtBias:
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001711 return os << "gt";
Roland Levillain31dd3d62016-02-16 12:21:02 +00001712 case ComparisonBias::kLtBias:
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001713 return os << "lt";
Roland Levillain31dd3d62016-02-16 12:21:02 +00001714 default:
1715 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1716 UNREACHABLE();
1717 }
1718}
1719
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001720bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1721 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001722}
1723
Vladimir Marko372f10e2016-05-17 16:30:10 +01001724bool HInstruction::Equals(const HInstruction* other) const {
Vladimir Marko0dcccd82018-05-04 13:32:25 +01001725 if (GetKind() != other->GetKind()) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001726 if (GetType() != other->GetType()) return false;
Vladimir Marko0dcccd82018-05-04 13:32:25 +01001727 if (!InstructionDataEquals(other)) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001728 HConstInputsRef inputs = GetInputs();
1729 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001730 if (inputs.size() != other_inputs.size()) return false;
1731 for (size_t i = 0; i != inputs.size(); ++i) {
1732 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001733 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001734
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001735 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001736 return true;
1737}
1738
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001739std::ostream& operator<<(std::ostream& os, HInstruction::InstructionKind rhs) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001740#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1741 switch (rhs) {
Vladimir Markoe3946222018-05-04 14:18:47 +01001742 FOR_EACH_CONCRETE_INSTRUCTION(DECLARE_CASE)
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001743 default:
1744 os << "Unknown instruction kind " << static_cast<int>(rhs);
1745 break;
1746 }
1747#undef DECLARE_CASE
1748 return os;
1749}
1750
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001751void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1752 if (do_checks) {
1753 DCHECK(!IsPhi());
1754 DCHECK(!IsControlFlow());
1755 DCHECK(CanBeMoved() ||
1756 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1757 IsShouldDeoptimizeFlag());
1758 DCHECK(!cursor->IsPhi());
1759 }
David Brazdild6c205e2016-06-07 14:20:52 +01001760
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001761 next_->previous_ = previous_;
1762 if (previous_ != nullptr) {
1763 previous_->next_ = next_;
1764 }
1765 if (block_->instructions_.first_instruction_ == this) {
1766 block_->instructions_.first_instruction_ = next_;
1767 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001768 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001769
1770 previous_ = cursor->previous_;
1771 if (previous_ != nullptr) {
1772 previous_->next_ = this;
1773 }
1774 next_ = cursor;
1775 cursor->previous_ = this;
1776 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001777
1778 if (block_->instructions_.first_instruction_ == cursor) {
1779 block_->instructions_.first_instruction_ = this;
1780 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001781}
1782
Vladimir Markofb337ea2015-11-25 15:25:10 +00001783void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1784 DCHECK(!CanThrow());
1785 DCHECK(!HasSideEffects());
1786 DCHECK(!HasEnvironmentUses());
1787 DCHECK(HasNonEnvironmentUses());
1788 DCHECK(!IsPhi()); // Makes no sense for Phi.
1789 DCHECK_EQ(InputCount(), 0u);
1790
1791 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001792 auto uses_it = GetUses().begin();
1793 auto uses_end = GetUses().end();
1794 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1795 ++uses_it;
1796 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1797 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001798 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001799 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001800 // This instruction has uses in two or more blocks. Find the common dominator.
1801 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001802 for (; uses_it != uses_end; ++uses_it) {
1803 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001804 }
1805 target_block = finder.Get();
1806 DCHECK(target_block != nullptr);
1807 }
1808 // Move to the first dominator not in a loop.
1809 while (target_block->IsInLoop()) {
1810 target_block = target_block->GetDominator();
1811 DCHECK(target_block != nullptr);
1812 }
1813
1814 // Find insertion position.
1815 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001816 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1817 if (use.GetUser()->GetBlock() == target_block &&
1818 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1819 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001820 }
1821 }
1822 if (insert_pos == nullptr) {
1823 // No user in `target_block`, insert before the control flow instruction.
1824 insert_pos = target_block->GetLastInstruction();
1825 DCHECK(insert_pos->IsControlFlow());
1826 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1827 if (insert_pos->IsIf()) {
1828 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1829 if (if_input == insert_pos->GetPrevious()) {
1830 insert_pos = if_input;
1831 }
1832 }
1833 }
1834 MoveBefore(insert_pos);
1835}
1836
David Brazdilfc6a86a2015-06-26 10:33:45 +00001837HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001838 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001839 DCHECK_EQ(cursor->GetBlock(), this);
1840
Vladimir Markoca6fff82017-10-03 14:49:14 +01001841 HBasicBlock* new_block =
1842 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001843 new_block->instructions_.first_instruction_ = cursor;
1844 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1845 instructions_.last_instruction_ = cursor->previous_;
1846 if (cursor->previous_ == nullptr) {
1847 instructions_.first_instruction_ = nullptr;
1848 } else {
1849 cursor->previous_->next_ = nullptr;
1850 cursor->previous_ = nullptr;
1851 }
1852
1853 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001854 AddInstruction(new (GetGraph()->GetAllocator()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001855
Vladimir Marko60584552015-09-03 13:35:12 +00001856 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001857 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001858 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001859 new_block->successors_.swap(successors_);
1860 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001861 AddSuccessor(new_block);
1862
David Brazdil56e1acc2015-06-30 15:41:36 +01001863 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001864 return new_block;
1865}
1866
David Brazdild7558da2015-09-22 13:04:14 +01001867HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001868 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001869 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1870
Vladimir Markoca6fff82017-10-03 14:49:14 +01001871 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
David Brazdild7558da2015-09-22 13:04:14 +01001872
1873 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001874 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1875 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001876 new_block->predecessors_.swap(predecessors_);
1877 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001878 AddPredecessor(new_block);
1879
1880 GetGraph()->AddBlock(new_block);
1881 return new_block;
1882}
1883
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001884HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1885 DCHECK_EQ(cursor->GetBlock(), this);
1886
Vladimir Markoca6fff82017-10-03 14:49:14 +01001887 HBasicBlock* new_block =
1888 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001889 new_block->instructions_.first_instruction_ = cursor;
1890 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1891 instructions_.last_instruction_ = cursor->previous_;
1892 if (cursor->previous_ == nullptr) {
1893 instructions_.first_instruction_ = nullptr;
1894 } else {
1895 cursor->previous_->next_ = nullptr;
1896 cursor->previous_ = nullptr;
1897 }
1898
1899 new_block->instructions_.SetBlockOfInstructions(new_block);
1900
1901 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001902 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1903 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001904 new_block->successors_.swap(successors_);
1905 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001906
1907 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1908 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001909 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001910 new_block->dominated_blocks_.swap(dominated_blocks_);
1911 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001912 return new_block;
1913}
1914
1915HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001916 DCHECK(!cursor->IsControlFlow());
1917 DCHECK_NE(instructions_.last_instruction_, cursor);
1918 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001919
Vladimir Markoca6fff82017-10-03 14:49:14 +01001920 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001921 new_block->instructions_.first_instruction_ = cursor->GetNext();
1922 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1923 cursor->next_->previous_ = nullptr;
1924 cursor->next_ = nullptr;
1925 instructions_.last_instruction_ = cursor;
1926
1927 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001928 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001929 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001930 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001931 new_block->successors_.swap(successors_);
1932 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001933
Vladimir Marko60584552015-09-03 13:35:12 +00001934 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001935 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001936 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001937 new_block->dominated_blocks_.swap(dominated_blocks_);
1938 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001939 return new_block;
1940}
1941
David Brazdilec16f792015-08-19 15:04:01 +01001942const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001943 if (EndsWithTryBoundary()) {
1944 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1945 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001946 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001947 return try_boundary;
1948 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001949 DCHECK(IsTryBlock());
1950 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001951 return nullptr;
1952 }
David Brazdilec16f792015-08-19 15:04:01 +01001953 } else if (IsTryBlock()) {
1954 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001955 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001956 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001957 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001958}
1959
Aart Bik75ff2c92018-04-21 01:28:11 +00001960bool HBasicBlock::HasThrowingInstructions() const {
1961 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1962 if (it.Current()->CanThrow()) {
1963 return true;
1964 }
1965 }
1966 return false;
1967}
1968
David Brazdilfc6a86a2015-06-26 10:33:45 +00001969static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1970 return block.GetPhis().IsEmpty()
1971 && !block.GetInstructions().IsEmpty()
1972 && block.GetFirstInstruction() == block.GetLastInstruction();
1973}
1974
David Brazdil46e2a392015-03-16 17:31:52 +00001975bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001976 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1977}
1978
Mads Ager16e52892017-07-14 13:11:37 +02001979bool HBasicBlock::IsSingleReturn() const {
1980 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
1981}
1982
Mingyao Yang46721ef2017-10-05 14:45:17 -07001983bool HBasicBlock::IsSingleReturnOrReturnVoidAllowingPhis() const {
1984 return (GetFirstInstruction() == GetLastInstruction()) &&
1985 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
1986}
1987
David Brazdilfc6a86a2015-06-26 10:33:45 +00001988bool HBasicBlock::IsSingleTryBoundary() const {
1989 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001990}
1991
David Brazdil8d5b8b22015-03-24 10:51:52 +00001992bool HBasicBlock::EndsWithControlFlowInstruction() const {
1993 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1994}
1995
Aart Bik4dc09e72018-05-11 14:40:31 -07001996bool HBasicBlock::EndsWithReturn() const {
1997 return !GetInstructions().IsEmpty() &&
1998 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
1999}
2000
David Brazdilb2bd1c52015-03-25 11:17:37 +00002001bool HBasicBlock::EndsWithIf() const {
2002 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
2003}
2004
David Brazdilffee3d32015-07-06 11:48:53 +01002005bool HBasicBlock::EndsWithTryBoundary() const {
2006 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
2007}
2008
David Brazdilb2bd1c52015-03-25 11:17:37 +00002009bool HBasicBlock::HasSinglePhi() const {
2010 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
2011}
2012
David Brazdild26a4112015-11-10 11:07:31 +00002013ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
2014 if (EndsWithTryBoundary()) {
2015 // The normal-flow successor of HTryBoundary is always stored at index zero.
2016 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
2017 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
2018 } else {
2019 // All successors of blocks not ending with TryBoundary are normal.
2020 return ArrayRef<HBasicBlock* const>(successors_);
2021 }
2022}
2023
2024ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
2025 if (EndsWithTryBoundary()) {
2026 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
2027 } else {
2028 // Blocks not ending with TryBoundary do not have exceptional successors.
2029 return ArrayRef<HBasicBlock* const>();
2030 }
2031}
2032
David Brazdilffee3d32015-07-06 11:48:53 +01002033bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00002034 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
2035 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
2036
2037 size_t length = handlers1.size();
2038 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01002039 return false;
2040 }
2041
David Brazdilb618ade2015-07-29 10:31:29 +01002042 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00002043 for (size_t i = 0; i < length; ++i) {
2044 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01002045 return false;
2046 }
2047 }
2048 return true;
2049}
2050
David Brazdil2d7352b2015-04-20 14:52:42 +01002051size_t HInstructionList::CountSize() const {
2052 size_t size = 0;
2053 HInstruction* current = first_instruction_;
2054 for (; current != nullptr; current = current->GetNext()) {
2055 size++;
2056 }
2057 return size;
2058}
2059
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002060void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
2061 for (HInstruction* current = first_instruction_;
2062 current != nullptr;
2063 current = current->GetNext()) {
2064 current->SetBlock(block);
2065 }
2066}
2067
2068void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
2069 DCHECK(Contains(cursor));
2070 if (!instruction_list.IsEmpty()) {
2071 if (cursor == last_instruction_) {
2072 last_instruction_ = instruction_list.last_instruction_;
2073 } else {
2074 cursor->next_->previous_ = instruction_list.last_instruction_;
2075 }
2076 instruction_list.last_instruction_->next_ = cursor->next_;
2077 cursor->next_ = instruction_list.first_instruction_;
2078 instruction_list.first_instruction_->previous_ = cursor;
2079 }
2080}
2081
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002082void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
2083 DCHECK(Contains(cursor));
2084 if (!instruction_list.IsEmpty()) {
2085 if (cursor == first_instruction_) {
2086 first_instruction_ = instruction_list.first_instruction_;
2087 } else {
2088 cursor->previous_->next_ = instruction_list.first_instruction_;
2089 }
2090 instruction_list.last_instruction_->next_ = cursor;
2091 instruction_list.first_instruction_->previous_ = cursor->previous_;
2092 cursor->previous_ = instruction_list.last_instruction_;
2093 }
2094}
2095
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002096void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00002097 if (IsEmpty()) {
2098 first_instruction_ = instruction_list.first_instruction_;
2099 last_instruction_ = instruction_list.last_instruction_;
2100 } else {
2101 AddAfter(last_instruction_, instruction_list);
2102 }
2103}
2104
David Brazdil04ff4e82015-12-10 13:54:52 +00002105// Should be called on instructions in a dead block in post order. This method
2106// assumes `insn` has been removed from all users with the exception of catch
2107// phis because of missing exceptional edges in the graph. It removes the
2108// instruction from catch phi uses, together with inputs of other catch phis in
2109// the catch block at the same index, as these must be dead too.
2110static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
2111 DCHECK(!insn->HasEnvironmentUses());
2112 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01002113 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
2114 size_t use_index = use.GetIndex();
2115 HBasicBlock* user_block = use.GetUser()->GetBlock();
2116 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00002117 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2118 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
2119 }
2120 }
2121}
2122
David Brazdil2d7352b2015-04-20 14:52:42 +01002123void HBasicBlock::DisconnectAndDelete() {
2124 // Dominators must be removed after all the blocks they dominate. This way
2125 // a loop header is removed last, a requirement for correct loop information
2126 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00002127 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00002128
David Brazdil9eeebf62016-03-24 11:18:15 +00002129 // The following steps gradually remove the block from all its dependants in
2130 // post order (b/27683071).
2131
2132 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
2133 // We need to do this before step (4) which destroys the predecessor list.
2134 HBasicBlock* loop_update_start = this;
2135 if (IsLoopHeader()) {
2136 HLoopInformation* loop_info = GetLoopInformation();
2137 // All other blocks in this loop should have been removed because the header
2138 // was their dominator.
2139 // Note that we do not remove `this` from `loop_info` as it is unreachable.
2140 DCHECK(!loop_info->IsIrreducible());
2141 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
2142 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
2143 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01002144 }
2145
David Brazdil9eeebf62016-03-24 11:18:15 +00002146 // (2) Disconnect the block from its successors and update their phis.
2147 for (HBasicBlock* successor : successors_) {
2148 // Delete this block from the list of predecessors.
2149 size_t this_index = successor->GetPredecessorIndexOf(this);
2150 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
2151
2152 // Check that `successor` has other predecessors, otherwise `this` is the
2153 // dominator of `successor` which violates the order DCHECKed at the top.
2154 DCHECK(!successor->predecessors_.empty());
2155
2156 // Remove this block's entries in the successor's phis. Skip exceptional
2157 // successors because catch phi inputs do not correspond to predecessor
2158 // blocks but throwing instructions. The inputs of the catch phis will be
2159 // updated in step (3).
2160 if (!successor->IsCatchBlock()) {
2161 if (successor->predecessors_.size() == 1u) {
2162 // The successor has just one predecessor left. Replace phis with the only
2163 // remaining input.
2164 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2165 HPhi* phi = phi_it.Current()->AsPhi();
2166 phi->ReplaceWith(phi->InputAt(1 - this_index));
2167 successor->RemovePhi(phi);
2168 }
2169 } else {
2170 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2171 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
2172 }
2173 }
2174 }
2175 }
2176 successors_.clear();
2177
2178 // (3) Remove instructions and phis. Instructions should have no remaining uses
2179 // except in catch phis. If an instruction is used by a catch phi at `index`,
2180 // remove `index`-th input of all phis in the catch block since they are
2181 // guaranteed dead. Note that we may miss dead inputs this way but the
2182 // graph will always remain consistent.
2183 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2184 HInstruction* insn = it.Current();
2185 RemoveUsesOfDeadInstruction(insn);
2186 RemoveInstruction(insn);
2187 }
2188 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
2189 HPhi* insn = it.Current()->AsPhi();
2190 RemoveUsesOfDeadInstruction(insn);
2191 RemovePhi(insn);
2192 }
2193
2194 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002195 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00002196 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00002197 // We should not see any back edges as they would have been removed by step (3).
2198 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
2199
David Brazdil2d7352b2015-04-20 14:52:42 +01002200 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002201 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
2202 // This block is the only normal-flow successor of the TryBoundary which
2203 // makes `predecessor` dead. Since DCE removes blocks in post order,
2204 // exception handlers of this TryBoundary were already visited and any
2205 // remaining handlers therefore must be live. We remove `predecessor` from
2206 // their list of predecessors.
2207 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
2208 while (predecessor->GetSuccessors().size() > 1) {
2209 HBasicBlock* handler = predecessor->GetSuccessors()[1];
2210 DCHECK(handler->IsCatchBlock());
2211 predecessor->RemoveSuccessor(handler);
2212 handler->RemovePredecessor(predecessor);
2213 }
2214 }
2215
David Brazdil2d7352b2015-04-20 14:52:42 +01002216 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04002217 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
2218 if (num_pred_successors == 1u) {
2219 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002220 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
2221 // successor. Replace those with a HGoto.
2222 DCHECK(last_instruction->IsIf() ||
2223 last_instruction->IsPackedSwitch() ||
2224 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002225 predecessor->RemoveInstruction(last_instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002226 predecessor->AddInstruction(new (graph_->GetAllocator()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002227 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002228 // The predecessor has no remaining successors and therefore must be dead.
2229 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00002230 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04002231 predecessor->RemoveInstruction(last_instruction);
2232 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002233 // There are multiple successors left. The removed block might be a successor
2234 // of a PackedSwitch which will be completely removed (perhaps replaced with
2235 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2236 // case, leave `last_instruction` as is for now.
2237 DCHECK(last_instruction->IsPackedSwitch() ||
2238 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002239 }
David Brazdil46e2a392015-03-16 17:31:52 +00002240 }
Vladimir Marko60584552015-09-03 13:35:12 +00002241 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002242
David Brazdil9eeebf62016-03-24 11:18:15 +00002243 // (5) Remove the block from all loops it is included in. Skip the inner-most
2244 // loop if this is the loop header (see definition of `loop_update_start`)
2245 // because the loop header's predecessor list has been destroyed in step (4).
2246 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2247 HLoopInformation* loop_info = it.Current();
2248 loop_info->Remove(this);
2249 if (loop_info->IsBackEdge(*this)) {
2250 // If this was the last back edge of the loop, we deliberately leave the
2251 // loop in an inconsistent state and will fail GraphChecker unless the
2252 // entire loop is removed during the pass.
2253 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002254 }
2255 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002256
David Brazdil9eeebf62016-03-24 11:18:15 +00002257 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002258 dominator_->RemoveDominatedBlock(this);
2259 SetDominator(nullptr);
2260
David Brazdil9eeebf62016-03-24 11:18:15 +00002261 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002262 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002263 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002264}
2265
Aart Bik6b69e0a2017-01-11 10:20:43 -08002266void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2267 DCHECK(EndsWithControlFlowInstruction());
2268 RemoveInstruction(GetLastInstruction());
2269 instructions_.Add(other->GetInstructions());
2270 other->instructions_.SetBlockOfInstructions(this);
2271 other->instructions_.Clear();
2272}
2273
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002274void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002275 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002276 DCHECK(ContainsElement(dominated_blocks_, other));
2277 DCHECK_EQ(GetSingleSuccessor(), other);
2278 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002279 DCHECK(other->GetPhis().IsEmpty());
2280
David Brazdil2d7352b2015-04-20 14:52:42 +01002281 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002282 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002283
David Brazdil2d7352b2015-04-20 14:52:42 +01002284 // Remove `other` from the loops it is included in.
2285 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2286 HLoopInformation* loop_info = it.Current();
2287 loop_info->Remove(other);
2288 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002289 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002290 }
2291 }
2292
2293 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002294 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002295 for (HBasicBlock* successor : other->GetSuccessors()) {
2296 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002297 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002298 successors_.swap(other->successors_);
2299 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002300
David Brazdil2d7352b2015-04-20 14:52:42 +01002301 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002302 RemoveDominatedBlock(other);
2303 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002304 dominated->SetDominator(this);
2305 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002306 dominated_blocks_.insert(
2307 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002308 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002309 other->dominator_ = nullptr;
2310
2311 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002312 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002313
2314 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002315 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002316 other->SetGraph(nullptr);
2317}
2318
2319void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2320 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002321 DCHECK(GetDominatedBlocks().empty());
2322 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002323 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002324 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002325 DCHECK(other->GetPhis().IsEmpty());
2326 DCHECK(!other->IsInLoop());
2327
2328 // Move instructions from `other` to `this`.
2329 instructions_.Add(other->GetInstructions());
2330 other->instructions_.SetBlockOfInstructions(this);
2331
2332 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002333 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002334 for (HBasicBlock* successor : other->GetSuccessors()) {
2335 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002336 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002337 successors_.swap(other->successors_);
2338 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002339
2340 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002341 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002342 dominated->SetDominator(this);
2343 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002344 dominated_blocks_.insert(
2345 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002346 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002347 other->dominator_ = nullptr;
2348 other->graph_ = nullptr;
2349}
2350
2351void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002352 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002353 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002354 predecessor->ReplaceSuccessor(this, other);
2355 }
Vladimir Marko60584552015-09-03 13:35:12 +00002356 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002357 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002358 successor->ReplacePredecessor(this, other);
2359 }
Vladimir Marko60584552015-09-03 13:35:12 +00002360 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2361 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002362 }
2363 GetDominator()->ReplaceDominatedBlock(this, other);
2364 other->SetDominator(GetDominator());
2365 dominator_ = nullptr;
2366 graph_ = nullptr;
2367}
2368
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002369void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002370 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002371 DCHECK(block->GetSuccessors().empty());
2372 DCHECK(block->GetPredecessors().empty());
2373 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002374 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002375 DCHECK(block->GetInstructions().IsEmpty());
2376 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002377
David Brazdilc7af85d2015-05-26 12:05:55 +01002378 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002379 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002380 }
2381
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002382 RemoveElement(reverse_post_order_, block);
2383 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002384 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002385}
2386
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002387void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2388 HBasicBlock* reference,
2389 bool replace_if_back_edge) {
2390 if (block->IsLoopHeader()) {
2391 // Clear the information of which blocks are contained in that loop. Since the
2392 // information is stored as a bit vector based on block ids, we have to update
2393 // it, as those block ids were specific to the callee graph and we are now adding
2394 // these blocks to the caller graph.
2395 block->GetLoopInformation()->ClearAllBlocks();
2396 }
2397
2398 // If not already in a loop, update the loop information.
2399 if (!block->IsInLoop()) {
2400 block->SetLoopInformation(reference->GetLoopInformation());
2401 }
2402
2403 // If the block is in a loop, update all its outward loops.
2404 HLoopInformation* loop_info = block->GetLoopInformation();
2405 if (loop_info != nullptr) {
2406 for (HLoopInformationOutwardIterator loop_it(*block);
2407 !loop_it.Done();
2408 loop_it.Advance()) {
2409 loop_it.Current()->Add(block);
2410 }
2411 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2412 loop_info->ReplaceBackEdge(reference, block);
2413 }
2414 }
2415
2416 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2417 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2418 ? reference->GetTryCatchInformation()
2419 : nullptr;
2420 block->SetTryCatchInformation(try_catch_info);
2421}
2422
Calin Juravle2e768302015-07-28 14:41:11 +00002423HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002424 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002425 // Update the environments in this graph to have the invoke's environment
2426 // as parent.
2427 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002428 // Skip the entry block, we do not need to update the entry's suspend check.
2429 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002430 for (HInstructionIterator instr_it(block->GetInstructions());
2431 !instr_it.Done();
2432 instr_it.Advance()) {
2433 HInstruction* current = instr_it.Current();
2434 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002435 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002436 current->GetEnvironment()->SetAndCopyParentChain(
Vladimir Markoca6fff82017-10-03 14:49:14 +01002437 outer_graph->GetAllocator(), invoke->GetEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002438 }
2439 }
2440 }
2441 }
2442 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002443
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002444 if (HasBoundsChecks()) {
2445 outer_graph->SetHasBoundsChecks(true);
2446 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002447 if (HasLoops()) {
2448 outer_graph->SetHasLoops(true);
2449 }
2450 if (HasIrreducibleLoops()) {
2451 outer_graph->SetHasIrreducibleLoops(true);
2452 }
Vladimir Markod3e9c622020-08-05 12:20:28 +01002453 if (HasDirectCriticalNativeCall()) {
2454 outer_graph->SetHasDirectCriticalNativeCall(true);
2455 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002456 if (HasTryCatch()) {
2457 outer_graph->SetHasTryCatch(true);
2458 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002459 if (HasSIMD()) {
2460 outer_graph->SetHasSIMD(true);
2461 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002462
Calin Juravle2e768302015-07-28 14:41:11 +00002463 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002464 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002465 // Inliner already made sure we don't inline methods that always throw.
2466 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002467 // Simple case of an entry block, a body block, and an exit block.
2468 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002469 HBasicBlock* body = GetBlocks()[1];
2470 DCHECK(GetBlocks()[0]->IsEntryBlock());
2471 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002472 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002473 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002474 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002475
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002476 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2477 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002478 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002479
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002480 // Replace the invoke with the return value of the inlined graph.
2481 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002482 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002483 } else {
2484 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002485 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002486
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002487 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002488 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002489 // Need to inline multiple blocks. We split `invoke`'s block
2490 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002491 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002492 // with the second half.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002493 ArenaAllocator* allocator = outer_graph->GetAllocator();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002494 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002495 // Note that we split before the invoke only to simplify polymorphic inlining.
2496 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002497
Vladimir Markoec7802a2015-10-01 20:57:57 +01002498 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002499 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002500 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002501 exit_block_->ReplaceWith(to);
2502
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002503 // Update the meta information surrounding blocks:
2504 // (1) the graph they are now in,
2505 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002506 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002507 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002508 // Note that we do not need to update catch phi inputs because they
2509 // correspond to the register file of the outer method which the inlinee
2510 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002511
2512 // We don't add the entry block, the exit block, and the first block, which
2513 // has been merged with `at`.
2514 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2515
2516 // We add the `to` block.
2517 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002518 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002519 + kNumberOfNewBlocksInCaller;
2520
2521 // Find the location of `at` in the outer graph's reverse post order. The new
2522 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002523 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002524 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2525
David Brazdil95177982015-10-30 12:56:58 -05002526 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2527 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002528 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002529 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002530 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002531 DCHECK(current->GetGraph() == this);
2532 current->SetGraph(outer_graph);
2533 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002534 outer_graph->reverse_post_order_[++index_of_at] = current;
Andreas Gampe3db70682018-12-26 15:12:03 -08002535 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge= */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002536 }
2537 }
2538
David Brazdil95177982015-10-30 12:56:58 -05002539 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002540 to->SetGraph(outer_graph);
2541 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002542 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002543 // Only `to` can become a back edge, as the inlined blocks
2544 // are predecessors of `to`.
Andreas Gampe3db70682018-12-26 15:12:03 -08002545 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge= */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002546
David Brazdil3f523062016-02-29 16:53:33 +00002547 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002548 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2549 // to now get the outer graph exit block as successor. Note that the inliner
2550 // currently doesn't support inlining methods with try/catch.
2551 HPhi* return_value_phi = nullptr;
2552 bool rerun_dominance = false;
2553 bool rerun_loop_analysis = false;
2554 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2555 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002556 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002557 if (last->IsThrow()) {
2558 DCHECK(!at->IsTryBlock());
2559 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2560 --pred;
2561 // We need to re-run dominance information, as the exit block now has
2562 // a new dominator.
2563 rerun_dominance = true;
2564 if (predecessor->GetLoopInformation() != nullptr) {
2565 // The exit block and blocks post dominated by the exit block do not belong
2566 // to any loop. Because we do not compute the post dominators, we need to re-run
2567 // loop analysis to get the loop information correct.
2568 rerun_loop_analysis = true;
2569 }
2570 } else {
2571 if (last->IsReturnVoid()) {
2572 DCHECK(return_value == nullptr);
2573 DCHECK(return_value_phi == nullptr);
2574 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002575 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002576 if (return_value_phi != nullptr) {
2577 return_value_phi->AddInput(last->InputAt(0));
2578 } else if (return_value == nullptr) {
2579 return_value = last->InputAt(0);
2580 } else {
2581 // There will be multiple returns.
2582 return_value_phi = new (allocator) HPhi(
2583 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2584 to->AddPhi(return_value_phi);
2585 return_value_phi->AddInput(return_value);
2586 return_value_phi->AddInput(last->InputAt(0));
2587 return_value = return_value_phi;
2588 }
David Brazdil3f523062016-02-29 16:53:33 +00002589 }
2590 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2591 predecessor->RemoveInstruction(last);
2592 }
2593 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002594 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002595 DCHECK(!outer_graph->HasIrreducibleLoops())
2596 << "Recomputing loop information in graphs with irreducible loops "
2597 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002598 outer_graph->ClearLoopInformation();
2599 outer_graph->ClearDominanceInformation();
2600 outer_graph->BuildDominatorTree();
2601 } else if (rerun_dominance) {
2602 outer_graph->ClearDominanceInformation();
2603 outer_graph->ComputeDominanceInformation();
2604 }
David Brazdil3f523062016-02-29 16:53:33 +00002605 }
David Brazdil05144f42015-04-16 15:18:00 +01002606
2607 // Walk over the entry block and:
2608 // - Move constants from the entry block to the outer_graph's entry block,
2609 // - Replace HParameterValue instructions with their real value.
2610 // - Remove suspend checks, that hold an environment.
2611 // We must do this after the other blocks have been inlined, otherwise ids of
2612 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002613 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002614 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2615 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002616 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002617 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002618 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002619 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002620 replacement = outer_graph->GetIntConstant(
2621 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002622 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002623 replacement = outer_graph->GetLongConstant(
2624 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002625 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002626 replacement = outer_graph->GetFloatConstant(
2627 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002628 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002629 replacement = outer_graph->GetDoubleConstant(
2630 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002631 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002632 if (kIsDebugBuild
2633 && invoke->IsInvokeStaticOrDirect()
2634 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2635 // Ensure we do not use the last input of `invoke`, as it
2636 // contains a clinit check which is not an actual argument.
2637 size_t last_input_index = invoke->InputCount() - 1;
2638 DCHECK(parameter_index != last_input_index);
2639 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002640 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002641 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002642 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002643 } else {
2644 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2645 entry_block_->RemoveInstruction(current);
2646 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002647 if (replacement != nullptr) {
2648 current->ReplaceWith(replacement);
2649 // If the current is the return value then we need to update the latter.
2650 if (current == return_value) {
2651 DCHECK_EQ(entry_block_, return_value->GetBlock());
2652 return_value = replacement;
2653 }
2654 }
2655 }
2656
Calin Juravle2e768302015-07-28 14:41:11 +00002657 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002658}
2659
Mingyao Yang3584bce2015-05-19 16:01:59 -07002660/*
2661 * Loop will be transformed to:
2662 * old_pre_header
2663 * |
2664 * if_block
2665 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002666 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002667 * \ /
2668 * new_pre_header
2669 * |
2670 * header
2671 */
2672void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2673 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002674 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002675
Aart Bik3fc7f352015-11-20 22:03:03 -08002676 // Need extra block to avoid critical edge.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002677 HBasicBlock* if_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2678 HBasicBlock* true_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2679 HBasicBlock* false_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2680 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002681 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002682 AddBlock(true_block);
2683 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002684 AddBlock(new_pre_header);
2685
Aart Bik3fc7f352015-11-20 22:03:03 -08002686 header->ReplacePredecessor(old_pre_header, new_pre_header);
2687 old_pre_header->successors_.clear();
2688 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002689
Aart Bik3fc7f352015-11-20 22:03:03 -08002690 old_pre_header->AddSuccessor(if_block);
2691 if_block->AddSuccessor(true_block); // True successor
2692 if_block->AddSuccessor(false_block); // False successor
2693 true_block->AddSuccessor(new_pre_header);
2694 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002695
Aart Bik3fc7f352015-11-20 22:03:03 -08002696 old_pre_header->dominated_blocks_.push_back(if_block);
2697 if_block->SetDominator(old_pre_header);
2698 if_block->dominated_blocks_.push_back(true_block);
2699 true_block->SetDominator(if_block);
2700 if_block->dominated_blocks_.push_back(false_block);
2701 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002702 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002703 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002704 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002705 header->SetDominator(new_pre_header);
2706
Aart Bik3fc7f352015-11-20 22:03:03 -08002707 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002708 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002709 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002710 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002711 reverse_post_order_[index_of_header++] = true_block;
2712 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002713 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002714
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002715 // The pre_header can never be a back edge of a loop.
2716 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2717 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2718 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08002719 if_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002720 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08002721 true_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002722 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08002723 false_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002724 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08002725 new_pre_header, old_pre_header, /* replace_if_back_edge= */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002726}
2727
Aart Bikf8f5a162017-02-06 15:35:29 -08002728HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2729 HBasicBlock* body,
2730 HBasicBlock* exit) {
2731 DCHECK(header->IsLoopHeader());
2732 HLoopInformation* loop = header->GetLoopInformation();
2733
2734 // Add new loop blocks.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002735 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2736 HBasicBlock* new_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2737 HBasicBlock* new_body = new (allocator_) HBasicBlock(this, header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002738 AddBlock(new_pre_header);
2739 AddBlock(new_header);
2740 AddBlock(new_body);
2741
2742 // Set up control flow.
2743 header->ReplaceSuccessor(exit, new_pre_header);
2744 new_pre_header->AddSuccessor(new_header);
2745 new_header->AddSuccessor(exit);
2746 new_header->AddSuccessor(new_body);
2747 new_body->AddSuccessor(new_header);
2748
2749 // Set up dominators.
2750 header->ReplaceDominatedBlock(exit, new_pre_header);
2751 new_pre_header->SetDominator(header);
2752 new_pre_header->dominated_blocks_.push_back(new_header);
2753 new_header->SetDominator(new_pre_header);
2754 new_header->dominated_blocks_.push_back(new_body);
2755 new_body->SetDominator(new_header);
2756 new_header->dominated_blocks_.push_back(exit);
2757 exit->SetDominator(new_header);
2758
2759 // Fix reverse post order.
2760 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2761 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2762 reverse_post_order_[++index_of_header] = new_pre_header;
2763 reverse_post_order_[++index_of_header] = new_header;
2764 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2765 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2766 reverse_post_order_[index_of_body] = new_body;
2767
Aart Bikb07d1bc2017-04-05 10:03:15 -07002768 // Add gotos and suspend check (client must add conditional in header).
Vladimir Markoca6fff82017-10-03 14:49:14 +01002769 new_pre_header->AddInstruction(new (allocator_) HGoto());
2770 HSuspendCheck* suspend_check = new (allocator_) HSuspendCheck(header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002771 new_header->AddInstruction(suspend_check);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002772 new_body->AddInstruction(new (allocator_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002773 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2774 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002775
2776 // Update loop information.
2777 new_header->AddBackEdge(new_body);
2778 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2779 new_header->GetLoopInformation()->Populate();
2780 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2781 HLoopInformationOutwardIterator it(*new_header);
2782 for (it.Advance(); !it.Done(); it.Advance()) {
2783 it.Current()->Add(new_pre_header);
2784 it.Current()->Add(new_header);
2785 it.Current()->Add(new_body);
2786 }
2787 return new_pre_header;
2788}
2789
David Brazdilf5552582015-12-27 13:36:12 +00002790static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002791 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002792 if (rti.IsValid()) {
2793 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2794 << " upper_bound_rti: " << upper_bound_rti
2795 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002796 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2797 << " upper_bound_rti: " << upper_bound_rti
2798 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002799 }
2800}
2801
Calin Juravle2e768302015-07-28 14:41:11 +00002802void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2803 if (kIsDebugBuild) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002804 DCHECK_EQ(GetType(), DataType::Type::kReference);
Calin Juravle2e768302015-07-28 14:41:11 +00002805 ScopedObjectAccess soa(Thread::Current());
2806 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2807 if (IsBoundType()) {
2808 // Having the test here spares us from making the method virtual just for
2809 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002810 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002811 }
2812 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002813 reference_type_handle_ = rti.GetTypeHandle();
2814 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002815}
2816
Artem Serov4d277ba2018-06-05 20:54:42 +01002817bool HBoundType::InstructionDataEquals(const HInstruction* other) const {
2818 const HBoundType* other_bt = other->AsBoundType();
2819 ScopedObjectAccess soa(Thread::Current());
2820 return GetUpperBound().IsEqual(other_bt->GetUpperBound()) &&
2821 GetUpperCanBeNull() == other_bt->GetUpperCanBeNull() &&
2822 CanBeNull() == other_bt->CanBeNull();
2823}
2824
David Brazdilf5552582015-12-27 13:36:12 +00002825void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2826 if (kIsDebugBuild) {
2827 ScopedObjectAccess soa(Thread::Current());
2828 DCHECK(upper_bound.IsValid());
2829 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2830 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2831 }
2832 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002833 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002834}
2835
Vladimir Markoa1de9182016-02-25 11:37:38 +00002836ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002837 if (kIsDebugBuild) {
2838 ScopedObjectAccess soa(Thread::Current());
2839 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002840 if (!is_exact) {
2841 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2842 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2843 }
Calin Juravle2e768302015-07-28 14:41:11 +00002844 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002845 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002846}
2847
Calin Juravleacf735c2015-02-12 15:25:22 +00002848std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2849 ScopedObjectAccess soa(Thread::Current());
2850 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002851 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002852 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002853 << " is_exact=" << rhs.IsExact()
2854 << " ]";
2855 return os;
2856}
2857
Mark Mendellc4701932015-04-10 13:18:51 -04002858bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2859 // For now, assume that instructions in different blocks may use the
2860 // environment.
2861 // TODO: Use the control flow to decide if this is true.
2862 if (GetBlock() != other->GetBlock()) {
2863 return true;
2864 }
2865
2866 // We know that we are in the same block. Walk from 'this' to 'other',
2867 // checking to see if there is any instruction with an environment.
2868 HInstruction* current = this;
2869 for (; current != other && current != nullptr; current = current->GetNext()) {
2870 // This is a conservative check, as the instruction result may not be in
2871 // the referenced environment.
2872 if (current->HasEnvironment()) {
2873 return true;
2874 }
2875 }
2876
2877 // We should have been called with 'this' before 'other' in the block.
2878 // Just confirm this.
2879 DCHECK(current != nullptr);
2880 return false;
2881}
2882
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002883void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002884 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2885 IntrinsicSideEffects side_effects,
2886 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002887 intrinsic_ = intrinsic;
2888 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002889
Aart Bik5d75afe2015-12-14 11:57:01 -08002890 // Adjust method's side effects from intrinsic table.
2891 switch (side_effects) {
2892 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2893 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2894 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2895 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2896 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002897
2898 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2899 opt.SetDoesNotNeedDexCache();
2900 opt.SetDoesNotNeedEnvironment();
2901 } else {
2902 // If we need an environment, that means there will be a call, which can trigger GC.
2903 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2904 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002905 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002906 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002907}
2908
David Brazdil6de19382016-01-08 17:37:10 +00002909bool HNewInstance::IsStringAlloc() const {
Alex Lightd109e302018-06-27 10:25:41 -07002910 return GetEntrypoint() == kQuickAllocStringObject;
David Brazdil6de19382016-01-08 17:37:10 +00002911}
2912
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002913bool HInvoke::NeedsEnvironment() const {
2914 if (!IsIntrinsic()) {
2915 return true;
2916 }
2917 IntrinsicOptimizations opt(*this);
2918 return !opt.GetDoesNotNeedEnvironment();
2919}
2920
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002921const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2922 ArtMethod* caller = GetEnvironment()->GetMethod();
2923 ScopedObjectAccess soa(Thread::Current());
2924 // `caller` is null for a top-level graph representing a method whose declaring
2925 // class was not resolved.
2926 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2927}
2928
Vladimir Markodc151b22015-10-15 18:02:30 +01002929bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002930 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002931 return false;
2932 }
2933 if (!IsIntrinsic()) {
2934 return true;
2935 }
2936 IntrinsicOptimizations opt(*this);
2937 return !opt.GetDoesNotNeedDexCache();
2938}
2939
Vladimir Markofbb184a2015-11-13 14:47:00 +00002940std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2941 switch (rhs) {
2942 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2943 return os << "explicit";
2944 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2945 return os << "implicit";
2946 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2947 return os << "none";
2948 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002949 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2950 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002951 }
2952}
2953
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002954bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2955 const HLoadClass* other_load_class = other->AsLoadClass();
2956 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2957 // names rather than type indexes. However, we shall also have to re-think the hash code.
2958 if (type_index_ != other_load_class->type_index_ ||
2959 GetPackedFields() != other_load_class->GetPackedFields()) {
2960 return false;
2961 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002962 switch (GetLoadKind()) {
Vladimir Markoe47f60c2018-02-21 13:43:28 +00002963 case LoadKind::kBootImageRelRo:
Vladimir Marko8e524ad2018-07-13 10:27:43 +01002964 case LoadKind::kJitBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002965 case LoadKind::kJitTableAddress: {
2966 ScopedObjectAccess soa(Thread::Current());
2967 return GetClass().Get() == other_load_class->GetClass().Get();
2968 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002969 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002970 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002971 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002972 }
2973}
2974
Vladimir Marko372f10e2016-05-17 16:30:10 +01002975bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2976 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002977 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2978 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002979 if (string_index_ != other_load_string->string_index_ ||
2980 GetPackedFields() != other_load_string->GetPackedFields()) {
2981 return false;
2982 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002983 switch (GetLoadKind()) {
Vladimir Markoe47f60c2018-02-21 13:43:28 +00002984 case LoadKind::kBootImageRelRo:
Vladimir Marko8e524ad2018-07-13 10:27:43 +01002985 case LoadKind::kJitBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002986 case LoadKind::kJitTableAddress: {
2987 ScopedObjectAccess soa(Thread::Current());
2988 return GetString().Get() == other_load_string->GetString().Get();
2989 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002990 default:
2991 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002992 }
2993}
2994
Mark Mendellc4701932015-04-10 13:18:51 -04002995void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002996 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2997 HEnvironment* user = use.GetUser();
2998 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002999 }
Vladimir Marko46817b82016-03-29 12:21:58 +01003000 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04003001}
3002
Artem Serovcced8ba2017-07-19 18:18:09 +01003003HInstruction* ReplaceInstrOrPhiByClone(HInstruction* instr) {
3004 HInstruction* clone = instr->Clone(instr->GetBlock()->GetGraph()->GetAllocator());
3005 HBasicBlock* block = instr->GetBlock();
3006
3007 if (instr->IsPhi()) {
3008 HPhi* phi = instr->AsPhi();
3009 DCHECK(!phi->HasEnvironment());
3010 HPhi* phi_clone = clone->AsPhi();
3011 block->ReplaceAndRemovePhiWith(phi, phi_clone);
3012 } else {
3013 block->ReplaceAndRemoveInstructionWith(instr, clone);
3014 if (instr->HasEnvironment()) {
3015 clone->CopyEnvironmentFrom(instr->GetEnvironment());
3016 HLoopInformation* loop_info = block->GetLoopInformation();
3017 if (instr->IsSuspendCheck() && loop_info != nullptr) {
3018 loop_info->SetSuspendCheck(clone->AsSuspendCheck());
3019 }
3020 }
3021 }
3022 return clone;
3023}
3024
Roland Levillainc9b21f82016-03-23 16:36:59 +00003025// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05003026HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01003027 ArenaAllocator* allocator = GetAllocator();
Mark Mendellf6529172015-11-17 11:16:56 -05003028
3029 if (cond->IsCondition() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003030 !DataType::IsFloatingPointType(cond->InputAt(0)->GetType())) {
Mark Mendellf6529172015-11-17 11:16:56 -05003031 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
3032 HInstruction* lhs = cond->InputAt(0);
3033 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00003034 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05003035 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
3036 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
3037 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
3038 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
3039 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
3040 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
3041 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
3042 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
3043 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
3044 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
3045 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00003046 default:
3047 LOG(FATAL) << "Unexpected condition";
3048 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05003049 }
3050 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3051 return replacement;
3052 } else if (cond->IsIntConstant()) {
3053 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00003054 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05003055 return GetIntConstant(1);
3056 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00003057 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05003058 return GetIntConstant(0);
3059 }
3060 } else {
3061 HInstruction* replacement = new (allocator) HBooleanNot(cond);
3062 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3063 return replacement;
3064 }
3065}
3066
Roland Levillainc9285912015-12-18 10:38:42 +00003067std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
3068 os << "["
3069 << " source=" << rhs.GetSource()
3070 << " destination=" << rhs.GetDestination()
3071 << " type=" << rhs.GetType()
3072 << " instruction=";
3073 if (rhs.GetInstruction() != nullptr) {
3074 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
3075 } else {
3076 os << "null";
3077 }
3078 os << " ]";
3079 return os;
3080}
3081
Roland Levillain86503782016-02-11 19:07:30 +00003082std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
3083 switch (rhs) {
3084 case TypeCheckKind::kUnresolvedCheck:
3085 return os << "unresolved_check";
3086 case TypeCheckKind::kExactCheck:
3087 return os << "exact_check";
3088 case TypeCheckKind::kClassHierarchyCheck:
3089 return os << "class_hierarchy_check";
3090 case TypeCheckKind::kAbstractClassCheck:
3091 return os << "abstract_class_check";
3092 case TypeCheckKind::kInterfaceCheck:
3093 return os << "interface_check";
3094 case TypeCheckKind::kArrayObjectCheck:
3095 return os << "array_object_check";
3096 case TypeCheckKind::kArrayCheck:
3097 return os << "array_check";
Vladimir Marko175e7862018-03-27 09:03:13 +00003098 case TypeCheckKind::kBitstringCheck:
3099 return os << "bitstring_check";
Roland Levillain86503782016-02-11 19:07:30 +00003100 default:
3101 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
3102 UNREACHABLE();
3103 }
3104}
3105
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003106// Check that intrinsic enum values fit within space set aside in ArtMethod modifier flags.
3107#define CHECK_INTRINSICS_ENUM_VALUES(Name, InvokeType, _, SideEffects, Exceptions, ...) \
3108 static_assert( \
3109 static_cast<uint32_t>(Intrinsics::k ## Name) <= (kAccIntrinsicBits >> CTZ(kAccIntrinsicBits)), \
3110 "Instrinsics enumeration space overflow.");
3111#include "intrinsics_list.h"
3112 INTRINSICS_LIST(CHECK_INTRINSICS_ENUM_VALUES)
3113#undef INTRINSICS_LIST
3114#undef CHECK_INTRINSICS_ENUM_VALUES
3115
3116// Function that returns whether an intrinsic needs an environment or not.
3117static inline IntrinsicNeedsEnvironmentOrCache NeedsEnvironmentOrCacheIntrinsic(Intrinsics i) {
3118 switch (i) {
3119 case Intrinsics::kNone:
3120 return kNeedsEnvironmentOrCache; // Non-sensical for intrinsic.
3121#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnvOrCache, SideEffects, Exceptions, ...) \
3122 case Intrinsics::k ## Name: \
3123 return NeedsEnvOrCache;
3124#include "intrinsics_list.h"
3125 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3126#undef INTRINSICS_LIST
3127#undef OPTIMIZING_INTRINSICS
3128 }
3129 return kNeedsEnvironmentOrCache;
3130}
3131
3132// Function that returns whether an intrinsic has side effects.
3133static inline IntrinsicSideEffects GetSideEffectsIntrinsic(Intrinsics i) {
3134 switch (i) {
3135 case Intrinsics::kNone:
3136 return kAllSideEffects;
3137#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnvOrCache, SideEffects, Exceptions, ...) \
3138 case Intrinsics::k ## Name: \
3139 return SideEffects;
3140#include "intrinsics_list.h"
3141 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3142#undef INTRINSICS_LIST
3143#undef OPTIMIZING_INTRINSICS
3144 }
3145 return kAllSideEffects;
3146}
3147
3148// Function that returns whether an intrinsic can throw exceptions.
3149static inline IntrinsicExceptions GetExceptionsIntrinsic(Intrinsics i) {
3150 switch (i) {
3151 case Intrinsics::kNone:
3152 return kCanThrow;
3153#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnvOrCache, SideEffects, Exceptions, ...) \
3154 case Intrinsics::k ## Name: \
3155 return Exceptions;
3156#include "intrinsics_list.h"
3157 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3158#undef INTRINSICS_LIST
3159#undef OPTIMIZING_INTRINSICS
3160 }
3161 return kCanThrow;
3162}
3163
3164void HInvoke::SetResolvedMethod(ArtMethod* method) {
Andra Danciua0130e82020-07-23 12:34:56 +00003165 if (method != nullptr && method->IsIntrinsic()) {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003166 Intrinsics intrinsic = static_cast<Intrinsics>(method->GetIntrinsic());
3167 SetIntrinsic(intrinsic,
3168 NeedsEnvironmentOrCacheIntrinsic(intrinsic),
3169 GetSideEffectsIntrinsic(intrinsic),
3170 GetExceptionsIntrinsic(intrinsic));
3171 }
3172 resolved_method_ = method;
3173}
3174
Evgeny Astigeevichaf92a0f2020-06-26 13:28:33 +01003175bool IsGEZero(HInstruction* instruction) {
3176 DCHECK(instruction != nullptr);
3177 if (instruction->IsArrayLength()) {
3178 return true;
3179 } else if (instruction->IsMin()) {
3180 // Instruction MIN(>=0, >=0) is >= 0.
3181 return IsGEZero(instruction->InputAt(0)) &&
3182 IsGEZero(instruction->InputAt(1));
3183 } else if (instruction->IsAbs()) {
3184 // Instruction ABS(>=0) is >= 0.
3185 // NOTE: ABS(minint) = minint prevents assuming
3186 // >= 0 without looking at the argument.
3187 return IsGEZero(instruction->InputAt(0));
3188 }
3189 int64_t value = -1;
3190 return IsInt64AndGet(instruction, &value) && value >= 0;
3191}
3192
Nicolas Geoffray818f2102014-02-18 16:43:35 +00003193} // namespace art