blob: 0e858388620cde6a62f7a29a514e198febf64157 [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
Alex Light86fe9b82020-11-16 16:54:01 +000018#include <algorithm>
Roland Levillain31dd3d62016-02-16 12:21:02 +000019#include <cfloat>
Alex Lightdc281e72021-01-06 12:35:31 -080020#include <functional>
Roland Levillain31dd3d62016-02-16 12:21:02 +000021
Andreas Gampec6ea7d02017-02-01 16:46:28 -080022#include "art_method-inl.h"
Alex Light86fe9b82020-11-16 16:54:01 +000023#include "base/arena_allocator.h"
24#include "base/arena_bit_vector.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070025#include "base/bit_utils.h"
26#include "base/bit_vector-inl.h"
Alex Light86fe9b82020-11-16 16:54:01 +000027#include "base/bit_vector.h"
28#include "base/iteration_range.h"
Andreas Gampe85f1c572018-11-21 13:52:48 -080029#include "base/logging.h"
Vladimir Markodac82392021-05-10 15:44:24 +000030#include "base/malloc_arena_pool.h"
Alex Light86fe9b82020-11-16 16:54:01 +000031#include "base/scoped_arena_allocator.h"
32#include "base/scoped_arena_containers.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070033#include "base/stl_util.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080034#include "class_linker-inl.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010035#include "class_root-inl.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040036#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000037#include "common_dominator.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010038#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010039#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070040#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070041#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000042
VladimĂ­r Marko434d9682022-11-04 14:04:17 +000043namespace art HIDDEN {
Nicolas Geoffray818f2102014-02-18 16:43:35 +000044
Roland Levillain31dd3d62016-02-16 12:21:02 +000045// Enable floating-point static evaluation during constant folding
46// only if all floating-point operations and constants evaluate in the
47// range and precision of the type used (i.e., 32-bit float, 64-bit
48// double).
49static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
50
Vladimir Marko02ca05a2020-05-12 13:58:51 +010051ReferenceTypeInfo::TypeHandle HandleCache::CreateRootHandle(VariableSizedHandleScope* handles,
52 ClassRoot class_root) {
53 // Mutator lock is required for NewHandle and GetClassRoot().
David Brazdilbadd8262016-02-02 16:28:56 +000054 ScopedObjectAccess soa(Thread::Current());
Vladimir Marko02ca05a2020-05-12 13:58:51 +010055 return handles->NewHandle(GetClassRoot(class_root));
David Brazdilbadd8262016-02-02 16:28:56 +000056}
57
Nicolas Geoffray818f2102014-02-18 16:43:35 +000058void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010059 block->SetBlockId(blocks_.size());
60 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000061}
62
Nicolas Geoffray804d0932014-05-02 08:46:00 +010063void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
65 DCHECK_EQ(visited->GetHighestBitSet(), -1);
66
Vladimir Marko69d310e2017-10-09 14:12:23 +010067 // Allocate memory from local ScopedArenaAllocator.
68 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Marko1f8695c2015-09-24 13:11:31 +010069 // Nodes that we're currently visiting, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +010070 ArenaBitVector visiting(
Andreas Gampe3db70682018-12-26 15:12:03 -080071 &allocator, blocks_.size(), /* expandable= */ false, kArenaAllocGraphBuilder);
Vladimir Marko69d310e2017-10-09 14:12:23 +010072 visiting.ClearAllBits();
Vladimir Marko1f8695c2015-09-24 13:11:31 +010073 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +010074 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
75 0u,
76 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010077 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko69d310e2017-10-09 14:12:23 +010078 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010079 constexpr size_t kDefaultWorklistSize = 8;
80 worklist.reserve(kDefaultWorklistSize);
81 visited->SetBit(entry_block_->GetBlockId());
82 visiting.SetBit(entry_block_->GetBlockId());
83 worklist.push_back(entry_block_);
84
85 while (!worklist.empty()) {
86 HBasicBlock* current = worklist.back();
87 uint32_t current_id = current->GetBlockId();
88 if (successors_visited[current_id] == current->GetSuccessors().size()) {
89 visiting.ClearBit(current_id);
90 worklist.pop_back();
91 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010092 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
93 uint32_t successor_id = successor->GetBlockId();
94 if (visiting.IsBitSet(successor_id)) {
95 DCHECK(ContainsElement(worklist, successor));
96 successor->AddBackEdge(current);
97 } else if (!visited->IsBitSet(successor_id)) {
98 visited->SetBit(successor_id);
99 visiting.SetBit(successor_id);
100 worklist.push_back(successor);
101 }
102 }
103 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000104}
105
Artem Serov21c7e6f2017-07-27 16:04:42 +0100106// Remove the environment use records of the instruction for users.
107void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +0100108 for (HEnvironment* environment = instruction->GetEnvironment();
109 environment != nullptr;
110 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000111 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +0000112 if (environment->GetInstructionAt(i) != nullptr) {
113 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000114 }
115 }
116 }
117}
118
Artem Serov21c7e6f2017-07-27 16:04:42 +0100119// Return whether the instruction has an environment and it's used by others.
120bool HasEnvironmentUsedByOthers(HInstruction* instruction) {
121 for (HEnvironment* environment = instruction->GetEnvironment();
122 environment != nullptr;
123 environment = environment->GetParent()) {
124 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
125 HInstruction* user = environment->GetInstructionAt(i);
126 if (user != nullptr) {
127 return true;
128 }
129 }
130 }
131 return false;
132}
133
134// Reset environment records of the instruction itself.
135void ResetEnvironmentInputRecords(HInstruction* instruction) {
136 for (HEnvironment* environment = instruction->GetEnvironment();
137 environment != nullptr;
138 environment = environment->GetParent()) {
139 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
140 DCHECK(environment->GetHolder() == instruction);
141 if (environment->GetInstructionAt(i) != nullptr) {
142 environment->SetRawEnvAt(i, nullptr);
143 }
144 }
145 }
146}
147
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000148static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100149 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000150 RemoveEnvironmentUses(instruction);
151}
152
Santiago Aboy Solanes65fd6a32022-08-22 13:12:46 +0100153void HGraph::RemoveDeadBlocksInstructionsAsUsersAndDisconnect(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100154 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000155 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100156 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000157 if (block == nullptr) continue;
Santiago Aboy Solanes65fd6a32022-08-22 13:12:46 +0100158
159 // Remove as user.
Nicolas Geoffray2cc9d342019-04-26 14:21:14 +0100160 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
161 RemoveAsUser(it.Current());
162 }
Roland Levillainfc600dc2014-12-02 17:16:31 +0000163 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
164 RemoveAsUser(it.Current());
165 }
Santiago Aboy Solanes65fd6a32022-08-22 13:12:46 +0100166
167 // Remove non-catch phi uses, and disconnect the block.
168 block->DisconnectFromSuccessors(&visited);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000169 }
170 }
171}
172
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +0100173// This method assumes `insn` has been removed from all users with the exception of catch
174// phis because of missing exceptional edges in the graph. It removes the
175// instruction from catch phi uses, together with inputs of other catch phis in
176// the catch block at the same index, as these must be dead too.
177static void RemoveCatchPhiUsesOfDeadInstruction(HInstruction* insn) {
178 DCHECK(!insn->HasEnvironmentUses());
179 while (insn->HasNonEnvironmentUses()) {
180 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
181 size_t use_index = use.GetIndex();
182 HBasicBlock* user_block = use.GetUser()->GetBlock();
Santiago Aboy Solanes65fd6a32022-08-22 13:12:46 +0100183 DCHECK(use.GetUser()->IsPhi());
184 DCHECK(user_block->IsCatchBlock());
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +0100185 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
186 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
187 }
188 }
189}
190
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100191void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +0100192 DCHECK(reverse_post_order_.empty()) << "We shouldn't have dominance information.";
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100193 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000194 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100195 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000196 if (block == nullptr) continue;
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +0100197
Santiago Aboy Solanes65fd6a32022-08-22 13:12:46 +0100198 // Remove all remaining uses (which should be only catch phi uses), and the instructions.
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +0100199 block->RemoveCatchPhiUsesAndInstruction(/* building_dominator_tree = */ true);
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +0100200
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100201 // Remove the block from the list of blocks, so that further analyses
202 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100203 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600204 if (block->IsExitBlock()) {
205 SetExitBlock(nullptr);
206 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000207 // Mark the block as removed. This is used by the HGraphBuilder to discard
208 // the block as a branch target.
209 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000210 }
211 }
212}
213
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000214GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Marko69d310e2017-10-09 14:12:23 +0100215 // Allocate memory from local ScopedArenaAllocator.
216 ScopedArenaAllocator allocator(GetArenaStack());
217
218 ArenaBitVector visited(&allocator, blocks_.size(), false, kArenaAllocGraphBuilder);
219 visited.ClearAllBits();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000220
David Brazdil86ea7ee2016-02-16 09:26:07 +0000221 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000222 FindBackEdges(&visited);
223
David Brazdil86ea7ee2016-02-16 09:26:07 +0000224 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000225 // the initial DFS as users from other instructions, so that
226 // users can be safely removed before uses later.
Santiago Aboy Solanes65fd6a32022-08-22 13:12:46 +0100227 // Also disconnect the block from its successors, updating the successor's phis if needed.
228 RemoveDeadBlocksInstructionsAsUsersAndDisconnect(visited);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000229
David Brazdil86ea7ee2016-02-16 09:26:07 +0000230 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000231 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000232 // predecessors list of live blocks.
233 RemoveDeadBlocks(visited);
234
David Brazdil86ea7ee2016-02-16 09:26:07 +0000235 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100236 // dominators and the reverse post order.
237 SimplifyCFG();
238
David Brazdil86ea7ee2016-02-16 09:26:07 +0000239 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100240 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000241
David Brazdil86ea7ee2016-02-16 09:26:07 +0000242 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000243 // set the loop information on each block.
244 GraphAnalysisResult result = AnalyzeLoops();
245 if (result != kAnalysisSuccess) {
246 return result;
247 }
248
David Brazdil86ea7ee2016-02-16 09:26:07 +0000249 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000250 // which needs the information to build catch block phis from values of
251 // locals at throwing instructions inside try blocks.
252 ComputeTryBlockInformation();
253
254 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100255}
256
257void HGraph::ClearDominanceInformation() {
Alex Light210a78d2020-11-30 16:58:05 -0800258 for (HBasicBlock* block : GetActiveBlocks()) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100259 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100260 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100261 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100262}
263
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000264void HGraph::ClearLoopInformation() {
265 SetHasIrreducibleLoops(false);
Alex Light210a78d2020-11-30 16:58:05 -0800266 for (HBasicBlock* block : GetActiveBlocks()) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100267 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000268 }
269}
270
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100271void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000272 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100273 dominator_ = nullptr;
274}
275
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000276HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
277 HInstruction* instruction = GetFirstInstruction();
278 while (instruction->IsParallelMove()) {
279 instruction = instruction->GetNext();
280 }
281 return instruction;
282}
283
David Brazdil3f4a5222016-05-06 12:46:21 +0100284static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
285 DCHECK(ContainsElement(block->GetSuccessors(), successor));
286
287 HBasicBlock* old_dominator = successor->GetDominator();
288 HBasicBlock* new_dominator =
289 (old_dominator == nullptr) ? block
290 : CommonDominator::ForPair(old_dominator, block);
291
292 if (old_dominator == new_dominator) {
293 return false;
294 } else {
295 successor->SetDominator(new_dominator);
296 return true;
297 }
298}
299
Alex Light86fe9b82020-11-16 16:54:01 +0000300// TODO Consider moving this entirely into LoadStoreAnalysis/Elimination.
301bool HGraph::PathBetween(uint32_t source_idx, uint32_t dest_idx) const {
302 DCHECK_LT(source_idx, blocks_.size()) << "source not present in graph!";
303 DCHECK_LT(dest_idx, blocks_.size()) << "dest not present in graph!";
304 DCHECK(blocks_[source_idx] != nullptr);
305 DCHECK(blocks_[dest_idx] != nullptr);
306 return reachability_graph_.IsBitSet(source_idx, dest_idx);
307}
308
309bool HGraph::PathBetween(const HBasicBlock* source, const HBasicBlock* dest) const {
310 if (source == nullptr || dest == nullptr) {
311 return false;
312 }
313 size_t source_idx = source->GetBlockId();
314 size_t dest_idx = dest->GetBlockId();
315 return PathBetween(source_idx, dest_idx);
316}
317
318// This function/struct calculates the reachability of every node from every
319// other node by iteratively using DFS to find reachability of each individual
320// block.
321//
322// This is in practice faster then the simpler Floyd-Warshall since while that
323// is O(N**3) this is O(N*(E + N)) where N is the number of blocks and E is the
324// number of edges. Since in practice each block only has a few outgoing edges
325// we can confidently say that E ~ B*N where B is a small number (~3). We also
326// memoize the results as we go allowing us to (potentially) avoid walking the
327// entire graph for every node. To make best use of this memoization we
328// calculate the reachability of blocks in PostOrder. This means that
329// (generally) blocks that are dominated by many other blocks and dominate few
330// blocks themselves will be examined first. This makes it more likely we can
331// use our memoized results.
332class ReachabilityAnalysisHelper {
333 public:
334 ReachabilityAnalysisHelper(const HGraph* graph,
335 ArenaBitVectorArray* reachability_graph,
336 ArenaStack* arena_stack)
337 : graph_(graph),
338 reachability_graph_(reachability_graph),
339 arena_stack_(arena_stack),
340 temporaries_(arena_stack_),
341 block_size_(RoundUp(graph_->GetBlocks().size(), BitVector::kWordBits)),
342 all_visited_nodes_(
343 &temporaries_, graph_->GetBlocks().size(), false, kArenaAllocReachabilityGraph),
344 not_post_order_visited_(
345 &temporaries_, graph_->GetBlocks().size(), false, kArenaAllocReachabilityGraph) {
346 // We can't adjust the size of reachability graph any more without breaking
347 // our allocator invariants so it had better be large enough.
348 CHECK_GE(reachability_graph_->NumRows(), graph_->GetBlocks().size());
349 CHECK_GE(reachability_graph_->NumColumns(), graph_->GetBlocks().size());
350 not_post_order_visited_.SetInitialBits(graph_->GetBlocks().size());
351 }
352
353 void CalculateReachability() {
354 // Calculate what blocks connect using repeated DFS
355 //
356 // Going in PostOrder should generally give memoization a good shot of
357 // hitting.
358 for (const HBasicBlock* blk : graph_->GetPostOrder()) {
359 if (blk == nullptr) {
360 continue;
361 }
362 not_post_order_visited_.ClearBit(blk->GetBlockId());
363 CalculateConnectednessOn(blk);
364 all_visited_nodes_.SetBit(blk->GetBlockId());
365 }
366 // Get all other bits
367 for (auto idx : not_post_order_visited_.Indexes()) {
368 const HBasicBlock* blk = graph_->GetBlocks()[idx];
369 if (blk == nullptr) {
370 continue;
371 }
372 CalculateConnectednessOn(blk);
373 all_visited_nodes_.SetBit(blk->GetBlockId());
374 }
375 }
376
377 private:
378 void AddEdge(uint32_t source, const HBasicBlock* dest) {
379 reachability_graph_->SetBit(source, dest->GetBlockId());
380 }
381
382 // Union the reachability of 'idx' into 'update_block_idx'. This is done to
383 // implement memoization. In order to improve performance we do this in 4-byte
384 // blocks. Clang should be able to optimize this to larger blocks if possible.
385 void UnionBlock(size_t update_block_idx, size_t idx) {
386 reachability_graph_->UnionRows(update_block_idx, idx);
387 }
388
389 // Single DFS to get connectedness of a single block
390 void CalculateConnectednessOn(const HBasicBlock* const target_block) {
391 const uint32_t target_idx = target_block->GetBlockId();
392 ScopedArenaAllocator connectedness_temps(arena_stack_);
393 // What nodes we have already discovered and either have processed or are
394 // already on the queue.
395 ArenaBitVector discovered(
396 &connectedness_temps, graph_->GetBlocks().size(), false, kArenaAllocReachabilityGraph);
397 // The work stack. What blocks we still need to process.
398 ScopedArenaVector<const HBasicBlock*> work_stack(
399 connectedness_temps.Adapter(kArenaAllocReachabilityGraph));
400 // Known max size since otherwise we'd have blocks multiple times. Avoids
401 // re-allocation
402 work_stack.reserve(graph_->GetBlocks().size());
403 discovered.SetBit(target_idx);
404 work_stack.push_back(target_block);
405 // Main DFS Loop.
406 while (!work_stack.empty()) {
407 const HBasicBlock* cur = work_stack.back();
408 work_stack.pop_back();
409 // Memoization of previous runs.
410 if (all_visited_nodes_.IsBitSet(cur->GetBlockId())) {
411 DCHECK_NE(target_block, cur);
412 // Already explored from here. Just use that data.
413 UnionBlock(target_idx, cur->GetBlockId());
414 continue;
415 }
416 for (const HBasicBlock* succ : cur->GetSuccessors()) {
417 AddEdge(target_idx, succ);
418 if (!discovered.IsBitSet(succ->GetBlockId())) {
419 work_stack.push_back(succ);
420 discovered.SetBit(succ->GetBlockId());
421 }
422 }
423 }
424 }
425
426 const HGraph* graph_;
427 // The graph's reachability_graph_ on the main allocator.
428 ArenaBitVectorArray* reachability_graph_;
429 ArenaStack* arena_stack_;
430 // An allocator for temporary bit-vectors used by this algorithm. The
431 // 'SetBit,ClearBit' on reachability_graph_ prior to the construction of this
432 // object should be the only allocation on the main allocator so it's safe to
433 // make a sub-allocator here.
434 ScopedArenaAllocator temporaries_;
435 // number of columns
436 const size_t block_size_;
437 // Where we've already completely calculated connectedness.
438 ArenaBitVector all_visited_nodes_;
439 // What we never visited and need to do later
440 ArenaBitVector not_post_order_visited_;
441
442 DISALLOW_COPY_AND_ASSIGN(ReachabilityAnalysisHelper);
443};
444
445void HGraph::ComputeReachabilityInformation() {
446 DCHECK_EQ(reachability_graph_.GetRawData().NumSetBits(), 0u);
447 DCHECK(reachability_graph_.IsExpandable());
448 // Reserve all the bits we'll need. This is the only allocation on the
449 // standard allocator we do here, enabling us to create a new ScopedArena for
450 // use with temporaries.
451 //
452 // reachability_graph_ acts as |N| x |N| graph for PathBetween. Array is
453 // padded so each row starts on an BitVector::kWordBits-bit alignment for
454 // simplicity and performance, allowing us to union blocks together without
455 // going bit-by-bit.
456 reachability_graph_.Resize(blocks_.size(), blocks_.size(), /*clear=*/false);
457 ReachabilityAnalysisHelper helper(this, &reachability_graph_, GetArenaStack());
458 helper.CalculateReachability();
459}
460
461void HGraph::ClearReachabilityInformation() {
462 reachability_graph_.Clear();
463}
464
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100465void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100466 DCHECK(reverse_post_order_.empty());
467 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100468 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100469
Vladimir Marko69d310e2017-10-09 14:12:23 +0100470 // Allocate memory from local ScopedArenaAllocator.
471 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Markod76d1392015-09-23 16:07:14 +0100472 // Number of visits of a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100473 ScopedArenaVector<size_t> visits(blocks_.size(), 0u, allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100474 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100475 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
476 0u,
477 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100478 // Nodes for which we need to visit successors.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100479 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100480 constexpr size_t kDefaultWorklistSize = 8;
481 worklist.reserve(kDefaultWorklistSize);
482 worklist.push_back(entry_block_);
483
484 while (!worklist.empty()) {
485 HBasicBlock* current = worklist.back();
486 uint32_t current_id = current->GetBlockId();
487 if (successors_visited[current_id] == current->GetSuccessors().size()) {
488 worklist.pop_back();
489 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100490 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100491 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100492
493 // Once all the forward edges have been visited, we know the immediate
494 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100495 if (++visits[successor->GetBlockId()] ==
496 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100497 reverse_post_order_.push_back(successor);
498 worklist.push_back(successor);
499 }
500 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000501 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000502
David Brazdil3f4a5222016-05-06 12:46:21 +0100503 // Check if the graph has back edges not dominated by their respective headers.
504 // If so, we need to update the dominators of those headers and recursively of
505 // their successors. We do that with a fix-point iteration over all blocks.
506 // The algorithm is guaranteed to terminate because it loops only if the sum
507 // of all dominator chains has decreased in the current iteration.
508 bool must_run_fix_point = false;
509 for (HBasicBlock* block : blocks_) {
510 if (block != nullptr &&
511 block->IsLoopHeader() &&
512 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
513 must_run_fix_point = true;
514 break;
515 }
516 }
517 if (must_run_fix_point) {
518 bool update_occurred = true;
519 while (update_occurred) {
520 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100521 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100522 for (HBasicBlock* successor : block->GetSuccessors()) {
523 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
524 }
525 }
526 }
527 }
528
529 // Make sure that there are no remaining blocks whose dominator information
530 // needs to be updated.
531 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100532 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100533 for (HBasicBlock* successor : block->GetSuccessors()) {
534 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
535 }
536 }
537 }
538
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000539 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000540 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100541 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000542 if (!block->IsEntryBlock()) {
543 block->GetDominator()->AddDominatedBlock(block);
544 }
545 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000546}
547
David Brazdilfc6a86a2015-06-26 10:33:45 +0000548HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100549 HBasicBlock* new_block = new (allocator_) HBasicBlock(this, successor->GetDexPc());
David Brazdil3e187382015-06-26 09:59:52 +0000550 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000551 // Use `InsertBetween` to ensure the predecessor index and successor index of
552 // `block` and `successor` are preserved.
553 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000554 return new_block;
555}
556
557void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
558 // Insert a new node between `block` and `successor` to split the
559 // critical edge.
560 HBasicBlock* new_block = SplitEdge(block, successor);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100561 new_block->AddInstruction(new (allocator_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100562 if (successor->IsLoopHeader()) {
563 // If we split at a back edge boundary, make the new block the back edge.
564 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000565 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100566 info->RemoveBackEdge(block);
567 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100568 }
569 }
570}
571
Santiago Aboy Solanes31242a92022-12-05 14:38:00 +0000572HBasicBlock* HGraph::SplitEdgeAndUpdateRPO(HBasicBlock* block, HBasicBlock* successor) {
573 HBasicBlock* new_block = SplitEdge(block, successor);
574 // In the RPO we have {... , block, ... , successor}. We want to insert `new_block` right after
575 // `block` to have a consistent RPO without recomputing the whole graph's RPO.
576 reverse_post_order_.insert(
577 reverse_post_order_.begin() + IndexOfElement(reverse_post_order_, block) + 1, new_block);
578 return new_block;
579}
580
Artem Serovc73ee372017-07-31 15:08:40 +0100581// Reorder phi inputs to match reordering of the block's predecessors.
582static void FixPhisAfterPredecessorsReodering(HBasicBlock* block, size_t first, size_t second) {
583 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
584 HPhi* phi = it.Current()->AsPhi();
585 HInstruction* first_instr = phi->InputAt(first);
586 HInstruction* second_instr = phi->InputAt(second);
587 phi->ReplaceInput(first_instr, second);
588 phi->ReplaceInput(second_instr, first);
589 }
590}
591
592// Make sure that the first predecessor of a loop header is the incoming block.
593void HGraph::OrderLoopHeaderPredecessors(HBasicBlock* header) {
594 DCHECK(header->IsLoopHeader());
595 HLoopInformation* info = header->GetLoopInformation();
596 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
597 HBasicBlock* to_swap = header->GetPredecessors()[0];
598 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
599 HBasicBlock* predecessor = header->GetPredecessors()[pred];
600 if (!info->IsBackEdge(*predecessor)) {
601 header->predecessors_[pred] = to_swap;
602 header->predecessors_[0] = predecessor;
603 FixPhisAfterPredecessorsReodering(header, 0, pred);
604 break;
605 }
606 }
607 }
608}
609
Artem Serov09faaea2017-12-07 14:36:01 +0000610// Transform control flow of the loop to a single preheader format (don't touch the data flow).
611// New_preheader can be already among the header predecessors - this situation will be correctly
612// processed.
613static void FixControlForNewSinglePreheader(HBasicBlock* header, HBasicBlock* new_preheader) {
614 HLoopInformation* loop_info = header->GetLoopInformation();
615 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
616 HBasicBlock* predecessor = header->GetPredecessors()[pred];
617 if (!loop_info->IsBackEdge(*predecessor) && predecessor != new_preheader) {
618 predecessor->ReplaceSuccessor(header, new_preheader);
619 pred--;
620 }
621 }
622}
623
624// == Before == == After ==
625// _________ _________ _________ _________
626// | B0 | | B1 | (old preheaders) | B0 | | B1 |
627// |=========| |=========| |=========| |=========|
628// | i0 = .. | | i1 = .. | | i0 = .. | | i1 = .. |
629// |_________| |_________| |_________| |_________|
630// \ / \ /
631// \ / ___v____________v___
632// \ / (new preheader) | B20 <- B0, B1 |
633// | | |====================|
634// | | | i20 = phi(i0, i1) |
635// | | |____________________|
636// | | |
637// /\ | | /\ /\ | /\
638// / v_______v_________v_______v \ / v___________v_____________v \
639// | | B10 <- B0, B1, B2, B3 | | | | B10 <- B20, B2, B3 | |
640// | |===========================| | (header) | |===========================| |
641// | | i10 = phi(i0, i1, i2, i3) | | | | i10 = phi(i20, i2, i3) | |
642// | |___________________________| | | |___________________________| |
643// | / \ | | / \ |
644// | ... ... | | ... ... |
645// | _________ _________ | | _________ _________ |
646// | | B2 | | B3 | | | | B2 | | B3 | |
647// | |=========| |=========| | (back edges) | |=========| |=========| |
648// | | i2 = .. | | i3 = .. | | | | i2 = .. | | i3 = .. | |
649// | |_________| |_________| | | |_________| |_________| |
650// \ / \ / \ / \ /
651// \___/ \___/ \___/ \___/
652//
653void HGraph::TransformLoopToSinglePreheaderFormat(HBasicBlock* header) {
654 HLoopInformation* loop_info = header->GetLoopInformation();
655
656 HBasicBlock* preheader = new (allocator_) HBasicBlock(this, header->GetDexPc());
657 AddBlock(preheader);
658 preheader->AddInstruction(new (allocator_) HGoto(header->GetDexPc()));
659
660 // If the old header has no Phis then we only need to fix the control flow.
661 if (header->GetPhis().IsEmpty()) {
662 FixControlForNewSinglePreheader(header, preheader);
663 preheader->AddSuccessor(header);
664 return;
665 }
666
667 // Find the first non-back edge block in the header's predecessors list.
668 size_t first_nonbackedge_pred_pos = 0;
669 bool found = false;
670 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
671 HBasicBlock* predecessor = header->GetPredecessors()[pred];
672 if (!loop_info->IsBackEdge(*predecessor)) {
673 first_nonbackedge_pred_pos = pred;
674 found = true;
675 break;
676 }
677 }
678
679 DCHECK(found);
680
681 // Fix the data-flow.
682 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
683 HPhi* header_phi = it.Current()->AsPhi();
684
685 HPhi* preheader_phi = new (GetAllocator()) HPhi(GetAllocator(),
686 header_phi->GetRegNumber(),
687 0,
688 header_phi->GetType());
689 if (header_phi->GetType() == DataType::Type::kReference) {
690 preheader_phi->SetReferenceTypeInfo(header_phi->GetReferenceTypeInfo());
691 }
692 preheader->AddPhi(preheader_phi);
693
694 HInstruction* orig_input = header_phi->InputAt(first_nonbackedge_pred_pos);
695 header_phi->ReplaceInput(preheader_phi, first_nonbackedge_pred_pos);
696 preheader_phi->AddInput(orig_input);
697
698 for (size_t input_pos = first_nonbackedge_pred_pos + 1;
699 input_pos < header_phi->InputCount();
700 input_pos++) {
701 HInstruction* input = header_phi->InputAt(input_pos);
702 HBasicBlock* pred_block = header->GetPredecessors()[input_pos];
703
704 if (loop_info->Contains(*pred_block)) {
705 DCHECK(loop_info->IsBackEdge(*pred_block));
706 } else {
707 preheader_phi->AddInput(input);
708 header_phi->RemoveInputAt(input_pos);
709 input_pos--;
710 }
711 }
712 }
713
714 // Fix the control-flow.
715 HBasicBlock* first_pred = header->GetPredecessors()[first_nonbackedge_pred_pos];
716 preheader->InsertBetween(first_pred, header);
717
718 FixControlForNewSinglePreheader(header, preheader);
719}
720
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100721void HGraph::SimplifyLoop(HBasicBlock* header) {
722 HLoopInformation* info = header->GetLoopInformation();
723
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100724 // Make sure the loop has only one pre header. This simplifies SSA building by having
725 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000726 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
727 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000728 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000729 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Artem Serov09faaea2017-12-07 14:36:01 +0000730 TransformLoopToSinglePreheaderFormat(header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100731 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100732
Artem Serovc73ee372017-07-31 15:08:40 +0100733 OrderLoopHeaderPredecessors(header);
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100734
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100735 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000736 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
737 // Called from DeadBlockElimination. Update SuspendCheck pointer.
738 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100739 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100740}
741
David Brazdilffee3d32015-07-06 11:48:53 +0100742void HGraph::ComputeTryBlockInformation() {
743 // Iterate in reverse post order to propagate try membership information from
744 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100745 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100746 if (block->IsEntryBlock() || block->IsCatchBlock()) {
747 // Catch blocks after simplification have only exceptional predecessors
748 // and hence are never in tries.
749 continue;
750 }
751
752 // Infer try membership from the first predecessor. Having simplified loops,
753 // the first predecessor can never be a back edge and therefore it must have
754 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100755 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
Santiago Aboy Solanes872ec722022-02-18 14:10:25 +0000756 DCHECK_IMPLIES(block->IsLoopHeader(),
757 !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100758 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000759 if (try_entry != nullptr &&
760 (block->GetTryCatchInformation() == nullptr ||
761 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
762 // We are either setting try block membership for the first time or it
763 // has changed.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100764 block->SetTryCatchInformation(new (allocator_) TryCatchInformation(*try_entry));
David Brazdilec16f792015-08-19 15:04:01 +0100765 }
David Brazdilffee3d32015-07-06 11:48:53 +0100766 }
767}
768
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100769void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000770// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100771 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000772 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100773 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
774 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
775 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
776 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100777 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000778 if (block->GetSuccessors().size() > 1) {
779 // Only split normal-flow edges. We cannot split exceptional edges as they
780 // are synthesized (approximate real control flow), and we do not need to
781 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000782 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
783 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
784 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100785 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000786 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000787 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
788 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000789 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000790 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100791 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000792 // SplitCriticalEdge could have invalidated the `normal_successors`
793 // ArrayRef. We must re-acquire it.
794 normal_successors = block->GetNormalSuccessors();
795 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
796 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100797 }
798 }
799 }
800 if (block->IsLoopHeader()) {
801 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000802 } else if (!block->IsEntryBlock() &&
803 block->GetFirstInstruction() != nullptr &&
804 block->GetFirstInstruction()->IsSuspendCheck()) {
805 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000806 // a loop got dismantled. Just remove the suspend check.
807 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100808 }
809 }
810}
811
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000812GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100813 // We iterate post order to ensure we visit inner loops before outer loops.
814 // `PopulateRecursive` needs this guarantee to know whether a natural loop
815 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100816 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100817 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100818 if (block->IsCatchBlock()) {
819 // TODO: Dealing with exceptional back edges could be tricky because
820 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffraydbb9aef2017-11-23 10:44:11 +0000821 VLOG(compiler) << "Not compiled: Exceptional back edges";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000822 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100823 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000824 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100825 }
826 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000827 return kAnalysisSuccess;
828}
829
830void HLoopInformation::Dump(std::ostream& os) {
831 os << "header: " << header_->GetBlockId() << std::endl;
832 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
833 for (HBasicBlock* block : back_edges_) {
834 os << "back edge: " << block->GetBlockId() << std::endl;
835 }
836 for (HBasicBlock* block : header_->GetPredecessors()) {
837 os << "predecessor: " << block->GetBlockId() << std::endl;
838 }
839 for (uint32_t idx : blocks_.Indexes()) {
840 os << " in loop: " << idx << std::endl;
841 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100842}
843
David Brazdil8d5b8b22015-03-24 10:51:52 +0000844void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000845 // New constants are inserted before the SuspendCheck at the bottom of the
846 // entry block. Note that this method can be called from the graph builder and
847 // the entry block therefore may not end with SuspendCheck->Goto yet.
848 HInstruction* insert_before = nullptr;
849
850 HInstruction* gota = entry_block_->GetLastInstruction();
851 if (gota != nullptr && gota->IsGoto()) {
852 HInstruction* suspend_check = gota->GetPrevious();
853 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
854 insert_before = suspend_check;
855 } else {
856 insert_before = gota;
857 }
858 }
859
860 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000861 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000862 } else {
863 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000864 }
865}
866
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600867HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100868 // For simplicity, don't bother reviving the cached null constant if it is
869 // not null and not in a block. Otherwise, we need to clear the instruction
870 // id and/or any invariants the graph is assuming when adding new instructions.
871 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100872 cached_null_constant_ = new (allocator_) HNullConstant(dex_pc);
Vladimir Marko02ca05a2020-05-12 13:58:51 +0100873 cached_null_constant_->SetReferenceTypeInfo(GetInexactObjectRti());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000874 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000875 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000876 if (kIsDebugBuild) {
877 ScopedObjectAccess soa(Thread::Current());
878 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
879 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000880 return cached_null_constant_;
881}
882
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100883HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100884 // For simplicity, don't bother reviving the cached current method if it is
885 // not null and not in a block. Otherwise, we need to clear the instruction
886 // id and/or any invariants the graph is assuming when adding new instructions.
887 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100888 cached_current_method_ = new (allocator_) HCurrentMethod(
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100889 Is64BitInstructionSet(instruction_set_) ? DataType::Type::kInt64 : DataType::Type::kInt32,
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600890 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100891 if (entry_block_->GetFirstInstruction() == nullptr) {
892 entry_block_->AddInstruction(cached_current_method_);
893 } else {
894 entry_block_->InsertInstructionBefore(
895 cached_current_method_, entry_block_->GetFirstInstruction());
896 }
897 }
898 return cached_current_method_;
899}
900
Igor Murashkind01745e2017-04-05 16:40:31 -0700901const char* HGraph::GetMethodName() const {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800902 const dex::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
Igor Murashkind01745e2017-04-05 16:40:31 -0700903 return dex_file_.GetMethodName(method_id);
904}
905
906std::string HGraph::PrettyMethod(bool with_signature) const {
907 return dex_file_.PrettyMethod(method_idx_, with_signature);
908}
909
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100910HConstant* HGraph::GetConstant(DataType::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000911 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100912 case DataType::Type::kBool:
David Brazdil8d5b8b22015-03-24 10:51:52 +0000913 DCHECK(IsUint<1>(value));
914 FALLTHROUGH_INTENDED;
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100915 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100916 case DataType::Type::kInt8:
917 case DataType::Type::kUint16:
918 case DataType::Type::kInt16:
919 case DataType::Type::kInt32:
920 DCHECK(IsInt(DataType::Size(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600921 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000922
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100923 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600924 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000925
926 default:
927 LOG(FATAL) << "Unsupported constant type";
928 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000929 }
David Brazdil46e2a392015-03-16 17:31:52 +0000930}
931
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000932void HGraph::CacheFloatConstant(HFloatConstant* constant) {
933 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
934 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
935 cached_float_constants_.Overwrite(value, constant);
936}
937
938void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
939 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
940 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
941 cached_double_constants_.Overwrite(value, constant);
942}
943
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000944void HLoopInformation::Add(HBasicBlock* block) {
945 blocks_.SetBit(block->GetBlockId());
946}
947
David Brazdil46e2a392015-03-16 17:31:52 +0000948void HLoopInformation::Remove(HBasicBlock* block) {
949 blocks_.ClearBit(block->GetBlockId());
950}
951
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100952void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
953 if (blocks_.IsBitSet(block->GetBlockId())) {
954 return;
955 }
956
957 blocks_.SetBit(block->GetBlockId());
958 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100959 if (block->IsLoopHeader()) {
960 // We're visiting loops in post-order, so inner loops must have been
961 // populated already.
962 DCHECK(block->GetLoopInformation()->IsPopulated());
963 if (block->GetLoopInformation()->IsIrreducible()) {
964 contains_irreducible_loop_ = true;
965 }
966 }
Vladimir Marko60584552015-09-03 13:35:12 +0000967 for (HBasicBlock* predecessor : block->GetPredecessors()) {
968 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100969 }
970}
971
David Brazdilc2e8af92016-04-05 17:15:19 +0100972void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
973 size_t block_id = block->GetBlockId();
974
975 // If `block` is in `finalized`, we know its membership in the loop has been
976 // decided and it does not need to be revisited.
977 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000978 return;
979 }
980
David Brazdilc2e8af92016-04-05 17:15:19 +0100981 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000982 if (block->IsLoopHeader()) {
983 // If we hit a loop header in an irreducible loop, we first check if the
984 // pre header of that loop belongs to the currently analyzed loop. If it does,
985 // then we visit the back edges.
986 // Note that we cannot use GetPreHeader, as the loop may have not been populated
987 // yet.
988 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100989 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000990 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000991 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100992 blocks_.SetBit(block_id);
993 finalized->SetBit(block_id);
994 is_finalized = true;
995
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000996 HLoopInformation* info = block->GetLoopInformation();
997 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100998 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000999 }
1000 }
1001 } else {
1002 // Visit all predecessors. If one predecessor is part of the loop, this
1003 // block is also part of this loop.
1004 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +01001005 PopulateIrreducibleRecursive(predecessor, finalized);
1006 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001007 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +01001008 blocks_.SetBit(block_id);
1009 finalized->SetBit(block_id);
1010 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001011 }
1012 }
1013 }
David Brazdilc2e8af92016-04-05 17:15:19 +01001014
1015 // All predecessors have been recursively visited. Mark finalized if not marked yet.
1016 if (!is_finalized) {
1017 finalized->SetBit(block_id);
1018 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001019}
1020
1021void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +01001022 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001023 // Populate this loop: starting with the back edge, recursively add predecessors
1024 // that are not already part of that loop. Set the header as part of the loop
1025 // to end the recursion.
1026 // This is a recursive implementation of the algorithm described in
1027 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +01001028 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001029 blocks_.SetBit(header_->GetBlockId());
1030 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +01001031
David Brazdil3f4a5222016-05-06 12:46:21 +01001032 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +01001033
1034 if (is_irreducible_loop) {
Vladimir Marko69d310e2017-10-09 14:12:23 +01001035 // Allocate memory from local ScopedArenaAllocator.
1036 ScopedArenaAllocator allocator(graph->GetArenaStack());
1037 ArenaBitVector visited(&allocator,
David Brazdilc2e8af92016-04-05 17:15:19 +01001038 graph->GetBlocks().size(),
Andreas Gampe3db70682018-12-26 15:12:03 -08001039 /* expandable= */ false,
David Brazdilc2e8af92016-04-05 17:15:19 +01001040 kArenaAllocGraphBuilder);
Vladimir Marko69d310e2017-10-09 14:12:23 +01001041 visited.ClearAllBits();
David Brazdil5a620592016-05-05 11:27:03 +01001042 // Stop marking blocks at the loop header.
1043 visited.SetBit(header_->GetBlockId());
1044
David Brazdilc2e8af92016-04-05 17:15:19 +01001045 for (HBasicBlock* back_edge : GetBackEdges()) {
1046 PopulateIrreducibleRecursive(back_edge, &visited);
1047 }
1048 } else {
1049 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001050 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001051 }
David Brazdila4b8c212015-05-07 09:59:30 +01001052 }
David Brazdilc2e8af92016-04-05 17:15:19 +01001053
Vladimir Markofd66c502016-04-18 15:37:01 +01001054 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
1055 // When compiling in OSR mode, all loops in the compiled method may be entered
1056 // from the interpreter. We treat this OSR entry point just like an extra entry
1057 // to an irreducible loop, so we need to mark the method's loops as irreducible.
1058 // This does not apply to inlined loops which do not act as OSR entry points.
1059 if (suspend_check_ == nullptr) {
1060 // Just building the graph in OSR mode, this loop is not inlined. We never build an
1061 // inner graph in OSR mode as we can do OSR transition only from the outer method.
1062 is_irreducible_loop = true;
1063 } else {
1064 // Look at the suspend check's environment to determine if the loop was inlined.
1065 DCHECK(suspend_check_->HasEnvironment());
1066 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
1067 is_irreducible_loop = true;
1068 }
1069 }
1070 }
1071 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +01001072 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +01001073 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +01001074 graph->SetHasIrreducibleLoops(true);
1075 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08001076 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +01001077}
1078
Artem Serov7f4aff62017-06-21 17:02:18 +01001079void HLoopInformation::PopulateInnerLoopUpwards(HLoopInformation* inner_loop) {
1080 DCHECK(inner_loop->GetPreHeader()->GetLoopInformation() == this);
1081 blocks_.Union(&inner_loop->blocks_);
1082 HLoopInformation* outer_loop = GetPreHeader()->GetLoopInformation();
1083 if (outer_loop != nullptr) {
1084 outer_loop->PopulateInnerLoopUpwards(this);
1085 }
1086}
1087
Nicolas Geoffray622d9c32014-05-12 16:11:02 +01001088HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001089 HBasicBlock* block = header_->GetPredecessors()[0];
1090 DCHECK(irreducible_ || (block == header_->GetDominator()));
1091 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +01001092}
1093
1094bool HLoopInformation::Contains(const HBasicBlock& block) const {
1095 return blocks_.IsBitSet(block.GetBlockId());
1096}
1097
1098bool HLoopInformation::IsIn(const HLoopInformation& other) const {
1099 return other.blocks_.IsBitSet(header_->GetBlockId());
1100}
1101
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001102bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
1103 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -07001104}
1105
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001106size_t HLoopInformation::GetLifetimeEnd() const {
1107 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001108 for (HBasicBlock* back_edge : GetBackEdges()) {
1109 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001110 }
1111 return last_position;
1112}
1113
David Brazdil3f4a5222016-05-06 12:46:21 +01001114bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
1115 for (HBasicBlock* back_edge : GetBackEdges()) {
1116 DCHECK(back_edge->GetDominator() != nullptr);
1117 if (!header_->Dominates(back_edge)) {
1118 return true;
1119 }
1120 }
1121 return false;
1122}
1123
Anton Shaminf89381f2016-05-16 16:44:13 +06001124bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
1125 for (HBasicBlock* back_edge : GetBackEdges()) {
1126 if (!block->Dominates(back_edge)) {
1127 return false;
1128 }
1129 }
1130 return true;
1131}
1132
David Sehrc757dec2016-11-04 15:48:34 -07001133
1134bool HLoopInformation::HasExitEdge() const {
1135 // Determine if this loop has at least one exit edge.
1136 HBlocksInLoopReversePostOrderIterator it_loop(*this);
1137 for (; !it_loop.Done(); it_loop.Advance()) {
1138 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
1139 if (!Contains(*successor)) {
1140 return true;
1141 }
1142 }
1143 }
1144 return false;
1145}
1146
Vladimir Marko8d100ba2022-03-04 10:13:10 +00001147bool HBasicBlock::Dominates(const HBasicBlock* other) const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +01001148 // Walk up the dominator tree from `other`, to find out if `this`
1149 // is an ancestor.
Vladimir Marko8d100ba2022-03-04 10:13:10 +00001150 const HBasicBlock* current = other;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +01001151 while (current != nullptr) {
1152 if (current == this) {
1153 return true;
1154 }
1155 current = current->GetDominator();
1156 }
1157 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001158}
1159
Nicolas Geoffray191c4b12014-10-07 14:14:27 +01001160static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +01001161 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001162 for (size_t i = 0; i < inputs.size(); ++i) {
1163 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +01001164 }
1165 // Environment should be created later.
1166 DCHECK(!instruction->HasEnvironment());
1167}
1168
Artem Serovcced8ba2017-07-19 18:18:09 +01001169void HBasicBlock::ReplaceAndRemovePhiWith(HPhi* initial, HPhi* replacement) {
1170 DCHECK(initial->GetBlock() == this);
1171 InsertPhiAfter(replacement, initial);
1172 initial->ReplaceWith(replacement);
1173 RemovePhi(initial);
1174}
1175
Roland Levillainccc07a92014-09-16 14:48:16 +01001176void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
1177 HInstruction* replacement) {
1178 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -04001179 if (initial->IsControlFlow()) {
1180 // We can only replace a control flow instruction with another control flow instruction.
1181 DCHECK(replacement->IsControlFlow());
1182 DCHECK_EQ(replacement->GetId(), -1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001183 DCHECK_EQ(replacement->GetType(), DataType::Type::kVoid);
Mark Mendell805b3b52015-09-18 14:10:29 -04001184 DCHECK_EQ(initial->GetBlock(), this);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001185 DCHECK_EQ(initial->GetType(), DataType::Type::kVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +01001186 DCHECK(initial->GetUses().empty());
1187 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -04001188 replacement->SetBlock(this);
1189 replacement->SetId(GetGraph()->GetNextInstructionId());
1190 instructions_.InsertInstructionBefore(replacement, initial);
1191 UpdateInputsUsers(replacement);
1192 } else {
1193 InsertInstructionBefore(replacement, initial);
1194 initial->ReplaceWith(replacement);
1195 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001196 RemoveInstruction(initial);
1197}
1198
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001199static void Add(HInstructionList* instruction_list,
1200 HBasicBlock* block,
1201 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +00001202 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +00001203 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001204 instruction->SetBlock(block);
1205 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +01001206 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001207 instruction_list->AddInstruction(instruction);
1208}
1209
1210void HBasicBlock::AddInstruction(HInstruction* instruction) {
1211 Add(&instructions_, this, instruction);
1212}
1213
1214void HBasicBlock::AddPhi(HPhi* phi) {
1215 Add(&phis_, this, phi);
1216}
1217
David Brazdilc3d743f2015-04-22 13:40:50 +01001218void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1219 DCHECK(!cursor->IsPhi());
1220 DCHECK(!instruction->IsPhi());
1221 DCHECK_EQ(instruction->GetId(), -1);
1222 DCHECK_NE(cursor->GetId(), -1);
1223 DCHECK_EQ(cursor->GetBlock(), this);
1224 DCHECK(!instruction->IsControlFlow());
1225 instruction->SetBlock(this);
1226 instruction->SetId(GetGraph()->GetNextInstructionId());
1227 UpdateInputsUsers(instruction);
1228 instructions_.InsertInstructionBefore(instruction, cursor);
1229}
1230
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +01001231void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1232 DCHECK(!cursor->IsPhi());
1233 DCHECK(!instruction->IsPhi());
1234 DCHECK_EQ(instruction->GetId(), -1);
1235 DCHECK_NE(cursor->GetId(), -1);
1236 DCHECK_EQ(cursor->GetBlock(), this);
1237 DCHECK(!instruction->IsControlFlow());
1238 DCHECK(!cursor->IsControlFlow());
1239 instruction->SetBlock(this);
1240 instruction->SetId(GetGraph()->GetNextInstructionId());
1241 UpdateInputsUsers(instruction);
1242 instructions_.InsertInstructionAfter(instruction, cursor);
1243}
1244
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001245void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
1246 DCHECK_EQ(phi->GetId(), -1);
1247 DCHECK_NE(cursor->GetId(), -1);
1248 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001249 phi->SetBlock(this);
1250 phi->SetId(GetGraph()->GetNextInstructionId());
1251 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +01001252 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001253}
1254
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001255static void Remove(HInstructionList* instruction_list,
1256 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +00001257 HInstruction* instruction,
1258 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001259 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001260 instruction->SetBlock(nullptr);
1261 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +00001262 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001263 DCHECK(instruction->GetUses().empty());
1264 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +00001265 RemoveAsUser(instruction);
1266 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001267}
1268
David Brazdil1abb4192015-02-17 18:33:36 +00001269void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +01001270 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +00001271 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001272}
1273
David Brazdil1abb4192015-02-17 18:33:36 +00001274void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
1275 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001276}
1277
David Brazdilc7508e92015-04-27 13:28:57 +01001278void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
1279 if (instruction->IsPhi()) {
1280 RemovePhi(instruction->AsPhi(), ensure_safety);
1281 } else {
1282 RemoveInstruction(instruction, ensure_safety);
1283 }
1284}
1285
Vladimir Marko69d310e2017-10-09 14:12:23 +01001286void HEnvironment::CopyFrom(ArrayRef<HInstruction* const> locals) {
Vladimir Marko71bf8092015-09-15 15:33:14 +01001287 for (size_t i = 0; i < locals.size(); i++) {
1288 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +01001289 SetRawEnvAt(i, instruction);
1290 if (instruction != nullptr) {
1291 instruction->AddEnvUseAt(this, i);
1292 }
1293 }
1294}
1295
David Brazdiled596192015-01-23 10:39:45 +00001296void HEnvironment::CopyFrom(HEnvironment* env) {
1297 for (size_t i = 0; i < env->Size(); i++) {
1298 HInstruction* instruction = env->GetInstructionAt(i);
1299 SetRawEnvAt(i, instruction);
1300 if (instruction != nullptr) {
1301 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001302 }
David Brazdiled596192015-01-23 10:39:45 +00001303 }
1304}
1305
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001306void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
1307 HBasicBlock* loop_header) {
1308 DCHECK(loop_header->IsLoopHeader());
1309 for (size_t i = 0; i < env->Size(); i++) {
1310 HInstruction* instruction = env->GetInstructionAt(i);
1311 SetRawEnvAt(i, instruction);
1312 if (instruction == nullptr) {
1313 continue;
1314 }
1315 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
1316 // At the end of the loop pre-header, the corresponding value for instruction
1317 // is the first input of the phi.
1318 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001319 SetRawEnvAt(i, initial);
1320 initial->AddEnvUseAt(this, i);
1321 } else {
1322 instruction->AddEnvUseAt(this, i);
1323 }
1324 }
1325}
1326
David Brazdil1abb4192015-02-17 18:33:36 +00001327void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +01001328 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
1329 HInstruction* user = env_use.GetInstruction();
1330 auto before_env_use_node = env_use.GetBeforeUseNode();
1331 user->env_uses_.erase_after(before_env_use_node);
1332 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001333}
1334
Artem Serovca210e32017-12-15 13:43:20 +00001335void HEnvironment::ReplaceInput(HInstruction* replacement, size_t index) {
1336 const HUserRecord<HEnvironment*>& env_use_record = vregs_[index];
1337 HInstruction* orig_instr = env_use_record.GetInstruction();
1338
1339 DCHECK(orig_instr != replacement);
1340
1341 HUseList<HEnvironment*>::iterator before_use_node = env_use_record.GetBeforeUseNode();
1342 // Note: fixup_end remains valid across splice_after().
1343 auto fixup_end = replacement->env_uses_.empty() ? replacement->env_uses_.begin()
1344 : ++replacement->env_uses_.begin();
1345 replacement->env_uses_.splice_after(replacement->env_uses_.before_begin(),
1346 env_use_record.GetInstruction()->env_uses_,
1347 before_use_node);
1348 replacement->FixUpUserRecordsAfterEnvUseInsertion(fixup_end);
1349 orig_instr->FixUpUserRecordsAfterEnvUseRemoval(before_use_node);
1350}
1351
Vladimir Markoc9fcfd02021-01-05 16:57:30 +00001352std::ostream& HInstruction::Dump(std::ostream& os, bool dump_args) {
Vladimir Markodac82392021-05-10 15:44:24 +00001353 // Note: Handle the case where the instruction has been removed from
1354 // the graph to support debugging output for failed gtests.
1355 HGraph* graph = (GetBlock() != nullptr) ? GetBlock()->GetGraph() : nullptr;
Vladimir Markoc9fcfd02021-01-05 16:57:30 +00001356 HGraphVisualizer::DumpInstruction(&os, graph, this);
1357 if (dump_args) {
1358 // Allocate memory from local ScopedArenaAllocator.
Vladimir Markodac82392021-05-10 15:44:24 +00001359 std::optional<MallocArenaPool> local_arena_pool;
1360 std::optional<ArenaStack> local_arena_stack;
1361 if (UNLIKELY(graph == nullptr)) {
1362 local_arena_pool.emplace();
1363 local_arena_stack.emplace(&local_arena_pool.value());
1364 }
1365 ScopedArenaAllocator allocator(
1366 graph != nullptr ? graph->GetArenaStack() : &local_arena_stack.value());
Vladimir Markoc9fcfd02021-01-05 16:57:30 +00001367 // Instructions that we already visited. We print each instruction only once.
Vladimir Markodac82392021-05-10 15:44:24 +00001368 ArenaBitVector visited(&allocator,
1369 (graph != nullptr) ? graph->GetCurrentInstructionId() : 0u,
1370 /* expandable= */ (graph == nullptr),
1371 kArenaAllocMisc);
Vladimir Markoc9fcfd02021-01-05 16:57:30 +00001372 visited.ClearAllBits();
1373 visited.SetBit(GetId());
1374 // Keep a queue of instructions with their indentations.
1375 ScopedArenaDeque<std::pair<HInstruction*, size_t>> queue(allocator.Adapter(kArenaAllocMisc));
1376 auto add_args = [&queue](HInstruction* instruction, size_t indentation) {
1377 for (HInstruction* arg : ReverseRange(instruction->GetInputs())) {
1378 queue.emplace_front(arg, indentation);
1379 }
1380 };
1381 add_args(this, /*indentation=*/ 1u);
1382 while (!queue.empty()) {
1383 HInstruction* instruction;
1384 size_t indentation;
1385 std::tie(instruction, indentation) = queue.front();
1386 queue.pop_front();
1387 if (!visited.IsBitSet(instruction->GetId())) {
1388 visited.SetBit(instruction->GetId());
1389 os << '\n';
1390 for (size_t i = 0; i != indentation; ++i) {
1391 os << " ";
1392 }
1393 HGraphVisualizer::DumpInstruction(&os, graph, instruction);
1394 add_args(instruction, indentation + 1u);
1395 }
1396 }
1397 }
1398 return os;
1399}
1400
Calin Juravle77520bc2015-01-12 18:45:46 +00001401HInstruction* HInstruction::GetNextDisregardingMoves() const {
1402 HInstruction* next = GetNext();
1403 while (next != nullptr && next->IsParallelMove()) {
1404 next = next->GetNext();
1405 }
1406 return next;
1407}
1408
1409HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1410 HInstruction* previous = GetPrevious();
1411 while (previous != nullptr && previous->IsParallelMove()) {
1412 previous = previous->GetPrevious();
1413 }
1414 return previous;
1415}
1416
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001417void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001418 if (first_instruction_ == nullptr) {
1419 DCHECK(last_instruction_ == nullptr);
1420 first_instruction_ = last_instruction_ = instruction;
1421 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001422 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001423 last_instruction_->next_ = instruction;
1424 instruction->previous_ = last_instruction_;
1425 last_instruction_ = instruction;
1426 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001427}
1428
David Brazdilc3d743f2015-04-22 13:40:50 +01001429void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1430 DCHECK(Contains(cursor));
1431 if (cursor == first_instruction_) {
1432 cursor->previous_ = instruction;
1433 instruction->next_ = cursor;
1434 first_instruction_ = instruction;
1435 } else {
1436 instruction->previous_ = cursor->previous_;
1437 instruction->next_ = cursor;
1438 cursor->previous_ = instruction;
1439 instruction->previous_->next_ = instruction;
1440 }
1441}
1442
1443void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1444 DCHECK(Contains(cursor));
1445 if (cursor == last_instruction_) {
1446 cursor->next_ = instruction;
1447 instruction->previous_ = cursor;
1448 last_instruction_ = instruction;
1449 } else {
1450 instruction->next_ = cursor->next_;
1451 instruction->previous_ = cursor;
1452 cursor->next_ = instruction;
1453 instruction->next_->previous_ = instruction;
1454 }
1455}
1456
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001457void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1458 if (instruction->previous_ != nullptr) {
1459 instruction->previous_->next_ = instruction->next_;
1460 }
1461 if (instruction->next_ != nullptr) {
1462 instruction->next_->previous_ = instruction->previous_;
1463 }
1464 if (instruction == first_instruction_) {
1465 first_instruction_ = instruction->next_;
1466 }
1467 if (instruction == last_instruction_) {
1468 last_instruction_ = instruction->previous_;
1469 }
1470}
1471
Roland Levillain6b469232014-09-25 10:10:38 +01001472bool HInstructionList::Contains(HInstruction* instruction) const {
1473 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1474 if (it.Current() == instruction) {
1475 return true;
1476 }
1477 }
1478 return false;
1479}
1480
Roland Levillainccc07a92014-09-16 14:48:16 +01001481bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1482 const HInstruction* instruction2) const {
1483 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1484 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1485 if (it.Current() == instruction1) {
1486 return true;
1487 }
1488 if (it.Current() == instruction2) {
1489 return false;
1490 }
1491 }
1492 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
Elliott Hughesc1896c92018-11-29 11:33:18 -08001493 UNREACHABLE();
Roland Levillainccc07a92014-09-16 14:48:16 +01001494}
1495
Santiago Aboy Solanes8c3b58a2022-08-15 13:21:59 +00001496bool HInstruction::Dominates(HInstruction* other_instruction) const {
1497 return other_instruction == this || StrictlyDominates(other_instruction);
1498}
1499
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001500bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
Roland Levillain6c82d402014-10-13 16:10:27 +01001501 if (other_instruction == this) {
1502 // An instruction does not strictly dominate itself.
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001503 return false;
Roland Levillain6c82d402014-10-13 16:10:27 +01001504 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001505 HBasicBlock* block = GetBlock();
1506 HBasicBlock* other_block = other_instruction->GetBlock();
1507 if (block != other_block) {
1508 return GetBlock()->Dominates(other_instruction->GetBlock());
1509 } else {
1510 // If both instructions are in the same block, ensure this
1511 // instruction comes before `other_instruction`.
1512 if (IsPhi()) {
1513 if (!other_instruction->IsPhi()) {
1514 // Phis appear before non phi-instructions so this instruction
1515 // dominates `other_instruction`.
1516 return true;
1517 } else {
1518 // There is no order among phis.
1519 LOG(FATAL) << "There is no dominance between phis of a same block.";
Elliott Hughesc1896c92018-11-29 11:33:18 -08001520 UNREACHABLE();
Roland Levillainccc07a92014-09-16 14:48:16 +01001521 }
1522 } else {
1523 // `this` is not a phi.
1524 if (other_instruction->IsPhi()) {
1525 // Phis appear before non phi-instructions so this instruction
1526 // does not dominate `other_instruction`.
1527 return false;
1528 } else {
1529 // Check whether this instruction comes before
1530 // `other_instruction` in the instruction list.
1531 return block->GetInstructions().FoundBefore(this, other_instruction);
1532 }
1533 }
1534 }
1535}
1536
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001537void HInstruction::RemoveEnvironment() {
1538 RemoveEnvironmentUses(this);
1539 environment_ = nullptr;
1540}
1541
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001542void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001543 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001544 // Note: fixup_end remains valid across splice_after().
1545 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1546 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1547 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001548
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001549 // Note: env_fixup_end remains valid across splice_after().
1550 auto env_fixup_end =
1551 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1552 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1553 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001554
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001555 DCHECK(uses_.empty());
1556 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001557}
1558
Santiago Aboy Solanes8c3b58a2022-08-15 13:21:59 +00001559void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator,
1560 HInstruction* replacement,
1561 bool strictly_dominated) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001562 const HUseList<HInstruction*>& uses = GetUses();
1563 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1564 HInstruction* user = it->GetUser();
1565 size_t index = it->GetIndex();
1566 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1567 ++it;
Santiago Aboy Solanes8c3b58a2022-08-15 13:21:59 +00001568 const bool dominated =
1569 strictly_dominated ? dominator->StrictlyDominates(user) : dominator->Dominates(user);
1570
1571 if (dominated) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001572 user->ReplaceInput(replacement, index);
Nicolas Geoffray1c8605e2018-08-05 12:05:01 +01001573 } else if (user->IsPhi() && !user->AsPhi()->IsCatchPhi()) {
1574 // If the input flows from a block dominated by `dominator`, we can replace it.
1575 // We do not perform this for catch phis as we don't have control flow support
1576 // for their inputs.
1577 const ArenaVector<HBasicBlock*>& predecessors = user->GetBlock()->GetPredecessors();
1578 HBasicBlock* predecessor = predecessors[index];
1579 if (dominator->GetBlock()->Dominates(predecessor)) {
1580 user->ReplaceInput(replacement, index);
1581 }
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001582 }
1583 }
1584}
1585
Nicolas Geoffray8a62a4c2018-07-03 09:39:07 +01001586void HInstruction::ReplaceEnvUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1587 const HUseList<HEnvironment*>& uses = GetEnvUses();
1588 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1589 HEnvironment* user = it->GetUser();
1590 size_t index = it->GetIndex();
1591 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1592 ++it;
1593 if (dominator->StrictlyDominates(user->GetHolder())) {
1594 user->ReplaceInput(replacement, index);
1595 }
1596 }
1597}
1598
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001599void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001600 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001601 if (input_use.GetInstruction() == replacement) {
1602 // Nothing to do.
1603 return;
1604 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001605 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001606 // Note: fixup_end remains valid across splice_after().
1607 auto fixup_end =
1608 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1609 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1610 input_use.GetInstruction()->uses_,
1611 before_use_node);
1612 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1613 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001614}
1615
Nicolas Geoffray39468442014-09-02 15:17:15 +01001616size_t HInstruction::EnvironmentSize() const {
1617 return HasEnvironment() ? environment_->Size() : 0;
1618}
1619
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001620void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001621 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001622 inputs_.push_back(HUserRecord<HInstruction*>(input));
1623 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001624}
1625
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001626void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1627 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1628 input->AddUseAt(this, index);
1629 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1630 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1631 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1632 inputs_[i].GetUseNode()->SetIndex(i);
1633 }
1634}
1635
1636void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001637 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001638 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001639 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1640 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1641 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1642 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001643 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001644}
1645
Igor Murashkind01745e2017-04-05 16:40:31 -07001646void HVariableInputSizeInstruction::RemoveAllInputs() {
1647 RemoveAsUserOfAllInputs();
1648 DCHECK(!HasNonEnvironmentUses());
1649
1650 inputs_.clear();
1651 DCHECK_EQ(0u, InputCount());
1652}
1653
Igor Murashkin6ef45672017-08-08 13:59:55 -07001654size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001655 DCHECK(instruction->GetBlock() != nullptr);
1656 // Removing constructor fences only makes sense for instructions with an object return type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001657 DCHECK_EQ(DataType::Type::kReference, instruction->GetType());
Igor Murashkind01745e2017-04-05 16:40:31 -07001658
Igor Murashkin6ef45672017-08-08 13:59:55 -07001659 // Return how many instructions were removed for statistic purposes.
1660 size_t remove_count = 0;
1661
Igor Murashkind01745e2017-04-05 16:40:31 -07001662 // Efficient implementation that simultaneously (in one pass):
1663 // * Scans the uses list for all constructor fences.
1664 // * Deletes that constructor fence from the uses list of `instruction`.
1665 // * Deletes `instruction` from the constructor fence's inputs.
1666 // * Deletes the constructor fence if it now has 0 inputs.
1667
1668 const HUseList<HInstruction*>& uses = instruction->GetUses();
1669 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1670 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1671 const HUseListNode<HInstruction*>& use_node = *it;
1672 HInstruction* const use_instruction = use_node.GetUser();
1673
1674 // Advance the iterator immediately once we fetch the use_node.
1675 // Warning: If the input is removed, the current iterator becomes invalid.
1676 ++it;
1677
1678 if (use_instruction->IsConstructorFence()) {
1679 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1680 size_t input_index = use_node.GetIndex();
1681
1682 // Process the candidate instruction for removal
1683 // from the graph.
1684
1685 // Constructor fence instructions are never
1686 // used by other instructions.
1687 //
1688 // If we wanted to make this more generic, it
1689 // could be a runtime if statement.
1690 DCHECK(!ctor_fence->HasUses());
1691
1692 // A constructor fence's return type is "kPrimVoid"
1693 // and therefore it can't have any environment uses.
1694 DCHECK(!ctor_fence->HasEnvironmentUses());
1695
1696 // Remove the inputs first, otherwise removing the instruction
1697 // will try to remove its uses while we are already removing uses
1698 // and this operation will fail.
1699 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1700
1701 // Removing the input will also remove the `use_node`.
1702 // (Do not look at `use_node` after this, it will be a dangling reference).
1703 ctor_fence->RemoveInputAt(input_index);
1704
1705 // Once all inputs are removed, the fence is considered dead and
1706 // is removed.
1707 if (ctor_fence->InputCount() == 0u) {
1708 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
Igor Murashkin6ef45672017-08-08 13:59:55 -07001709 ++remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001710 }
1711 }
1712 }
1713
1714 if (kIsDebugBuild) {
1715 // Post-condition checks:
1716 // * None of the uses of `instruction` are a constructor fence.
1717 // * The `instruction` itself did not get removed from a block.
1718 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1719 CHECK(!use_node.GetUser()->IsConstructorFence());
1720 }
1721 CHECK(instruction->GetBlock() != nullptr);
1722 }
Igor Murashkin6ef45672017-08-08 13:59:55 -07001723
1724 return remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001725}
1726
Igor Murashkindd018df2017-08-09 10:38:31 -07001727void HConstructorFence::Merge(HConstructorFence* other) {
1728 // Do not delete yourself from the graph.
1729 DCHECK(this != other);
1730 // Don't try to merge with an instruction not associated with a block.
1731 DCHECK(other->GetBlock() != nullptr);
1732 // A constructor fence's return type is "kPrimVoid"
1733 // and therefore it cannot have any environment uses.
1734 DCHECK(!other->HasEnvironmentUses());
1735
1736 auto has_input = [](HInstruction* haystack, HInstruction* needle) {
1737 // Check if `haystack` has `needle` as any of its inputs.
1738 for (size_t input_count = 0; input_count < haystack->InputCount(); ++input_count) {
1739 if (haystack->InputAt(input_count) == needle) {
1740 return true;
1741 }
1742 }
1743 return false;
1744 };
1745
1746 // Add any inputs from `other` into `this` if it wasn't already an input.
1747 for (size_t input_count = 0; input_count < other->InputCount(); ++input_count) {
1748 HInstruction* other_input = other->InputAt(input_count);
1749 if (!has_input(this, other_input)) {
1750 AddInput(other_input);
1751 }
1752 }
1753
1754 other->GetBlock()->RemoveInstruction(other);
1755}
1756
1757HInstruction* HConstructorFence::GetAssociatedAllocation(bool ignore_inputs) {
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001758 HInstruction* new_instance_inst = GetPrevious();
1759 // Check if the immediately preceding instruction is a new-instance/new-array.
1760 // Otherwise this fence is for protecting final fields.
1761 if (new_instance_inst != nullptr &&
1762 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
Igor Murashkindd018df2017-08-09 10:38:31 -07001763 if (ignore_inputs) {
1764 // If inputs are ignored, simply check if the predecessor is
1765 // *any* HNewInstance/HNewArray.
1766 //
1767 // Inputs are normally only ignored for prepare_for_register_allocation,
1768 // at which point *any* prior HNewInstance/Array can be considered
1769 // associated.
1770 return new_instance_inst;
1771 } else {
1772 // Normal case: There must be exactly 1 input and the previous instruction
1773 // must be that input.
1774 if (InputCount() == 1u && InputAt(0) == new_instance_inst) {
1775 return new_instance_inst;
1776 }
1777 }
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001778 }
Igor Murashkindd018df2017-08-09 10:38:31 -07001779 return nullptr;
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001780}
1781
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001782#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001783void H##name::Accept(HGraphVisitor* visitor) { \
1784 visitor->Visit##name(this); \
1785}
1786
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001787FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001788
1789#undef DEFINE_ACCEPT
1790
1791void HGraphVisitor::VisitInsertionOrder() {
Alex Light210a78d2020-11-30 16:58:05 -08001792 for (HBasicBlock* block : graph_->GetActiveBlocks()) {
1793 VisitBasicBlock(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001794 }
1795}
1796
Roland Levillain633021e2014-10-01 14:12:25 +01001797void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001798 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1799 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001800 }
1801}
1802
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001803void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001804 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001805 it.Current()->Accept(this);
1806 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001807 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001808 it.Current()->Accept(this);
1809 }
1810}
1811
Mark Mendelle82549b2015-05-06 10:55:34 -04001812HConstant* HTypeConversion::TryStaticEvaluation() const {
1813 HGraph* graph = GetBlock()->GetGraph();
1814 if (GetInput()->IsIntConstant()) {
1815 int32_t value = GetInput()->AsIntConstant()->GetValue();
1816 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001817 case DataType::Type::kInt8:
1818 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1819 case DataType::Type::kUint8:
1820 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1821 case DataType::Type::kInt16:
1822 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1823 case DataType::Type::kUint16:
1824 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001825 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001826 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001827 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001828 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001829 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001830 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001831 default:
1832 return nullptr;
1833 }
1834 } else if (GetInput()->IsLongConstant()) {
1835 int64_t value = GetInput()->AsLongConstant()->GetValue();
1836 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001837 case DataType::Type::kInt8:
1838 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1839 case DataType::Type::kUint8:
1840 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1841 case DataType::Type::kInt16:
1842 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1843 case DataType::Type::kUint16:
1844 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001845 case DataType::Type::kInt32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001846 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001847 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001848 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001849 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001850 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001851 default:
1852 return nullptr;
1853 }
1854 } else if (GetInput()->IsFloatConstant()) {
1855 float value = GetInput()->AsFloatConstant()->GetValue();
1856 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001857 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001858 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001859 return graph->GetIntConstant(0, GetDexPc());
Nick Desaulniers706e7782019-10-16 10:02:23 -07001860 if (value >= static_cast<float>(kPrimIntMax))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001861 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001862 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001863 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1864 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001865 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001866 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001867 return graph->GetLongConstant(0, GetDexPc());
Nick Desaulniers706e7782019-10-16 10:02:23 -07001868 if (value >= static_cast<float>(kPrimLongMax))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001869 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001870 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001871 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1872 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001873 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001874 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001875 default:
1876 return nullptr;
1877 }
1878 } else if (GetInput()->IsDoubleConstant()) {
1879 double value = GetInput()->AsDoubleConstant()->GetValue();
1880 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001881 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001882 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001883 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001884 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001885 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001886 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001887 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1888 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001889 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001890 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001891 return graph->GetLongConstant(0, GetDexPc());
Nick Desaulniers706e7782019-10-16 10:02:23 -07001892 if (value >= static_cast<double>(kPrimLongMax))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001893 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001894 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001895 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1896 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001897 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001898 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001899 default:
1900 return nullptr;
1901 }
1902 }
1903 return nullptr;
1904}
1905
Roland Levillain9240d6a2014-10-20 16:47:04 +01001906HConstant* HUnaryOperation::TryStaticEvaluation() const {
1907 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001908 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001909 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001910 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001911 } else if (kEnableFloatingPointStaticEvaluation) {
1912 if (GetInput()->IsFloatConstant()) {
1913 return Evaluate(GetInput()->AsFloatConstant());
1914 } else if (GetInput()->IsDoubleConstant()) {
1915 return Evaluate(GetInput()->AsDoubleConstant());
1916 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001917 }
1918 return nullptr;
1919}
1920
1921HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001922 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1923 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001924 } else if (GetLeft()->IsLongConstant()) {
1925 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001926 // The binop(long, int) case is only valid for shifts and rotations.
1927 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001928 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1929 } else if (GetRight()->IsLongConstant()) {
1930 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001931 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001932 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001933 // The binop(null, null) case is only valid for equal and not-equal conditions.
1934 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001935 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001936 } else if (kEnableFloatingPointStaticEvaluation) {
1937 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1938 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1939 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1940 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1941 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001942 }
1943 return nullptr;
1944}
Dave Allison20dfc792014-06-16 20:44:29 -07001945
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001946HConstant* HBinaryOperation::GetConstantRight() const {
1947 if (GetRight()->IsConstant()) {
1948 return GetRight()->AsConstant();
1949 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1950 return GetLeft()->AsConstant();
1951 } else {
1952 return nullptr;
1953 }
1954}
1955
1956// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001957// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001958HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1959 HInstruction* most_constant_right = GetConstantRight();
1960 if (most_constant_right == nullptr) {
1961 return nullptr;
1962 } else if (most_constant_right == GetLeft()) {
1963 return GetRight();
1964 } else {
1965 return GetLeft();
1966 }
1967}
1968
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001969std::ostream& operator<<(std::ostream& os, ComparisonBias rhs) {
1970 // TODO: Replace with auto-generated operator<<.
Roland Levillain31dd3d62016-02-16 12:21:02 +00001971 switch (rhs) {
1972 case ComparisonBias::kNoBias:
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001973 return os << "none";
Roland Levillain31dd3d62016-02-16 12:21:02 +00001974 case ComparisonBias::kGtBias:
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001975 return os << "gt";
Roland Levillain31dd3d62016-02-16 12:21:02 +00001976 case ComparisonBias::kLtBias:
Vladimir Marko9974e3c2020-06-10 16:27:06 +01001977 return os << "lt";
Roland Levillain31dd3d62016-02-16 12:21:02 +00001978 default:
1979 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1980 UNREACHABLE();
1981 }
1982}
1983
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001984bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1985 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001986}
1987
Vladimir Marko372f10e2016-05-17 16:30:10 +01001988bool HInstruction::Equals(const HInstruction* other) const {
Vladimir Marko0dcccd82018-05-04 13:32:25 +01001989 if (GetKind() != other->GetKind()) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001990 if (GetType() != other->GetType()) return false;
Vladimir Marko0dcccd82018-05-04 13:32:25 +01001991 if (!InstructionDataEquals(other)) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001992 HConstInputsRef inputs = GetInputs();
1993 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001994 if (inputs.size() != other_inputs.size()) return false;
1995 for (size_t i = 0; i != inputs.size(); ++i) {
1996 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001997 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001998
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001999 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01002000 return true;
2001}
2002
Vladimir Marko9974e3c2020-06-10 16:27:06 +01002003std::ostream& operator<<(std::ostream& os, HInstruction::InstructionKind rhs) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002004#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
2005 switch (rhs) {
Vladimir Markoe3946222018-05-04 14:18:47 +01002006 FOR_EACH_CONCRETE_INSTRUCTION(DECLARE_CASE)
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002007 default:
2008 os << "Unknown instruction kind " << static_cast<int>(rhs);
2009 break;
2010 }
2011#undef DECLARE_CASE
2012 return os;
2013}
2014
Alex Lightdc281e72021-01-06 12:35:31 -08002015std::ostream& operator<<(std::ostream& os, const HInstruction::NoArgsDump rhs) {
2016 // TODO Really this should be const but that would require const-ifying
2017 // graph-visualizer and HGraphVisitor which are tangled up everywhere.
2018 return const_cast<HInstruction*>(rhs.ins)->Dump(os, /* dump_args= */ false);
2019}
2020
2021std::ostream& operator<<(std::ostream& os, const HInstruction::ArgsDump rhs) {
2022 // TODO Really this should be const but that would require const-ifying
2023 // graph-visualizer and HGraphVisitor which are tangled up everywhere.
2024 return const_cast<HInstruction*>(rhs.ins)->Dump(os, /* dump_args= */ true);
2025}
2026
2027std::ostream& operator<<(std::ostream& os, const HInstruction& rhs) {
2028 return os << rhs.DumpWithoutArgs();
2029}
2030
2031std::ostream& operator<<(std::ostream& os, const HUseList<HInstruction*>& lst) {
2032 os << "Instructions[";
2033 bool first = true;
2034 for (const auto& hi : lst) {
2035 if (!first) {
2036 os << ", ";
2037 }
2038 first = false;
2039 os << hi.GetUser()->DebugName() << "[id: " << hi.GetUser()->GetId()
2040 << ", blk: " << hi.GetUser()->GetBlock()->GetBlockId() << "]@" << hi.GetIndex();
2041 }
2042 os << "]";
2043 return os;
2044}
2045
2046std::ostream& operator<<(std::ostream& os, const HUseList<HEnvironment*>& lst) {
2047 os << "Environments[";
2048 bool first = true;
2049 for (const auto& hi : lst) {
2050 if (!first) {
2051 os << ", ";
2052 }
2053 first = false;
2054 os << *hi.GetUser()->GetHolder() << "@" << hi.GetIndex();
2055 }
2056 os << "]";
2057 return os;
2058}
2059
2060std::ostream& HGraph::Dump(std::ostream& os,
Nicolas Geoffray22df3e02022-01-10 09:31:57 +00002061 CodeGenerator* codegen,
Alex Lightdc281e72021-01-06 12:35:31 -08002062 std::optional<std::reference_wrapper<const BlockNamer>> namer) {
Nicolas Geoffray22df3e02022-01-10 09:31:57 +00002063 HGraphVisualizer vis(&os, this, codegen, namer);
Alex Lightdc281e72021-01-06 12:35:31 -08002064 vis.DumpGraphDebug();
2065 return os;
2066}
2067
Alexandre Rames22aa54b2016-10-18 09:32:29 +01002068void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
2069 if (do_checks) {
2070 DCHECK(!IsPhi());
2071 DCHECK(!IsControlFlow());
2072 DCHECK(CanBeMoved() ||
2073 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
2074 IsShouldDeoptimizeFlag());
2075 DCHECK(!cursor->IsPhi());
2076 }
David Brazdild6c205e2016-06-07 14:20:52 +01002077
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002078 next_->previous_ = previous_;
2079 if (previous_ != nullptr) {
2080 previous_->next_ = next_;
2081 }
2082 if (block_->instructions_.first_instruction_ == this) {
2083 block_->instructions_.first_instruction_ = next_;
2084 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00002085 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002086
2087 previous_ = cursor->previous_;
2088 if (previous_ != nullptr) {
2089 previous_->next_ = this;
2090 }
2091 next_ = cursor;
2092 cursor->previous_ = this;
2093 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00002094
2095 if (block_->instructions_.first_instruction_ == cursor) {
2096 block_->instructions_.first_instruction_ = this;
2097 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002098}
2099
Vladimir Markofb337ea2015-11-25 15:25:10 +00002100void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
2101 DCHECK(!CanThrow());
2102 DCHECK(!HasSideEffects());
2103 DCHECK(!HasEnvironmentUses());
2104 DCHECK(HasNonEnvironmentUses());
2105 DCHECK(!IsPhi()); // Makes no sense for Phi.
2106 DCHECK_EQ(InputCount(), 0u);
2107
2108 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01002109 auto uses_it = GetUses().begin();
2110 auto uses_end = GetUses().end();
2111 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
2112 ++uses_it;
2113 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
2114 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00002115 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002116 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00002117 // This instruction has uses in two or more blocks. Find the common dominator.
2118 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01002119 for (; uses_it != uses_end; ++uses_it) {
2120 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00002121 }
2122 target_block = finder.Get();
2123 DCHECK(target_block != nullptr);
2124 }
2125 // Move to the first dominator not in a loop.
2126 while (target_block->IsInLoop()) {
2127 target_block = target_block->GetDominator();
2128 DCHECK(target_block != nullptr);
2129 }
2130
2131 // Find insertion position.
2132 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01002133 for (const HUseListNode<HInstruction*>& use : GetUses()) {
2134 if (use.GetUser()->GetBlock() == target_block &&
2135 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
2136 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00002137 }
2138 }
2139 if (insert_pos == nullptr) {
2140 // No user in `target_block`, insert before the control flow instruction.
2141 insert_pos = target_block->GetLastInstruction();
2142 DCHECK(insert_pos->IsControlFlow());
2143 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
2144 if (insert_pos->IsIf()) {
2145 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
2146 if (if_input == insert_pos->GetPrevious()) {
2147 insert_pos = if_input;
2148 }
2149 }
2150 }
2151 MoveBefore(insert_pos);
2152}
2153
Santiago Aboy Solanes78f3d3a2022-07-15 14:30:05 +01002154HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor, bool require_graph_not_in_ssa_form) {
2155 DCHECK_IMPLIES(require_graph_not_in_ssa_form, !graph_->IsInSsaForm())
2156 << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00002157 DCHECK_EQ(cursor->GetBlock(), this);
2158
Vladimir Markoca6fff82017-10-03 14:49:14 +01002159 HBasicBlock* new_block =
2160 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00002161 new_block->instructions_.first_instruction_ = cursor;
2162 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
2163 instructions_.last_instruction_ = cursor->previous_;
2164 if (cursor->previous_ == nullptr) {
2165 instructions_.first_instruction_ = nullptr;
2166 } else {
2167 cursor->previous_->next_ = nullptr;
2168 cursor->previous_ = nullptr;
2169 }
2170
2171 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002172 AddInstruction(new (GetGraph()->GetAllocator()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00002173
Vladimir Marko60584552015-09-03 13:35:12 +00002174 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00002175 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00002176 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002177 new_block->successors_.swap(successors_);
2178 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00002179 AddSuccessor(new_block);
2180
David Brazdil56e1acc2015-06-30 15:41:36 +01002181 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00002182 return new_block;
2183}
2184
David Brazdild7558da2015-09-22 13:04:14 +01002185HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00002186 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01002187 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
2188
Vladimir Markoca6fff82017-10-03 14:49:14 +01002189 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
David Brazdild7558da2015-09-22 13:04:14 +01002190
2191 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01002192 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
2193 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002194 new_block->predecessors_.swap(predecessors_);
2195 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01002196 AddPredecessor(new_block);
2197
2198 GetGraph()->AddBlock(new_block);
2199 return new_block;
2200}
2201
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002202HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
2203 DCHECK_EQ(cursor->GetBlock(), this);
2204
Vladimir Markoca6fff82017-10-03 14:49:14 +01002205 HBasicBlock* new_block =
2206 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002207 new_block->instructions_.first_instruction_ = cursor;
2208 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
2209 instructions_.last_instruction_ = cursor->previous_;
2210 if (cursor->previous_ == nullptr) {
2211 instructions_.first_instruction_ = nullptr;
2212 } else {
2213 cursor->previous_->next_ = nullptr;
2214 cursor->previous_ = nullptr;
2215 }
2216
2217 new_block->instructions_.SetBlockOfInstructions(new_block);
2218
2219 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002220 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
2221 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002222 new_block->successors_.swap(successors_);
2223 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002224
2225 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2226 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002227 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002228 new_block->dominated_blocks_.swap(dominated_blocks_);
2229 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002230 return new_block;
2231}
2232
2233HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002234 DCHECK(!cursor->IsControlFlow());
2235 DCHECK_NE(instructions_.last_instruction_, cursor);
2236 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002237
Vladimir Markoca6fff82017-10-03 14:49:14 +01002238 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002239 new_block->instructions_.first_instruction_ = cursor->GetNext();
2240 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
2241 cursor->next_->previous_ = nullptr;
2242 cursor->next_ = nullptr;
2243 instructions_.last_instruction_ = cursor;
2244
2245 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002246 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00002247 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002248 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002249 new_block->successors_.swap(successors_);
2250 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002251
Vladimir Marko60584552015-09-03 13:35:12 +00002252 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002253 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002254 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002255 new_block->dominated_blocks_.swap(dominated_blocks_);
2256 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002257 return new_block;
2258}
2259
David Brazdilec16f792015-08-19 15:04:01 +01002260const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01002261 if (EndsWithTryBoundary()) {
2262 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
2263 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01002264 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01002265 return try_boundary;
2266 } else {
David Brazdilec16f792015-08-19 15:04:01 +01002267 DCHECK(IsTryBlock());
2268 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01002269 return nullptr;
2270 }
David Brazdilec16f792015-08-19 15:04:01 +01002271 } else if (IsTryBlock()) {
2272 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01002273 } else {
David Brazdilec16f792015-08-19 15:04:01 +01002274 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01002275 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00002276}
2277
Aart Bik75ff2c92018-04-21 01:28:11 +00002278bool HBasicBlock::HasThrowingInstructions() const {
2279 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2280 if (it.Current()->CanThrow()) {
2281 return true;
2282 }
2283 }
2284 return false;
2285}
2286
David Brazdilfc6a86a2015-06-26 10:33:45 +00002287static bool HasOnlyOneInstruction(const HBasicBlock& block) {
2288 return block.GetPhis().IsEmpty()
2289 && !block.GetInstructions().IsEmpty()
2290 && block.GetFirstInstruction() == block.GetLastInstruction();
2291}
2292
David Brazdil46e2a392015-03-16 17:31:52 +00002293bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00002294 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
2295}
2296
Mads Ager16e52892017-07-14 13:11:37 +02002297bool HBasicBlock::IsSingleReturn() const {
2298 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
2299}
2300
Mingyao Yang46721ef2017-10-05 14:45:17 -07002301bool HBasicBlock::IsSingleReturnOrReturnVoidAllowingPhis() const {
2302 return (GetFirstInstruction() == GetLastInstruction()) &&
2303 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
2304}
2305
David Brazdilfc6a86a2015-06-26 10:33:45 +00002306bool HBasicBlock::IsSingleTryBoundary() const {
2307 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00002308}
2309
David Brazdil8d5b8b22015-03-24 10:51:52 +00002310bool HBasicBlock::EndsWithControlFlowInstruction() const {
2311 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
2312}
2313
Aart Bik4dc09e72018-05-11 14:40:31 -07002314bool HBasicBlock::EndsWithReturn() const {
2315 return !GetInstructions().IsEmpty() &&
2316 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
2317}
2318
David Brazdilb2bd1c52015-03-25 11:17:37 +00002319bool HBasicBlock::EndsWithIf() const {
2320 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
2321}
2322
David Brazdilffee3d32015-07-06 11:48:53 +01002323bool HBasicBlock::EndsWithTryBoundary() const {
2324 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
2325}
2326
David Brazdilb2bd1c52015-03-25 11:17:37 +00002327bool HBasicBlock::HasSinglePhi() const {
2328 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
2329}
2330
David Brazdild26a4112015-11-10 11:07:31 +00002331ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
2332 if (EndsWithTryBoundary()) {
2333 // The normal-flow successor of HTryBoundary is always stored at index zero.
2334 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
2335 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
2336 } else {
2337 // All successors of blocks not ending with TryBoundary are normal.
2338 return ArrayRef<HBasicBlock* const>(successors_);
2339 }
2340}
2341
2342ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
2343 if (EndsWithTryBoundary()) {
2344 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
2345 } else {
2346 // Blocks not ending with TryBoundary do not have exceptional successors.
2347 return ArrayRef<HBasicBlock* const>();
2348 }
2349}
2350
David Brazdilffee3d32015-07-06 11:48:53 +01002351bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00002352 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
2353 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
2354
2355 size_t length = handlers1.size();
2356 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01002357 return false;
2358 }
2359
David Brazdilb618ade2015-07-29 10:31:29 +01002360 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00002361 for (size_t i = 0; i < length; ++i) {
2362 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01002363 return false;
2364 }
2365 }
2366 return true;
2367}
2368
David Brazdil2d7352b2015-04-20 14:52:42 +01002369size_t HInstructionList::CountSize() const {
2370 size_t size = 0;
2371 HInstruction* current = first_instruction_;
2372 for (; current != nullptr; current = current->GetNext()) {
2373 size++;
2374 }
2375 return size;
2376}
2377
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002378void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
2379 for (HInstruction* current = first_instruction_;
2380 current != nullptr;
2381 current = current->GetNext()) {
2382 current->SetBlock(block);
2383 }
2384}
2385
2386void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
2387 DCHECK(Contains(cursor));
2388 if (!instruction_list.IsEmpty()) {
2389 if (cursor == last_instruction_) {
2390 last_instruction_ = instruction_list.last_instruction_;
2391 } else {
2392 cursor->next_->previous_ = instruction_list.last_instruction_;
2393 }
2394 instruction_list.last_instruction_->next_ = cursor->next_;
2395 cursor->next_ = instruction_list.first_instruction_;
2396 instruction_list.first_instruction_->previous_ = cursor;
2397 }
2398}
2399
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002400void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
2401 DCHECK(Contains(cursor));
2402 if (!instruction_list.IsEmpty()) {
2403 if (cursor == first_instruction_) {
2404 first_instruction_ = instruction_list.first_instruction_;
2405 } else {
2406 cursor->previous_->next_ = instruction_list.first_instruction_;
2407 }
2408 instruction_list.last_instruction_->next_ = cursor;
2409 instruction_list.first_instruction_->previous_ = cursor->previous_;
2410 cursor->previous_ = instruction_list.last_instruction_;
2411 }
2412}
2413
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002414void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00002415 if (IsEmpty()) {
2416 first_instruction_ = instruction_list.first_instruction_;
2417 last_instruction_ = instruction_list.last_instruction_;
2418 } else {
2419 AddAfter(last_instruction_, instruction_list);
2420 }
2421}
2422
David Brazdil2d7352b2015-04-20 14:52:42 +01002423void HBasicBlock::DisconnectAndDelete() {
2424 // Dominators must be removed after all the blocks they dominate. This way
2425 // a loop header is removed last, a requirement for correct loop information
2426 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00002427 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00002428
David Brazdil9eeebf62016-03-24 11:18:15 +00002429 // The following steps gradually remove the block from all its dependants in
2430 // post order (b/27683071).
2431
2432 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
2433 // We need to do this before step (4) which destroys the predecessor list.
2434 HBasicBlock* loop_update_start = this;
2435 if (IsLoopHeader()) {
2436 HLoopInformation* loop_info = GetLoopInformation();
2437 // All other blocks in this loop should have been removed because the header
2438 // was their dominator.
2439 // Note that we do not remove `this` from `loop_info` as it is unreachable.
2440 DCHECK(!loop_info->IsIrreducible());
2441 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
2442 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
2443 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01002444 }
2445
David Brazdil9eeebf62016-03-24 11:18:15 +00002446 // (2) Disconnect the block from its successors and update their phis.
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +01002447 DisconnectFromSuccessors();
David Brazdil9eeebf62016-03-24 11:18:15 +00002448
2449 // (3) Remove instructions and phis. Instructions should have no remaining uses
2450 // except in catch phis. If an instruction is used by a catch phi at `index`,
2451 // remove `index`-th input of all phis in the catch block since they are
2452 // guaranteed dead. Note that we may miss dead inputs this way but the
2453 // graph will always remain consistent.
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +01002454 RemoveCatchPhiUsesAndInstruction(/* building_dominator_tree = */ false);
David Brazdil9eeebf62016-03-24 11:18:15 +00002455
2456 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002457 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00002458 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00002459 // We should not see any back edges as they would have been removed by step (3).
Santiago Aboy Solanes872ec722022-02-18 14:10:25 +00002460 DCHECK_IMPLIES(IsInLoop(), !GetLoopInformation()->IsBackEdge(*predecessor));
David Brazdil9eeebf62016-03-24 11:18:15 +00002461
David Brazdil2d7352b2015-04-20 14:52:42 +01002462 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002463 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
2464 // This block is the only normal-flow successor of the TryBoundary which
2465 // makes `predecessor` dead. Since DCE removes blocks in post order,
2466 // exception handlers of this TryBoundary were already visited and any
2467 // remaining handlers therefore must be live. We remove `predecessor` from
2468 // their list of predecessors.
2469 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
2470 while (predecessor->GetSuccessors().size() > 1) {
2471 HBasicBlock* handler = predecessor->GetSuccessors()[1];
2472 DCHECK(handler->IsCatchBlock());
2473 predecessor->RemoveSuccessor(handler);
2474 handler->RemovePredecessor(predecessor);
2475 }
2476 }
2477
David Brazdil2d7352b2015-04-20 14:52:42 +01002478 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04002479 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
2480 if (num_pred_successors == 1u) {
2481 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002482 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
2483 // successor. Replace those with a HGoto.
2484 DCHECK(last_instruction->IsIf() ||
2485 last_instruction->IsPackedSwitch() ||
2486 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002487 predecessor->RemoveInstruction(last_instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002488 predecessor->AddInstruction(new (graph_->GetAllocator()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002489 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002490 // The predecessor has no remaining successors and therefore must be dead.
2491 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00002492 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04002493 predecessor->RemoveInstruction(last_instruction);
2494 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002495 // There are multiple successors left. The removed block might be a successor
2496 // of a PackedSwitch which will be completely removed (perhaps replaced with
2497 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2498 // case, leave `last_instruction` as is for now.
2499 DCHECK(last_instruction->IsPackedSwitch() ||
2500 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002501 }
David Brazdil46e2a392015-03-16 17:31:52 +00002502 }
Vladimir Marko60584552015-09-03 13:35:12 +00002503 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002504
David Brazdil9eeebf62016-03-24 11:18:15 +00002505 // (5) Remove the block from all loops it is included in. Skip the inner-most
2506 // loop if this is the loop header (see definition of `loop_update_start`)
2507 // because the loop header's predecessor list has been destroyed in step (4).
2508 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2509 HLoopInformation* loop_info = it.Current();
2510 loop_info->Remove(this);
2511 if (loop_info->IsBackEdge(*this)) {
2512 // If this was the last back edge of the loop, we deliberately leave the
2513 // loop in an inconsistent state and will fail GraphChecker unless the
2514 // entire loop is removed during the pass.
2515 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002516 }
2517 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002518
David Brazdil9eeebf62016-03-24 11:18:15 +00002519 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002520 dominator_->RemoveDominatedBlock(this);
2521 SetDominator(nullptr);
2522
David Brazdil9eeebf62016-03-24 11:18:15 +00002523 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002524 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002525 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002526}
2527
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +01002528void HBasicBlock::DisconnectFromSuccessors(const ArenaBitVector* visited) {
2529 for (HBasicBlock* successor : successors_) {
2530 // Delete this block from the list of predecessors.
2531 size_t this_index = successor->GetPredecessorIndexOf(this);
2532 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
2533
2534 if (visited != nullptr && !visited->IsBitSet(successor->GetBlockId())) {
2535 // `successor` itself is dead. Therefore, there is no need to update its phis.
2536 continue;
2537 }
2538
2539 DCHECK(!successor->predecessors_.empty());
2540
2541 // Remove this block's entries in the successor's phis. Skips exceptional
2542 // successors because catch phi inputs do not correspond to predecessor
2543 // blocks but throwing instructions. They are removed in `RemoveCatchPhiUses`.
2544 if (!successor->IsCatchBlock()) {
2545 if (successor->predecessors_.size() == 1u) {
2546 // The successor has just one predecessor left. Replace phis with the only
2547 // remaining input.
2548 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2549 HPhi* phi = phi_it.Current()->AsPhi();
2550 phi->ReplaceWith(phi->InputAt(1 - this_index));
2551 successor->RemovePhi(phi);
2552 }
2553 } else {
2554 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2555 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
2556 }
2557 }
2558 }
2559 }
2560 successors_.clear();
2561}
2562
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +01002563void HBasicBlock::RemoveCatchPhiUsesAndInstruction(bool building_dominator_tree) {
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +01002564 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2565 HInstruction* insn = it.Current();
2566 RemoveCatchPhiUsesOfDeadInstruction(insn);
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +01002567
2568 // If we are building the dominator tree, we removed all input records previously.
2569 // `RemoveInstruction` will try to remove them again but that's not something we support and we
2570 // will crash. We check here since we won't be checking that in RemoveInstruction.
2571 if (building_dominator_tree) {
2572 DCHECK(insn->GetUses().empty());
2573 DCHECK(insn->GetEnvUses().empty());
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +01002574 }
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +01002575 RemoveInstruction(insn, /* ensure_safety= */ !building_dominator_tree);
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +01002576 }
2577 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
2578 HPhi* insn = it.Current()->AsPhi();
2579 RemoveCatchPhiUsesOfDeadInstruction(insn);
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +01002580
2581 // If we are building the dominator tree, we removed all input records previously.
2582 // `RemovePhi` will try to remove them again but that's not something we support and we
2583 // will crash. We check here since we won't be checking that in RemovePhi.
2584 if (building_dominator_tree) {
2585 DCHECK(insn->GetUses().empty());
2586 DCHECK(insn->GetEnvUses().empty());
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +01002587 }
Santiago Aboy Solanes7023bf82022-08-19 10:28:11 +01002588 RemovePhi(insn, /* ensure_safety= */ !building_dominator_tree);
Santiago Aboy Solanesd48da352022-07-28 17:58:53 +01002589 }
2590}
2591
Aart Bik6b69e0a2017-01-11 10:20:43 -08002592void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2593 DCHECK(EndsWithControlFlowInstruction());
2594 RemoveInstruction(GetLastInstruction());
2595 instructions_.Add(other->GetInstructions());
2596 other->instructions_.SetBlockOfInstructions(this);
2597 other->instructions_.Clear();
2598}
2599
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002600void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002601 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002602 DCHECK(ContainsElement(dominated_blocks_, other));
2603 DCHECK_EQ(GetSingleSuccessor(), other);
2604 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002605 DCHECK(other->GetPhis().IsEmpty());
2606
David Brazdil2d7352b2015-04-20 14:52:42 +01002607 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002608 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002609
David Brazdil2d7352b2015-04-20 14:52:42 +01002610 // Remove `other` from the loops it is included in.
2611 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2612 HLoopInformation* loop_info = it.Current();
2613 loop_info->Remove(other);
2614 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002615 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002616 }
2617 }
2618
2619 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002620 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002621 for (HBasicBlock* successor : other->GetSuccessors()) {
2622 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002623 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002624 successors_.swap(other->successors_);
2625 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002626
David Brazdil2d7352b2015-04-20 14:52:42 +01002627 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002628 RemoveDominatedBlock(other);
2629 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002630 dominated->SetDominator(this);
2631 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002632 dominated_blocks_.insert(
2633 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002634 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002635 other->dominator_ = nullptr;
2636
2637 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002638 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002639
2640 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002641 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002642 other->SetGraph(nullptr);
2643}
2644
2645void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2646 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002647 DCHECK(GetDominatedBlocks().empty());
2648 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002649 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002650 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002651 DCHECK(other->GetPhis().IsEmpty());
2652 DCHECK(!other->IsInLoop());
2653
2654 // Move instructions from `other` to `this`.
2655 instructions_.Add(other->GetInstructions());
2656 other->instructions_.SetBlockOfInstructions(this);
2657
2658 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002659 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002660 for (HBasicBlock* successor : other->GetSuccessors()) {
2661 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002662 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002663 successors_.swap(other->successors_);
2664 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002665
2666 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002667 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002668 dominated->SetDominator(this);
2669 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002670 dominated_blocks_.insert(
2671 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002672 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002673 other->dominator_ = nullptr;
2674 other->graph_ = nullptr;
2675}
2676
2677void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002678 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002679 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002680 predecessor->ReplaceSuccessor(this, other);
2681 }
Vladimir Marko60584552015-09-03 13:35:12 +00002682 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002683 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002684 successor->ReplacePredecessor(this, other);
2685 }
Vladimir Marko60584552015-09-03 13:35:12 +00002686 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2687 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002688 }
2689 GetDominator()->ReplaceDominatedBlock(this, other);
2690 other->SetDominator(GetDominator());
2691 dominator_ = nullptr;
2692 graph_ = nullptr;
2693}
2694
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002695void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002696 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002697 DCHECK(block->GetSuccessors().empty());
2698 DCHECK(block->GetPredecessors().empty());
2699 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002700 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002701 DCHECK(block->GetInstructions().IsEmpty());
2702 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002703
David Brazdilc7af85d2015-05-26 12:05:55 +01002704 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002705 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002706 }
2707
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002708 RemoveElement(reverse_post_order_, block);
2709 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002710 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002711}
2712
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002713void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2714 HBasicBlock* reference,
Santiago Aboy Solanes8efb1a62022-06-24 11:16:35 +01002715 bool replace_if_back_edge,
2716 bool has_more_specific_try_catch_info) {
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002717 if (block->IsLoopHeader()) {
2718 // Clear the information of which blocks are contained in that loop. Since the
2719 // information is stored as a bit vector based on block ids, we have to update
2720 // it, as those block ids were specific to the callee graph and we are now adding
2721 // these blocks to the caller graph.
2722 block->GetLoopInformation()->ClearAllBlocks();
2723 }
2724
2725 // If not already in a loop, update the loop information.
2726 if (!block->IsInLoop()) {
2727 block->SetLoopInformation(reference->GetLoopInformation());
2728 }
2729
2730 // If the block is in a loop, update all its outward loops.
2731 HLoopInformation* loop_info = block->GetLoopInformation();
2732 if (loop_info != nullptr) {
2733 for (HLoopInformationOutwardIterator loop_it(*block);
2734 !loop_it.Done();
2735 loop_it.Advance()) {
2736 loop_it.Current()->Add(block);
2737 }
2738 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2739 loop_info->ReplaceBackEdge(reference, block);
2740 }
2741 }
2742
Santiago Aboy Solanes343b9d92022-12-06 18:13:10 +00002743 DCHECK_IMPLIES(has_more_specific_try_catch_info, !reference->IsTryBlock())
2744 << "We don't allow to inline try catches inside of other try blocks.";
Santiago Aboy Solanes8efb1a62022-06-24 11:16:35 +01002745
2746 // Update the TryCatchInformation, if we are not inlining a try catch.
2747 if (!has_more_specific_try_catch_info) {
2748 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2749 TryCatchInformation* try_catch_info =
2750 reference->IsTryBlock() ? reference->GetTryCatchInformation() : nullptr;
2751 block->SetTryCatchInformation(try_catch_info);
2752 }
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002753}
2754
Calin Juravle2e768302015-07-28 14:41:11 +00002755HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002756 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002757 // Update the environments in this graph to have the invoke's environment
2758 // as parent.
2759 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002760 // Skip the entry block, we do not need to update the entry's suspend check.
2761 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002762 for (HInstructionIterator instr_it(block->GetInstructions());
2763 !instr_it.Done();
2764 instr_it.Advance()) {
2765 HInstruction* current = instr_it.Current();
2766 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002767 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002768 current->GetEnvironment()->SetAndCopyParentChain(
Vladimir Markoca6fff82017-10-03 14:49:14 +01002769 outer_graph->GetAllocator(), invoke->GetEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002770 }
2771 }
2772 }
2773 }
2774 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002775
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002776 if (HasBoundsChecks()) {
2777 outer_graph->SetHasBoundsChecks(true);
2778 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002779 if (HasLoops()) {
2780 outer_graph->SetHasLoops(true);
2781 }
2782 if (HasIrreducibleLoops()) {
2783 outer_graph->SetHasIrreducibleLoops(true);
2784 }
Vladimir Markod3e9c622020-08-05 12:20:28 +01002785 if (HasDirectCriticalNativeCall()) {
2786 outer_graph->SetHasDirectCriticalNativeCall(true);
2787 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002788 if (HasTryCatch()) {
2789 outer_graph->SetHasTryCatch(true);
2790 }
Santiago Aboy Solanesbf778f02022-12-15 14:58:21 +00002791 if (HasMonitorOperations()) {
2792 outer_graph->SetHasMonitorOperations(true);
2793 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002794 if (HasSIMD()) {
2795 outer_graph->SetHasSIMD(true);
2796 }
Santiago Aboy Solanes78f3d3a2022-07-15 14:30:05 +01002797 if (HasAlwaysThrowingInvokes()) {
2798 outer_graph->SetHasAlwaysThrowingInvokes(true);
2799 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002800
Calin Juravle2e768302015-07-28 14:41:11 +00002801 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002802 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002803 // Inliner already made sure we don't inline methods that always throw.
2804 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002805 // Simple case of an entry block, a body block, and an exit block.
2806 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002807 HBasicBlock* body = GetBlocks()[1];
2808 DCHECK(GetBlocks()[0]->IsEntryBlock());
2809 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002810 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002811 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002812 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002813
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002814 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2815 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002816 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002817
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002818 // Replace the invoke with the return value of the inlined graph.
2819 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002820 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002821 } else {
2822 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002823 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002824
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002825 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002826 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002827 // Need to inline multiple blocks. We split `invoke`'s block
2828 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002829 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002830 // with the second half.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002831 ArenaAllocator* allocator = outer_graph->GetAllocator();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002832 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002833 // Note that we split before the invoke only to simplify polymorphic inlining.
2834 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002835
Vladimir Markoec7802a2015-10-01 20:57:57 +01002836 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002837 DCHECK(!first->IsInLoop());
Santiago Aboy Solanes343b9d92022-12-06 18:13:10 +00002838 DCHECK(first->GetTryCatchInformation() == nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002839 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002840 exit_block_->ReplaceWith(to);
2841
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002842 // Update the meta information surrounding blocks:
2843 // (1) the graph they are now in,
2844 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002845 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002846 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002847 // Note that we do not need to update catch phi inputs because they
2848 // correspond to the register file of the outer method which the inlinee
2849 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002850
2851 // We don't add the entry block, the exit block, and the first block, which
2852 // has been merged with `at`.
2853 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2854
2855 // We add the `to` block.
2856 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002857 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002858 + kNumberOfNewBlocksInCaller;
2859
2860 // Find the location of `at` in the outer graph's reverse post order. The new
2861 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002862 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002863 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2864
David Brazdil95177982015-10-30 12:56:58 -05002865 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2866 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002867 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002868 if (current != exit_block_ && current != entry_block_ && current != first) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002869 DCHECK(current->GetGraph() == this);
2870 current->SetGraph(outer_graph);
2871 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002872 outer_graph->reverse_post_order_[++index_of_at] = current;
Santiago Aboy Solanes8efb1a62022-06-24 11:16:35 +01002873 UpdateLoopAndTryInformationOfNewBlock(current,
2874 at,
2875 /* replace_if_back_edge= */ false,
2876 current->GetTryCatchInformation() != nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002877 }
2878 }
2879
David Brazdil95177982015-10-30 12:56:58 -05002880 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002881 to->SetGraph(outer_graph);
2882 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002883 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002884 // Only `to` can become a back edge, as the inlined blocks
2885 // are predecessors of `to`.
Andreas Gampe3db70682018-12-26 15:12:03 -08002886 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge= */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002887
David Brazdil3f523062016-02-29 16:53:33 +00002888 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002889 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
Santiago Aboy Solanes8efb1a62022-06-24 11:16:35 +01002890 // to now get the outer graph exit block as successor.
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002891 HPhi* return_value_phi = nullptr;
2892 bool rerun_dominance = false;
2893 bool rerun_loop_analysis = false;
2894 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2895 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002896 HInstruction* last = predecessor->GetLastInstruction();
Santiago Aboy Solanes8efb1a62022-06-24 11:16:35 +01002897
2898 // At this point we might either have:
Santiago Aboy Solanes69293b02022-12-08 19:10:57 +00002899 // A) Return/ReturnVoid/Throw as the last instruction, or
2900 // B) `Return/ReturnVoid/Throw->TryBoundary` as the last instruction chain
Santiago Aboy Solanes8efb1a62022-06-24 11:16:35 +01002901
2902 const bool saw_try_boundary = last->IsTryBoundary();
2903 if (saw_try_boundary) {
2904 DCHECK(predecessor->IsSingleTryBoundary());
2905 DCHECK(!last->AsTryBoundary()->IsEntry());
2906 predecessor = predecessor->GetSinglePredecessor();
2907 last = predecessor->GetLastInstruction();
2908 }
2909
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002910 if (last->IsThrow()) {
Santiago Aboy Solanesb9df1372022-12-08 15:15:17 +00002911 if (at->IsTryBlock()) {
2912 DCHECK(!saw_try_boundary) << "We don't support inlining of try blocks into try blocks.";
2913 // Create a TryBoundary of kind:exit and point it to the Exit block.
2914 HBasicBlock* new_block = outer_graph->SplitEdge(predecessor, to);
2915 new_block->AddInstruction(
2916 new (allocator) HTryBoundary(HTryBoundary::BoundaryKind::kExit, last->GetDexPc()));
2917 new_block->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2918
2919 // Copy information from the predecessor.
2920 new_block->SetLoopInformation(predecessor->GetLoopInformation());
2921 TryCatchInformation* try_catch_info = predecessor->GetTryCatchInformation();
2922 new_block->SetTryCatchInformation(try_catch_info);
2923 for (HBasicBlock* xhandler :
2924 try_catch_info->GetTryEntry().GetBlock()->GetExceptionalSuccessors()) {
2925 new_block->AddSuccessor(xhandler);
2926 }
2927 DCHECK(try_catch_info->GetTryEntry().HasSameExceptionHandlersAs(
2928 *new_block->GetLastInstruction()->AsTryBoundary()));
2929 } else {
2930 // We either have `Throw->TryBoundary` or `Throw`. We want to point the whole chain to the
2931 // exit, so we recompute `predecessor`
2932 predecessor = to->GetPredecessors()[pred];
2933 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2934 }
2935
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002936 --pred;
2937 // We need to re-run dominance information, as the exit block now has
Santiago Aboy Solanesb9df1372022-12-08 15:15:17 +00002938 // a new predecessor and potential new dominator.
2939 // TODO(solanes): See if it's worth it to hand-modify the domination chain instead of
2940 // rerunning the dominance for the whole graph.
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002941 rerun_dominance = true;
2942 if (predecessor->GetLoopInformation() != nullptr) {
Santiago Aboy Solanesb9df1372022-12-08 15:15:17 +00002943 // The loop information might have changed e.g. `predecessor` might not be in a loop
2944 // anymore. We only do this if `predecessor` has loop information as it is impossible for
2945 // predecessor to end up in a loop if it wasn't in one before.
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002946 rerun_loop_analysis = true;
2947 }
2948 } else {
2949 if (last->IsReturnVoid()) {
2950 DCHECK(return_value == nullptr);
2951 DCHECK(return_value_phi == nullptr);
2952 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002953 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002954 if (return_value_phi != nullptr) {
2955 return_value_phi->AddInput(last->InputAt(0));
2956 } else if (return_value == nullptr) {
2957 return_value = last->InputAt(0);
2958 } else {
2959 // There will be multiple returns.
2960 return_value_phi = new (allocator) HPhi(
2961 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2962 to->AddPhi(return_value_phi);
2963 return_value_phi->AddInput(return_value);
2964 return_value_phi->AddInput(last->InputAt(0));
2965 return_value = return_value_phi;
2966 }
David Brazdil3f523062016-02-29 16:53:33 +00002967 }
2968 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2969 predecessor->RemoveInstruction(last);
Santiago Aboy Solanes69293b02022-12-08 19:10:57 +00002970
2971 if (saw_try_boundary) {
2972 predecessor = to->GetPredecessors()[pred];
2973 DCHECK(predecessor->EndsWithTryBoundary());
2974 DCHECK_EQ(predecessor->GetNormalSuccessors().size(), 1u);
2975 if (predecessor->GetSuccessors()[0]->GetPredecessors().size() > 1) {
2976 outer_graph->SplitCriticalEdge(predecessor, to);
2977 rerun_dominance = true;
2978 if (predecessor->GetLoopInformation() != nullptr) {
2979 rerun_loop_analysis = true;
2980 }
2981 }
2982 }
David Brazdil3f523062016-02-29 16:53:33 +00002983 }
2984 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002985 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002986 DCHECK(!outer_graph->HasIrreducibleLoops())
2987 << "Recomputing loop information in graphs with irreducible loops "
2988 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002989 outer_graph->ClearLoopInformation();
2990 outer_graph->ClearDominanceInformation();
2991 outer_graph->BuildDominatorTree();
2992 } else if (rerun_dominance) {
2993 outer_graph->ClearDominanceInformation();
2994 outer_graph->ComputeDominanceInformation();
2995 }
David Brazdil3f523062016-02-29 16:53:33 +00002996 }
David Brazdil05144f42015-04-16 15:18:00 +01002997
2998 // Walk over the entry block and:
2999 // - Move constants from the entry block to the outer_graph's entry block,
3000 // - Replace HParameterValue instructions with their real value.
3001 // - Remove suspend checks, that hold an environment.
3002 // We must do this after the other blocks have been inlined, otherwise ids of
3003 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01003004 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01003005 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
3006 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01003007 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01003008 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01003009 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01003010 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01003011 replacement = outer_graph->GetIntConstant(
3012 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01003013 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01003014 replacement = outer_graph->GetLongConstant(
3015 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00003016 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01003017 replacement = outer_graph->GetFloatConstant(
3018 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00003019 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01003020 replacement = outer_graph->GetDoubleConstant(
3021 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01003022 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01003023 if (kIsDebugBuild
3024 && invoke->IsInvokeStaticOrDirect()
3025 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
3026 // Ensure we do not use the last input of `invoke`, as it
3027 // contains a clinit check which is not an actual argument.
3028 size_t last_input_index = invoke->InputCount() - 1;
3029 DCHECK(parameter_index != last_input_index);
3030 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01003031 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01003032 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01003033 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01003034 } else {
Mythri Alle5097f832021-11-02 14:52:30 +00003035 // It is OK to ignore MethodEntryHook for inlined functions.
3036 // In debug mode we don't inline and in release mode method
3037 // tracing is best effort so OK to ignore them.
3038 DCHECK(current->IsGoto() || current->IsSuspendCheck() || current->IsMethodEntryHook());
David Brazdil05144f42015-04-16 15:18:00 +01003039 entry_block_->RemoveInstruction(current);
3040 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01003041 if (replacement != nullptr) {
3042 current->ReplaceWith(replacement);
3043 // If the current is the return value then we need to update the latter.
3044 if (current == return_value) {
3045 DCHECK_EQ(entry_block_, return_value->GetBlock());
3046 return_value = replacement;
3047 }
3048 }
3049 }
3050
Calin Juravle2e768302015-07-28 14:41:11 +00003051 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00003052}
3053
Mingyao Yang3584bce2015-05-19 16:01:59 -07003054/*
3055 * Loop will be transformed to:
3056 * old_pre_header
3057 * |
3058 * if_block
3059 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08003060 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07003061 * \ /
3062 * new_pre_header
3063 * |
3064 * header
3065 */
3066void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
3067 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08003068 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07003069
Aart Bik3fc7f352015-11-20 22:03:03 -08003070 // Need extra block to avoid critical edge.
Vladimir Markoca6fff82017-10-03 14:49:14 +01003071 HBasicBlock* if_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
3072 HBasicBlock* true_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
3073 HBasicBlock* false_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
3074 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07003075 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08003076 AddBlock(true_block);
3077 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07003078 AddBlock(new_pre_header);
3079
Aart Bik3fc7f352015-11-20 22:03:03 -08003080 header->ReplacePredecessor(old_pre_header, new_pre_header);
3081 old_pre_header->successors_.clear();
3082 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07003083
Aart Bik3fc7f352015-11-20 22:03:03 -08003084 old_pre_header->AddSuccessor(if_block);
3085 if_block->AddSuccessor(true_block); // True successor
3086 if_block->AddSuccessor(false_block); // False successor
3087 true_block->AddSuccessor(new_pre_header);
3088 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07003089
Aart Bik3fc7f352015-11-20 22:03:03 -08003090 old_pre_header->dominated_blocks_.push_back(if_block);
3091 if_block->SetDominator(old_pre_header);
3092 if_block->dominated_blocks_.push_back(true_block);
3093 true_block->SetDominator(if_block);
3094 if_block->dominated_blocks_.push_back(false_block);
3095 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00003096 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07003097 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00003098 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07003099 header->SetDominator(new_pre_header);
3100
Aart Bik3fc7f352015-11-20 22:03:03 -08003101 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01003102 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07003103 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01003104 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08003105 reverse_post_order_[index_of_header++] = true_block;
3106 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01003107 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07003108
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00003109 // The pre_header can never be a back edge of a loop.
3110 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
3111 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
3112 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08003113 if_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00003114 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08003115 true_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00003116 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08003117 false_block, old_pre_header, /* replace_if_back_edge= */ false);
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00003118 UpdateLoopAndTryInformationOfNewBlock(
Andreas Gampe3db70682018-12-26 15:12:03 -08003119 new_pre_header, old_pre_header, /* replace_if_back_edge= */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07003120}
3121
Aart Bikf8f5a162017-02-06 15:35:29 -08003122HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
3123 HBasicBlock* body,
3124 HBasicBlock* exit) {
3125 DCHECK(header->IsLoopHeader());
3126 HLoopInformation* loop = header->GetLoopInformation();
3127
3128 // Add new loop blocks.
Vladimir Markoca6fff82017-10-03 14:49:14 +01003129 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
3130 HBasicBlock* new_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
3131 HBasicBlock* new_body = new (allocator_) HBasicBlock(this, header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08003132 AddBlock(new_pre_header);
3133 AddBlock(new_header);
3134 AddBlock(new_body);
3135
3136 // Set up control flow.
3137 header->ReplaceSuccessor(exit, new_pre_header);
3138 new_pre_header->AddSuccessor(new_header);
3139 new_header->AddSuccessor(exit);
3140 new_header->AddSuccessor(new_body);
3141 new_body->AddSuccessor(new_header);
3142
3143 // Set up dominators.
3144 header->ReplaceDominatedBlock(exit, new_pre_header);
3145 new_pre_header->SetDominator(header);
3146 new_pre_header->dominated_blocks_.push_back(new_header);
3147 new_header->SetDominator(new_pre_header);
3148 new_header->dominated_blocks_.push_back(new_body);
3149 new_body->SetDominator(new_header);
3150 new_header->dominated_blocks_.push_back(exit);
3151 exit->SetDominator(new_header);
3152
3153 // Fix reverse post order.
3154 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
3155 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
3156 reverse_post_order_[++index_of_header] = new_pre_header;
3157 reverse_post_order_[++index_of_header] = new_header;
3158 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
3159 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
3160 reverse_post_order_[index_of_body] = new_body;
3161
Aart Bikb07d1bc2017-04-05 10:03:15 -07003162 // Add gotos and suspend check (client must add conditional in header).
Vladimir Markoca6fff82017-10-03 14:49:14 +01003163 new_pre_header->AddInstruction(new (allocator_) HGoto());
3164 HSuspendCheck* suspend_check = new (allocator_) HSuspendCheck(header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08003165 new_header->AddInstruction(suspend_check);
Vladimir Markoca6fff82017-10-03 14:49:14 +01003166 new_body->AddInstruction(new (allocator_) HGoto());
Stelios Ioannouc54cc7c2021-07-09 17:06:03 +01003167 DCHECK(loop->GetSuspendCheck() != nullptr);
Aart Bikb07d1bc2017-04-05 10:03:15 -07003168 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
3169 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08003170
3171 // Update loop information.
3172 new_header->AddBackEdge(new_body);
3173 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
3174 new_header->GetLoopInformation()->Populate();
3175 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
3176 HLoopInformationOutwardIterator it(*new_header);
3177 for (it.Advance(); !it.Done(); it.Advance()) {
3178 it.Current()->Add(new_pre_header);
3179 it.Current()->Add(new_header);
3180 it.Current()->Add(new_body);
3181 }
3182 return new_pre_header;
3183}
3184
David Brazdilf5552582015-12-27 13:36:12 +00003185static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003186 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00003187 if (rti.IsValid()) {
3188 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
3189 << " upper_bound_rti: " << upper_bound_rti
3190 << " rti: " << rti;
Santiago Aboy Solanes872ec722022-02-18 14:10:25 +00003191 DCHECK_IMPLIES(upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes(), rti.IsExact())
Nicolas Geoffray18401b72016-03-11 13:35:51 +00003192 << " upper_bound_rti: " << upper_bound_rti
3193 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00003194 }
3195}
3196
Calin Juravle2e768302015-07-28 14:41:11 +00003197void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
3198 if (kIsDebugBuild) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003199 DCHECK_EQ(GetType(), DataType::Type::kReference);
Calin Juravle2e768302015-07-28 14:41:11 +00003200 ScopedObjectAccess soa(Thread::Current());
3201 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
3202 if (IsBoundType()) {
3203 // Having the test here spares us from making the method virtual just for
3204 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00003205 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00003206 }
3207 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00003208 reference_type_handle_ = rti.GetTypeHandle();
3209 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00003210}
3211
Artem Serov4d277ba2018-06-05 20:54:42 +01003212bool HBoundType::InstructionDataEquals(const HInstruction* other) const {
3213 const HBoundType* other_bt = other->AsBoundType();
3214 ScopedObjectAccess soa(Thread::Current());
3215 return GetUpperBound().IsEqual(other_bt->GetUpperBound()) &&
3216 GetUpperCanBeNull() == other_bt->GetUpperCanBeNull() &&
3217 CanBeNull() == other_bt->CanBeNull();
3218}
3219
David Brazdilf5552582015-12-27 13:36:12 +00003220void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
3221 if (kIsDebugBuild) {
3222 ScopedObjectAccess soa(Thread::Current());
3223 DCHECK(upper_bound.IsValid());
3224 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
3225 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
3226 }
3227 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00003228 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00003229}
3230
Vladimir Markoa1de9182016-02-25 11:37:38 +00003231ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00003232 if (kIsDebugBuild) {
3233 ScopedObjectAccess soa(Thread::Current());
3234 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00003235 if (!is_exact) {
3236 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
3237 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
3238 }
Calin Juravle2e768302015-07-28 14:41:11 +00003239 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00003240 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00003241}
3242
Calin Juravleacf735c2015-02-12 15:25:22 +00003243std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
3244 ScopedObjectAccess soa(Thread::Current());
3245 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00003246 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07003247 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00003248 << " is_exact=" << rhs.IsExact()
3249 << " ]";
3250 return os;
3251}
3252
Mark Mendellc4701932015-04-10 13:18:51 -04003253bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
3254 // For now, assume that instructions in different blocks may use the
3255 // environment.
3256 // TODO: Use the control flow to decide if this is true.
3257 if (GetBlock() != other->GetBlock()) {
3258 return true;
3259 }
3260
3261 // We know that we are in the same block. Walk from 'this' to 'other',
3262 // checking to see if there is any instruction with an environment.
3263 HInstruction* current = this;
3264 for (; current != other && current != nullptr; current = current->GetNext()) {
3265 // This is a conservative check, as the instruction result may not be in
3266 // the referenced environment.
3267 if (current->HasEnvironment()) {
3268 return true;
3269 }
3270 }
3271
3272 // We should have been called with 'this' before 'other' in the block.
3273 // Just confirm this.
3274 DCHECK(current != nullptr);
3275 return false;
3276}
3277
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01003278void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003279 IntrinsicNeedsEnvironment needs_env,
Aart Bik5d75afe2015-12-14 11:57:01 -08003280 IntrinsicSideEffects side_effects,
3281 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01003282 intrinsic_ = intrinsic;
3283 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00003284
Aart Bik5d75afe2015-12-14 11:57:01 -08003285 // Adjust method's side effects from intrinsic table.
3286 switch (side_effects) {
3287 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
3288 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
3289 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
3290 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
3291 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00003292
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003293 if (needs_env == kNoEnvironment) {
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00003294 opt.SetDoesNotNeedEnvironment();
3295 } else {
3296 // If we need an environment, that means there will be a call, which can trigger GC.
3297 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
3298 }
Aart Bik5d75afe2015-12-14 11:57:01 -08003299 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08003300 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01003301}
3302
David Brazdil6de19382016-01-08 17:37:10 +00003303bool HNewInstance::IsStringAlloc() const {
Alex Lightd109e302018-06-27 10:25:41 -07003304 return GetEntrypoint() == kQuickAllocStringObject;
David Brazdil6de19382016-01-08 17:37:10 +00003305}
3306
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01003307bool HInvoke::NeedsEnvironment() const {
3308 if (!IsIntrinsic()) {
3309 return true;
3310 }
3311 IntrinsicOptimizations opt(*this);
3312 return !opt.GetDoesNotNeedEnvironment();
3313}
3314
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00003315const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
3316 ArtMethod* caller = GetEnvironment()->GetMethod();
3317 ScopedObjectAccess soa(Thread::Current());
3318 // `caller` is null for a top-level graph representing a method whose declaring
3319 // class was not resolved.
3320 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
3321}
3322
Vladimir Markofbb184a2015-11-13 14:47:00 +00003323std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
3324 switch (rhs) {
3325 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
3326 return os << "explicit";
3327 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
3328 return os << "implicit";
3329 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
3330 return os << "none";
3331 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00003332 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
3333 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00003334 }
3335}
3336
Vladimir Markoac27ac02021-02-01 09:31:02 +00003337bool HInvokeVirtual::CanDoImplicitNullCheckOn(HInstruction* obj) const {
3338 if (obj != InputAt(0)) {
3339 return false;
3340 }
3341 switch (GetIntrinsic()) {
Vladimir Marko5e060ee2021-02-23 10:56:42 +00003342 case Intrinsics::kNone:
3343 return true;
Vladimir Markoac27ac02021-02-01 09:31:02 +00003344 case Intrinsics::kReferenceRefersTo:
3345 return true;
3346 default:
3347 // TODO: Add implicit null checks in more intrinsics.
3348 return false;
3349 }
3350}
3351
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01003352bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
3353 const HLoadClass* other_load_class = other->AsLoadClass();
3354 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
3355 // names rather than type indexes. However, we shall also have to re-think the hash code.
3356 if (type_index_ != other_load_class->type_index_ ||
3357 GetPackedFields() != other_load_class->GetPackedFields()) {
3358 return false;
3359 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00003360 switch (GetLoadKind()) {
Vladimir Markoe47f60c2018-02-21 13:43:28 +00003361 case LoadKind::kBootImageRelRo:
Vladimir Marko8e524ad2018-07-13 10:27:43 +01003362 case LoadKind::kJitBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00003363 case LoadKind::kJitTableAddress: {
3364 ScopedObjectAccess soa(Thread::Current());
3365 return GetClass().Get() == other_load_class->GetClass().Get();
3366 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00003367 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00003368 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00003369 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01003370 }
3371}
3372
Vladimir Marko372f10e2016-05-17 16:30:10 +01003373bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
3374 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01003375 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
3376 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003377 if (string_index_ != other_load_string->string_index_ ||
3378 GetPackedFields() != other_load_string->GetPackedFields()) {
3379 return false;
3380 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00003381 switch (GetLoadKind()) {
Vladimir Markoe47f60c2018-02-21 13:43:28 +00003382 case LoadKind::kBootImageRelRo:
Vladimir Marko8e524ad2018-07-13 10:27:43 +01003383 case LoadKind::kJitBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00003384 case LoadKind::kJitTableAddress: {
3385 ScopedObjectAccess soa(Thread::Current());
3386 return GetString().Get() == other_load_string->GetString().Get();
3387 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00003388 default:
3389 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00003390 }
3391}
3392
Mark Mendellc4701932015-04-10 13:18:51 -04003393void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01003394 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
3395 HEnvironment* user = use.GetUser();
3396 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04003397 }
Vladimir Marko46817b82016-03-29 12:21:58 +01003398 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04003399}
3400
Artem Serovcced8ba2017-07-19 18:18:09 +01003401HInstruction* ReplaceInstrOrPhiByClone(HInstruction* instr) {
3402 HInstruction* clone = instr->Clone(instr->GetBlock()->GetGraph()->GetAllocator());
3403 HBasicBlock* block = instr->GetBlock();
3404
3405 if (instr->IsPhi()) {
3406 HPhi* phi = instr->AsPhi();
3407 DCHECK(!phi->HasEnvironment());
3408 HPhi* phi_clone = clone->AsPhi();
3409 block->ReplaceAndRemovePhiWith(phi, phi_clone);
3410 } else {
3411 block->ReplaceAndRemoveInstructionWith(instr, clone);
3412 if (instr->HasEnvironment()) {
3413 clone->CopyEnvironmentFrom(instr->GetEnvironment());
3414 HLoopInformation* loop_info = block->GetLoopInformation();
3415 if (instr->IsSuspendCheck() && loop_info != nullptr) {
3416 loop_info->SetSuspendCheck(clone->AsSuspendCheck());
3417 }
3418 }
3419 }
3420 return clone;
3421}
3422
Roland Levillainc9b21f82016-03-23 16:36:59 +00003423// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05003424HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01003425 ArenaAllocator* allocator = GetAllocator();
Mark Mendellf6529172015-11-17 11:16:56 -05003426
3427 if (cond->IsCondition() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003428 !DataType::IsFloatingPointType(cond->InputAt(0)->GetType())) {
Mark Mendellf6529172015-11-17 11:16:56 -05003429 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
3430 HInstruction* lhs = cond->InputAt(0);
3431 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00003432 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05003433 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
3434 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
3435 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
3436 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
3437 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
3438 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
3439 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
3440 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
3441 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
3442 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
3443 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00003444 default:
3445 LOG(FATAL) << "Unexpected condition";
3446 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05003447 }
3448 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3449 return replacement;
3450 } else if (cond->IsIntConstant()) {
3451 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00003452 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05003453 return GetIntConstant(1);
3454 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00003455 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05003456 return GetIntConstant(0);
3457 }
3458 } else {
3459 HInstruction* replacement = new (allocator) HBooleanNot(cond);
3460 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3461 return replacement;
3462 }
3463}
3464
Roland Levillainc9285912015-12-18 10:38:42 +00003465std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
3466 os << "["
3467 << " source=" << rhs.GetSource()
3468 << " destination=" << rhs.GetDestination()
3469 << " type=" << rhs.GetType()
3470 << " instruction=";
3471 if (rhs.GetInstruction() != nullptr) {
3472 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
3473 } else {
3474 os << "null";
3475 }
3476 os << " ]";
3477 return os;
3478}
3479
Roland Levillain86503782016-02-11 19:07:30 +00003480std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
3481 switch (rhs) {
3482 case TypeCheckKind::kUnresolvedCheck:
3483 return os << "unresolved_check";
3484 case TypeCheckKind::kExactCheck:
3485 return os << "exact_check";
3486 case TypeCheckKind::kClassHierarchyCheck:
3487 return os << "class_hierarchy_check";
3488 case TypeCheckKind::kAbstractClassCheck:
3489 return os << "abstract_class_check";
3490 case TypeCheckKind::kInterfaceCheck:
3491 return os << "interface_check";
3492 case TypeCheckKind::kArrayObjectCheck:
3493 return os << "array_object_check";
3494 case TypeCheckKind::kArrayCheck:
3495 return os << "array_check";
Vladimir Marko175e7862018-03-27 09:03:13 +00003496 case TypeCheckKind::kBitstringCheck:
3497 return os << "bitstring_check";
Roland Levillain86503782016-02-11 19:07:30 +00003498 default:
3499 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
3500 UNREACHABLE();
3501 }
3502}
3503
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003504// Check that intrinsic enum values fit within space set aside in ArtMethod modifier flags.
3505#define CHECK_INTRINSICS_ENUM_VALUES(Name, InvokeType, _, SideEffects, Exceptions, ...) \
3506 static_assert( \
3507 static_cast<uint32_t>(Intrinsics::k ## Name) <= (kAccIntrinsicBits >> CTZ(kAccIntrinsicBits)), \
3508 "Instrinsics enumeration space overflow.");
3509#include "intrinsics_list.h"
3510 INTRINSICS_LIST(CHECK_INTRINSICS_ENUM_VALUES)
3511#undef INTRINSICS_LIST
3512#undef CHECK_INTRINSICS_ENUM_VALUES
3513
3514// Function that returns whether an intrinsic needs an environment or not.
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003515static inline IntrinsicNeedsEnvironment NeedsEnvironmentIntrinsic(Intrinsics i) {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003516 switch (i) {
3517 case Intrinsics::kNone:
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003518 return kNeedsEnvironment; // Non-sensical for intrinsic.
3519#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnv, SideEffects, Exceptions, ...) \
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003520 case Intrinsics::k ## Name: \
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003521 return NeedsEnv;
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003522#include "intrinsics_list.h"
3523 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3524#undef INTRINSICS_LIST
3525#undef OPTIMIZING_INTRINSICS
3526 }
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003527 return kNeedsEnvironment;
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003528}
3529
3530// Function that returns whether an intrinsic has side effects.
3531static inline IntrinsicSideEffects GetSideEffectsIntrinsic(Intrinsics i) {
3532 switch (i) {
3533 case Intrinsics::kNone:
3534 return kAllSideEffects;
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003535#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnv, SideEffects, Exceptions, ...) \
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003536 case Intrinsics::k ## Name: \
3537 return SideEffects;
3538#include "intrinsics_list.h"
3539 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3540#undef INTRINSICS_LIST
3541#undef OPTIMIZING_INTRINSICS
3542 }
3543 return kAllSideEffects;
3544}
3545
3546// Function that returns whether an intrinsic can throw exceptions.
3547static inline IntrinsicExceptions GetExceptionsIntrinsic(Intrinsics i) {
3548 switch (i) {
3549 case Intrinsics::kNone:
3550 return kCanThrow;
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003551#define OPTIMIZING_INTRINSICS(Name, InvokeType, NeedsEnv, SideEffects, Exceptions, ...) \
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003552 case Intrinsics::k ## Name: \
3553 return Exceptions;
3554#include "intrinsics_list.h"
3555 INTRINSICS_LIST(OPTIMIZING_INTRINSICS)
3556#undef INTRINSICS_LIST
3557#undef OPTIMIZING_INTRINSICS
3558 }
3559 return kCanThrow;
3560}
3561
3562void HInvoke::SetResolvedMethod(ArtMethod* method) {
Andra Danciua0130e82020-07-23 12:34:56 +00003563 if (method != nullptr && method->IsIntrinsic()) {
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003564 Intrinsics intrinsic = static_cast<Intrinsics>(method->GetIntrinsic());
3565 SetIntrinsic(intrinsic,
Nicolas Geoffray8f2eb252020-11-06 13:39:54 +00003566 NeedsEnvironmentIntrinsic(intrinsic),
Nicolas Geoffray76d4bb0f32018-09-21 12:58:45 +01003567 GetSideEffectsIntrinsic(intrinsic),
3568 GetExceptionsIntrinsic(intrinsic));
3569 }
3570 resolved_method_ = method;
3571}
3572
Evgeny Astigeevichaf92a0f2020-06-26 13:28:33 +01003573bool IsGEZero(HInstruction* instruction) {
3574 DCHECK(instruction != nullptr);
3575 if (instruction->IsArrayLength()) {
3576 return true;
3577 } else if (instruction->IsMin()) {
3578 // Instruction MIN(>=0, >=0) is >= 0.
3579 return IsGEZero(instruction->InputAt(0)) &&
3580 IsGEZero(instruction->InputAt(1));
3581 } else if (instruction->IsAbs()) {
3582 // Instruction ABS(>=0) is >= 0.
3583 // NOTE: ABS(minint) = minint prevents assuming
3584 // >= 0 without looking at the argument.
3585 return IsGEZero(instruction->InputAt(0));
3586 }
3587 int64_t value = -1;
3588 return IsInt64AndGet(instruction, &value) && value >= 0;
3589}
3590
Nicolas Geoffray818f2102014-02-18 16:43:35 +00003591} // namespace art