blob: 91e475d737c8b5314615f533fcc9af388acffdc0 [file] [log] [blame]
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Nicolas Geoffray818f2102014-02-18 16:43:35 +000016#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000017
Roland Levillain31dd3d62016-02-16 12:21:02 +000018#include <cfloat>
19
Andreas Gampec6ea7d02017-02-01 16:46:28 -080020#include "art_method-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "base/bit_utils.h"
22#include "base/bit_vector-inl.h"
23#include "base/stl_util.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080024#include "class_linker-inl.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040025#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000026#include "common_dominator.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010027#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010028#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070029#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070030#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000031
32namespace art {
33
Roland Levillain31dd3d62016-02-16 12:21:02 +000034// Enable floating-point static evaluation during constant folding
35// only if all floating-point operations and constants evaluate in the
36// range and precision of the type used (i.e., 32-bit float, 64-bit
37// double).
38static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
39
Mathieu Chartiere8a3c572016-10-11 16:52:17 -070040void HGraph::InitializeInexactObjectRTI(VariableSizedHandleScope* handles) {
David Brazdilbadd8262016-02-02 16:28:56 +000041 ScopedObjectAccess soa(Thread::Current());
42 // Create the inexact Object reference type and store it in the HGraph.
43 ClassLinker* linker = Runtime::Current()->GetClassLinker();
44 inexact_object_rti_ = ReferenceTypeInfo::Create(
45 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
46 /* is_exact */ false);
47}
48
Nicolas Geoffray818f2102014-02-18 16:43:35 +000049void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010050 block->SetBlockId(blocks_.size());
51 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000052}
53
Nicolas Geoffray804d0932014-05-02 08:46:00 +010054void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010055 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
56 DCHECK_EQ(visited->GetHighestBitSet(), -1);
57
Vladimir Marko69d310e2017-10-09 14:12:23 +010058 // Allocate memory from local ScopedArenaAllocator.
59 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Marko1f8695c2015-09-24 13:11:31 +010060 // Nodes that we're currently visiting, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +010061 ArenaBitVector visiting(
62 &allocator, blocks_.size(), /* expandable */ false, kArenaAllocGraphBuilder);
63 visiting.ClearAllBits();
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +010065 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
66 0u,
67 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010068 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko69d310e2017-10-09 14:12:23 +010069 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010070 constexpr size_t kDefaultWorklistSize = 8;
71 worklist.reserve(kDefaultWorklistSize);
72 visited->SetBit(entry_block_->GetBlockId());
73 visiting.SetBit(entry_block_->GetBlockId());
74 worklist.push_back(entry_block_);
75
76 while (!worklist.empty()) {
77 HBasicBlock* current = worklist.back();
78 uint32_t current_id = current->GetBlockId();
79 if (successors_visited[current_id] == current->GetSuccessors().size()) {
80 visiting.ClearBit(current_id);
81 worklist.pop_back();
82 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010083 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
84 uint32_t successor_id = successor->GetBlockId();
85 if (visiting.IsBitSet(successor_id)) {
86 DCHECK(ContainsElement(worklist, successor));
87 successor->AddBackEdge(current);
88 } else if (!visited->IsBitSet(successor_id)) {
89 visited->SetBit(successor_id);
90 visiting.SetBit(successor_id);
91 worklist.push_back(successor);
92 }
93 }
94 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000095}
96
Artem Serov21c7e6f2017-07-27 16:04:42 +010097// Remove the environment use records of the instruction for users.
98void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010099 for (HEnvironment* environment = instruction->GetEnvironment();
100 environment != nullptr;
101 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000102 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +0000103 if (environment->GetInstructionAt(i) != nullptr) {
104 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000105 }
106 }
107 }
108}
109
Artem Serov21c7e6f2017-07-27 16:04:42 +0100110// Return whether the instruction has an environment and it's used by others.
111bool HasEnvironmentUsedByOthers(HInstruction* instruction) {
112 for (HEnvironment* environment = instruction->GetEnvironment();
113 environment != nullptr;
114 environment = environment->GetParent()) {
115 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
116 HInstruction* user = environment->GetInstructionAt(i);
117 if (user != nullptr) {
118 return true;
119 }
120 }
121 }
122 return false;
123}
124
125// Reset environment records of the instruction itself.
126void ResetEnvironmentInputRecords(HInstruction* instruction) {
127 for (HEnvironment* environment = instruction->GetEnvironment();
128 environment != nullptr;
129 environment = environment->GetParent()) {
130 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
131 DCHECK(environment->GetHolder() == instruction);
132 if (environment->GetInstructionAt(i) != nullptr) {
133 environment->SetRawEnvAt(i, nullptr);
134 }
135 }
136 }
137}
138
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000139static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100140 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000141 RemoveEnvironmentUses(instruction);
142}
143
Roland Levillainfc600dc2014-12-02 17:16:31 +0000144void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100145 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000146 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100147 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000148 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100149 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000150 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
151 RemoveAsUser(it.Current());
152 }
153 }
154 }
155}
156
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100157void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100158 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000159 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100160 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000161 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100162 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000163 for (HBasicBlock* successor : block->GetSuccessors()) {
164 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000165 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100166 // Remove the block from the list of blocks, so that further analyses
167 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100168 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600169 if (block->IsExitBlock()) {
170 SetExitBlock(nullptr);
171 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000172 // Mark the block as removed. This is used by the HGraphBuilder to discard
173 // the block as a branch target.
174 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000175 }
176 }
177}
178
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000179GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Marko69d310e2017-10-09 14:12:23 +0100180 // Allocate memory from local ScopedArenaAllocator.
181 ScopedArenaAllocator allocator(GetArenaStack());
182
183 ArenaBitVector visited(&allocator, blocks_.size(), false, kArenaAllocGraphBuilder);
184 visited.ClearAllBits();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000185
David Brazdil86ea7ee2016-02-16 09:26:07 +0000186 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000187 FindBackEdges(&visited);
188
David Brazdil86ea7ee2016-02-16 09:26:07 +0000189 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000190 // the initial DFS as users from other instructions, so that
191 // users can be safely removed before uses later.
192 RemoveInstructionsAsUsersFromDeadBlocks(visited);
193
David Brazdil86ea7ee2016-02-16 09:26:07 +0000194 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000195 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000196 // predecessors list of live blocks.
197 RemoveDeadBlocks(visited);
198
David Brazdil86ea7ee2016-02-16 09:26:07 +0000199 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100200 // dominators and the reverse post order.
201 SimplifyCFG();
202
David Brazdil86ea7ee2016-02-16 09:26:07 +0000203 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100204 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000205
David Brazdil86ea7ee2016-02-16 09:26:07 +0000206 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000207 // set the loop information on each block.
208 GraphAnalysisResult result = AnalyzeLoops();
209 if (result != kAnalysisSuccess) {
210 return result;
211 }
212
David Brazdil86ea7ee2016-02-16 09:26:07 +0000213 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000214 // which needs the information to build catch block phis from values of
215 // locals at throwing instructions inside try blocks.
216 ComputeTryBlockInformation();
217
218 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100219}
220
221void HGraph::ClearDominanceInformation() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100222 for (HBasicBlock* block : GetReversePostOrder()) {
223 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100224 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100225 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100226}
227
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000228void HGraph::ClearLoopInformation() {
229 SetHasIrreducibleLoops(false);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100230 for (HBasicBlock* block : GetReversePostOrder()) {
231 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000232 }
233}
234
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100235void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000236 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100237 dominator_ = nullptr;
238}
239
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000240HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
241 HInstruction* instruction = GetFirstInstruction();
242 while (instruction->IsParallelMove()) {
243 instruction = instruction->GetNext();
244 }
245 return instruction;
246}
247
David Brazdil3f4a5222016-05-06 12:46:21 +0100248static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
249 DCHECK(ContainsElement(block->GetSuccessors(), successor));
250
251 HBasicBlock* old_dominator = successor->GetDominator();
252 HBasicBlock* new_dominator =
253 (old_dominator == nullptr) ? block
254 : CommonDominator::ForPair(old_dominator, block);
255
256 if (old_dominator == new_dominator) {
257 return false;
258 } else {
259 successor->SetDominator(new_dominator);
260 return true;
261 }
262}
263
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100264void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100265 DCHECK(reverse_post_order_.empty());
266 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100267 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100268
Vladimir Marko69d310e2017-10-09 14:12:23 +0100269 // Allocate memory from local ScopedArenaAllocator.
270 ScopedArenaAllocator allocator(GetArenaStack());
Vladimir Markod76d1392015-09-23 16:07:14 +0100271 // Number of visits of a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100272 ScopedArenaVector<size_t> visits(blocks_.size(), 0u, allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100273 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100274 ScopedArenaVector<size_t> successors_visited(blocks_.size(),
275 0u,
276 allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100277 // Nodes for which we need to visit successors.
Vladimir Marko69d310e2017-10-09 14:12:23 +0100278 ScopedArenaVector<HBasicBlock*> worklist(allocator.Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100279 constexpr size_t kDefaultWorklistSize = 8;
280 worklist.reserve(kDefaultWorklistSize);
281 worklist.push_back(entry_block_);
282
283 while (!worklist.empty()) {
284 HBasicBlock* current = worklist.back();
285 uint32_t current_id = current->GetBlockId();
286 if (successors_visited[current_id] == current->GetSuccessors().size()) {
287 worklist.pop_back();
288 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100289 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100290 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100291
292 // Once all the forward edges have been visited, we know the immediate
293 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100294 if (++visits[successor->GetBlockId()] ==
295 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100296 reverse_post_order_.push_back(successor);
297 worklist.push_back(successor);
298 }
299 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000300 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000301
David Brazdil3f4a5222016-05-06 12:46:21 +0100302 // Check if the graph has back edges not dominated by their respective headers.
303 // If so, we need to update the dominators of those headers and recursively of
304 // their successors. We do that with a fix-point iteration over all blocks.
305 // The algorithm is guaranteed to terminate because it loops only if the sum
306 // of all dominator chains has decreased in the current iteration.
307 bool must_run_fix_point = false;
308 for (HBasicBlock* block : blocks_) {
309 if (block != nullptr &&
310 block->IsLoopHeader() &&
311 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
312 must_run_fix_point = true;
313 break;
314 }
315 }
316 if (must_run_fix_point) {
317 bool update_occurred = true;
318 while (update_occurred) {
319 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100320 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100321 for (HBasicBlock* successor : block->GetSuccessors()) {
322 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
323 }
324 }
325 }
326 }
327
328 // Make sure that there are no remaining blocks whose dominator information
329 // needs to be updated.
330 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100331 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100332 for (HBasicBlock* successor : block->GetSuccessors()) {
333 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
334 }
335 }
336 }
337
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000338 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000339 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100340 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000341 if (!block->IsEntryBlock()) {
342 block->GetDominator()->AddDominatedBlock(block);
343 }
344 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000345}
346
David Brazdilfc6a86a2015-06-26 10:33:45 +0000347HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100348 HBasicBlock* new_block = new (allocator_) HBasicBlock(this, successor->GetDexPc());
David Brazdil3e187382015-06-26 09:59:52 +0000349 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000350 // Use `InsertBetween` to ensure the predecessor index and successor index of
351 // `block` and `successor` are preserved.
352 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000353 return new_block;
354}
355
356void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
357 // Insert a new node between `block` and `successor` to split the
358 // critical edge.
359 HBasicBlock* new_block = SplitEdge(block, successor);
Vladimir Markoca6fff82017-10-03 14:49:14 +0100360 new_block->AddInstruction(new (allocator_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100361 if (successor->IsLoopHeader()) {
362 // If we split at a back edge boundary, make the new block the back edge.
363 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000364 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100365 info->RemoveBackEdge(block);
366 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100367 }
368 }
369}
370
Artem Serovc73ee372017-07-31 15:08:40 +0100371// Reorder phi inputs to match reordering of the block's predecessors.
372static void FixPhisAfterPredecessorsReodering(HBasicBlock* block, size_t first, size_t second) {
373 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
374 HPhi* phi = it.Current()->AsPhi();
375 HInstruction* first_instr = phi->InputAt(first);
376 HInstruction* second_instr = phi->InputAt(second);
377 phi->ReplaceInput(first_instr, second);
378 phi->ReplaceInput(second_instr, first);
379 }
380}
381
382// Make sure that the first predecessor of a loop header is the incoming block.
383void HGraph::OrderLoopHeaderPredecessors(HBasicBlock* header) {
384 DCHECK(header->IsLoopHeader());
385 HLoopInformation* info = header->GetLoopInformation();
386 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
387 HBasicBlock* to_swap = header->GetPredecessors()[0];
388 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
389 HBasicBlock* predecessor = header->GetPredecessors()[pred];
390 if (!info->IsBackEdge(*predecessor)) {
391 header->predecessors_[pred] = to_swap;
392 header->predecessors_[0] = predecessor;
393 FixPhisAfterPredecessorsReodering(header, 0, pred);
394 break;
395 }
396 }
397 }
398}
399
Artem Serov09faaea2017-12-07 14:36:01 +0000400// Transform control flow of the loop to a single preheader format (don't touch the data flow).
401// New_preheader can be already among the header predecessors - this situation will be correctly
402// processed.
403static void FixControlForNewSinglePreheader(HBasicBlock* header, HBasicBlock* new_preheader) {
404 HLoopInformation* loop_info = header->GetLoopInformation();
405 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
406 HBasicBlock* predecessor = header->GetPredecessors()[pred];
407 if (!loop_info->IsBackEdge(*predecessor) && predecessor != new_preheader) {
408 predecessor->ReplaceSuccessor(header, new_preheader);
409 pred--;
410 }
411 }
412}
413
414// == Before == == After ==
415// _________ _________ _________ _________
416// | B0 | | B1 | (old preheaders) | B0 | | B1 |
417// |=========| |=========| |=========| |=========|
418// | i0 = .. | | i1 = .. | | i0 = .. | | i1 = .. |
419// |_________| |_________| |_________| |_________|
420// \ / \ /
421// \ / ___v____________v___
422// \ / (new preheader) | B20 <- B0, B1 |
423// | | |====================|
424// | | | i20 = phi(i0, i1) |
425// | | |____________________|
426// | | |
427// /\ | | /\ /\ | /\
428// / v_______v_________v_______v \ / v___________v_____________v \
429// | | B10 <- B0, B1, B2, B3 | | | | B10 <- B20, B2, B3 | |
430// | |===========================| | (header) | |===========================| |
431// | | i10 = phi(i0, i1, i2, i3) | | | | i10 = phi(i20, i2, i3) | |
432// | |___________________________| | | |___________________________| |
433// | / \ | | / \ |
434// | ... ... | | ... ... |
435// | _________ _________ | | _________ _________ |
436// | | B2 | | B3 | | | | B2 | | B3 | |
437// | |=========| |=========| | (back edges) | |=========| |=========| |
438// | | i2 = .. | | i3 = .. | | | | i2 = .. | | i3 = .. | |
439// | |_________| |_________| | | |_________| |_________| |
440// \ / \ / \ / \ /
441// \___/ \___/ \___/ \___/
442//
443void HGraph::TransformLoopToSinglePreheaderFormat(HBasicBlock* header) {
444 HLoopInformation* loop_info = header->GetLoopInformation();
445
446 HBasicBlock* preheader = new (allocator_) HBasicBlock(this, header->GetDexPc());
447 AddBlock(preheader);
448 preheader->AddInstruction(new (allocator_) HGoto(header->GetDexPc()));
449
450 // If the old header has no Phis then we only need to fix the control flow.
451 if (header->GetPhis().IsEmpty()) {
452 FixControlForNewSinglePreheader(header, preheader);
453 preheader->AddSuccessor(header);
454 return;
455 }
456
457 // Find the first non-back edge block in the header's predecessors list.
458 size_t first_nonbackedge_pred_pos = 0;
459 bool found = false;
460 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
461 HBasicBlock* predecessor = header->GetPredecessors()[pred];
462 if (!loop_info->IsBackEdge(*predecessor)) {
463 first_nonbackedge_pred_pos = pred;
464 found = true;
465 break;
466 }
467 }
468
469 DCHECK(found);
470
471 // Fix the data-flow.
472 for (HInstructionIterator it(header->GetPhis()); !it.Done(); it.Advance()) {
473 HPhi* header_phi = it.Current()->AsPhi();
474
475 HPhi* preheader_phi = new (GetAllocator()) HPhi(GetAllocator(),
476 header_phi->GetRegNumber(),
477 0,
478 header_phi->GetType());
479 if (header_phi->GetType() == DataType::Type::kReference) {
480 preheader_phi->SetReferenceTypeInfo(header_phi->GetReferenceTypeInfo());
481 }
482 preheader->AddPhi(preheader_phi);
483
484 HInstruction* orig_input = header_phi->InputAt(first_nonbackedge_pred_pos);
485 header_phi->ReplaceInput(preheader_phi, first_nonbackedge_pred_pos);
486 preheader_phi->AddInput(orig_input);
487
488 for (size_t input_pos = first_nonbackedge_pred_pos + 1;
489 input_pos < header_phi->InputCount();
490 input_pos++) {
491 HInstruction* input = header_phi->InputAt(input_pos);
492 HBasicBlock* pred_block = header->GetPredecessors()[input_pos];
493
494 if (loop_info->Contains(*pred_block)) {
495 DCHECK(loop_info->IsBackEdge(*pred_block));
496 } else {
497 preheader_phi->AddInput(input);
498 header_phi->RemoveInputAt(input_pos);
499 input_pos--;
500 }
501 }
502 }
503
504 // Fix the control-flow.
505 HBasicBlock* first_pred = header->GetPredecessors()[first_nonbackedge_pred_pos];
506 preheader->InsertBetween(first_pred, header);
507
508 FixControlForNewSinglePreheader(header, preheader);
509}
510
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100511void HGraph::SimplifyLoop(HBasicBlock* header) {
512 HLoopInformation* info = header->GetLoopInformation();
513
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100514 // Make sure the loop has only one pre header. This simplifies SSA building by having
515 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000516 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
517 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000518 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000519 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Artem Serov09faaea2017-12-07 14:36:01 +0000520 TransformLoopToSinglePreheaderFormat(header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100521 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100522
Artem Serovc73ee372017-07-31 15:08:40 +0100523 OrderLoopHeaderPredecessors(header);
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100524
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100525 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000526 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
527 // Called from DeadBlockElimination. Update SuspendCheck pointer.
528 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100529 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100530}
531
David Brazdilffee3d32015-07-06 11:48:53 +0100532void HGraph::ComputeTryBlockInformation() {
533 // Iterate in reverse post order to propagate try membership information from
534 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100535 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100536 if (block->IsEntryBlock() || block->IsCatchBlock()) {
537 // Catch blocks after simplification have only exceptional predecessors
538 // and hence are never in tries.
539 continue;
540 }
541
542 // Infer try membership from the first predecessor. Having simplified loops,
543 // the first predecessor can never be a back edge and therefore it must have
544 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100545 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100546 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100547 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000548 if (try_entry != nullptr &&
549 (block->GetTryCatchInformation() == nullptr ||
550 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
551 // We are either setting try block membership for the first time or it
552 // has changed.
Vladimir Markoca6fff82017-10-03 14:49:14 +0100553 block->SetTryCatchInformation(new (allocator_) TryCatchInformation(*try_entry));
David Brazdilec16f792015-08-19 15:04:01 +0100554 }
David Brazdilffee3d32015-07-06 11:48:53 +0100555 }
556}
557
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100558void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000559// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100560 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000561 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100562 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
563 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
564 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
565 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100566 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000567 if (block->GetSuccessors().size() > 1) {
568 // Only split normal-flow edges. We cannot split exceptional edges as they
569 // are synthesized (approximate real control flow), and we do not need to
570 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000571 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
572 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
573 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100574 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000575 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000576 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
577 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000578 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000579 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100580 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000581 // SplitCriticalEdge could have invalidated the `normal_successors`
582 // ArrayRef. We must re-acquire it.
583 normal_successors = block->GetNormalSuccessors();
584 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
585 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100586 }
587 }
588 }
589 if (block->IsLoopHeader()) {
590 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000591 } else if (!block->IsEntryBlock() &&
592 block->GetFirstInstruction() != nullptr &&
593 block->GetFirstInstruction()->IsSuspendCheck()) {
594 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000595 // a loop got dismantled. Just remove the suspend check.
596 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100597 }
598 }
599}
600
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000601GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100602 // We iterate post order to ensure we visit inner loops before outer loops.
603 // `PopulateRecursive` needs this guarantee to know whether a natural loop
604 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100605 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100606 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100607 if (block->IsCatchBlock()) {
608 // TODO: Dealing with exceptional back edges could be tricky because
609 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffraydbb9aef2017-11-23 10:44:11 +0000610 VLOG(compiler) << "Not compiled: Exceptional back edges";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000611 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100612 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000613 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100614 }
615 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000616 return kAnalysisSuccess;
617}
618
619void HLoopInformation::Dump(std::ostream& os) {
620 os << "header: " << header_->GetBlockId() << std::endl;
621 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
622 for (HBasicBlock* block : back_edges_) {
623 os << "back edge: " << block->GetBlockId() << std::endl;
624 }
625 for (HBasicBlock* block : header_->GetPredecessors()) {
626 os << "predecessor: " << block->GetBlockId() << std::endl;
627 }
628 for (uint32_t idx : blocks_.Indexes()) {
629 os << " in loop: " << idx << std::endl;
630 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100631}
632
David Brazdil8d5b8b22015-03-24 10:51:52 +0000633void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000634 // New constants are inserted before the SuspendCheck at the bottom of the
635 // entry block. Note that this method can be called from the graph builder and
636 // the entry block therefore may not end with SuspendCheck->Goto yet.
637 HInstruction* insert_before = nullptr;
638
639 HInstruction* gota = entry_block_->GetLastInstruction();
640 if (gota != nullptr && gota->IsGoto()) {
641 HInstruction* suspend_check = gota->GetPrevious();
642 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
643 insert_before = suspend_check;
644 } else {
645 insert_before = gota;
646 }
647 }
648
649 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000650 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000651 } else {
652 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000653 }
654}
655
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600656HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100657 // For simplicity, don't bother reviving the cached null constant if it is
658 // not null and not in a block. Otherwise, we need to clear the instruction
659 // id and/or any invariants the graph is assuming when adding new instructions.
660 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100661 cached_null_constant_ = new (allocator_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000662 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000663 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000664 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000665 if (kIsDebugBuild) {
666 ScopedObjectAccess soa(Thread::Current());
667 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
668 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000669 return cached_null_constant_;
670}
671
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100672HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100673 // For simplicity, don't bother reviving the cached current method if it is
674 // not null and not in a block. Otherwise, we need to clear the instruction
675 // id and/or any invariants the graph is assuming when adding new instructions.
676 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100677 cached_current_method_ = new (allocator_) HCurrentMethod(
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100678 Is64BitInstructionSet(instruction_set_) ? DataType::Type::kInt64 : DataType::Type::kInt32,
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600679 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100680 if (entry_block_->GetFirstInstruction() == nullptr) {
681 entry_block_->AddInstruction(cached_current_method_);
682 } else {
683 entry_block_->InsertInstructionBefore(
684 cached_current_method_, entry_block_->GetFirstInstruction());
685 }
686 }
687 return cached_current_method_;
688}
689
Igor Murashkind01745e2017-04-05 16:40:31 -0700690const char* HGraph::GetMethodName() const {
691 const DexFile::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
692 return dex_file_.GetMethodName(method_id);
693}
694
695std::string HGraph::PrettyMethod(bool with_signature) const {
696 return dex_file_.PrettyMethod(method_idx_, with_signature);
697}
698
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100699HConstant* HGraph::GetConstant(DataType::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000700 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100701 case DataType::Type::kBool:
David Brazdil8d5b8b22015-03-24 10:51:52 +0000702 DCHECK(IsUint<1>(value));
703 FALLTHROUGH_INTENDED;
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100704 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100705 case DataType::Type::kInt8:
706 case DataType::Type::kUint16:
707 case DataType::Type::kInt16:
708 case DataType::Type::kInt32:
709 DCHECK(IsInt(DataType::Size(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600710 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000711
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100712 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600713 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000714
715 default:
716 LOG(FATAL) << "Unsupported constant type";
717 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000718 }
David Brazdil46e2a392015-03-16 17:31:52 +0000719}
720
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000721void HGraph::CacheFloatConstant(HFloatConstant* constant) {
722 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
723 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
724 cached_float_constants_.Overwrite(value, constant);
725}
726
727void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
728 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
729 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
730 cached_double_constants_.Overwrite(value, constant);
731}
732
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000733void HLoopInformation::Add(HBasicBlock* block) {
734 blocks_.SetBit(block->GetBlockId());
735}
736
David Brazdil46e2a392015-03-16 17:31:52 +0000737void HLoopInformation::Remove(HBasicBlock* block) {
738 blocks_.ClearBit(block->GetBlockId());
739}
740
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100741void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
742 if (blocks_.IsBitSet(block->GetBlockId())) {
743 return;
744 }
745
746 blocks_.SetBit(block->GetBlockId());
747 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100748 if (block->IsLoopHeader()) {
749 // We're visiting loops in post-order, so inner loops must have been
750 // populated already.
751 DCHECK(block->GetLoopInformation()->IsPopulated());
752 if (block->GetLoopInformation()->IsIrreducible()) {
753 contains_irreducible_loop_ = true;
754 }
755 }
Vladimir Marko60584552015-09-03 13:35:12 +0000756 for (HBasicBlock* predecessor : block->GetPredecessors()) {
757 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100758 }
759}
760
David Brazdilc2e8af92016-04-05 17:15:19 +0100761void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
762 size_t block_id = block->GetBlockId();
763
764 // If `block` is in `finalized`, we know its membership in the loop has been
765 // decided and it does not need to be revisited.
766 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000767 return;
768 }
769
David Brazdilc2e8af92016-04-05 17:15:19 +0100770 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000771 if (block->IsLoopHeader()) {
772 // If we hit a loop header in an irreducible loop, we first check if the
773 // pre header of that loop belongs to the currently analyzed loop. If it does,
774 // then we visit the back edges.
775 // Note that we cannot use GetPreHeader, as the loop may have not been populated
776 // yet.
777 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100778 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000779 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000780 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100781 blocks_.SetBit(block_id);
782 finalized->SetBit(block_id);
783 is_finalized = true;
784
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000785 HLoopInformation* info = block->GetLoopInformation();
786 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100787 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000788 }
789 }
790 } else {
791 // Visit all predecessors. If one predecessor is part of the loop, this
792 // block is also part of this loop.
793 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100794 PopulateIrreducibleRecursive(predecessor, finalized);
795 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000796 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100797 blocks_.SetBit(block_id);
798 finalized->SetBit(block_id);
799 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000800 }
801 }
802 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100803
804 // All predecessors have been recursively visited. Mark finalized if not marked yet.
805 if (!is_finalized) {
806 finalized->SetBit(block_id);
807 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000808}
809
810void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100811 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000812 // Populate this loop: starting with the back edge, recursively add predecessors
813 // that are not already part of that loop. Set the header as part of the loop
814 // to end the recursion.
815 // This is a recursive implementation of the algorithm described in
816 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100817 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000818 blocks_.SetBit(header_->GetBlockId());
819 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100820
David Brazdil3f4a5222016-05-06 12:46:21 +0100821 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100822
823 if (is_irreducible_loop) {
Vladimir Marko69d310e2017-10-09 14:12:23 +0100824 // Allocate memory from local ScopedArenaAllocator.
825 ScopedArenaAllocator allocator(graph->GetArenaStack());
826 ArenaBitVector visited(&allocator,
David Brazdilc2e8af92016-04-05 17:15:19 +0100827 graph->GetBlocks().size(),
828 /* expandable */ false,
829 kArenaAllocGraphBuilder);
Vladimir Marko69d310e2017-10-09 14:12:23 +0100830 visited.ClearAllBits();
David Brazdil5a620592016-05-05 11:27:03 +0100831 // Stop marking blocks at the loop header.
832 visited.SetBit(header_->GetBlockId());
833
David Brazdilc2e8af92016-04-05 17:15:19 +0100834 for (HBasicBlock* back_edge : GetBackEdges()) {
835 PopulateIrreducibleRecursive(back_edge, &visited);
836 }
837 } else {
838 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000839 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100840 }
David Brazdila4b8c212015-05-07 09:59:30 +0100841 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100842
Vladimir Markofd66c502016-04-18 15:37:01 +0100843 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
844 // When compiling in OSR mode, all loops in the compiled method may be entered
845 // from the interpreter. We treat this OSR entry point just like an extra entry
846 // to an irreducible loop, so we need to mark the method's loops as irreducible.
847 // This does not apply to inlined loops which do not act as OSR entry points.
848 if (suspend_check_ == nullptr) {
849 // Just building the graph in OSR mode, this loop is not inlined. We never build an
850 // inner graph in OSR mode as we can do OSR transition only from the outer method.
851 is_irreducible_loop = true;
852 } else {
853 // Look at the suspend check's environment to determine if the loop was inlined.
854 DCHECK(suspend_check_->HasEnvironment());
855 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
856 is_irreducible_loop = true;
857 }
858 }
859 }
860 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100861 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100862 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100863 graph->SetHasIrreducibleLoops(true);
864 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800865 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +0100866}
867
Artem Serov7f4aff62017-06-21 17:02:18 +0100868void HLoopInformation::PopulateInnerLoopUpwards(HLoopInformation* inner_loop) {
869 DCHECK(inner_loop->GetPreHeader()->GetLoopInformation() == this);
870 blocks_.Union(&inner_loop->blocks_);
871 HLoopInformation* outer_loop = GetPreHeader()->GetLoopInformation();
872 if (outer_loop != nullptr) {
873 outer_loop->PopulateInnerLoopUpwards(this);
874 }
875}
876
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100877HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000878 HBasicBlock* block = header_->GetPredecessors()[0];
879 DCHECK(irreducible_ || (block == header_->GetDominator()));
880 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100881}
882
883bool HLoopInformation::Contains(const HBasicBlock& block) const {
884 return blocks_.IsBitSet(block.GetBlockId());
885}
886
887bool HLoopInformation::IsIn(const HLoopInformation& other) const {
888 return other.blocks_.IsBitSet(header_->GetBlockId());
889}
890
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800891bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
892 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700893}
894
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100895size_t HLoopInformation::GetLifetimeEnd() const {
896 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100897 for (HBasicBlock* back_edge : GetBackEdges()) {
898 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100899 }
900 return last_position;
901}
902
David Brazdil3f4a5222016-05-06 12:46:21 +0100903bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
904 for (HBasicBlock* back_edge : GetBackEdges()) {
905 DCHECK(back_edge->GetDominator() != nullptr);
906 if (!header_->Dominates(back_edge)) {
907 return true;
908 }
909 }
910 return false;
911}
912
Anton Shaminf89381f2016-05-16 16:44:13 +0600913bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
914 for (HBasicBlock* back_edge : GetBackEdges()) {
915 if (!block->Dominates(back_edge)) {
916 return false;
917 }
918 }
919 return true;
920}
921
David Sehrc757dec2016-11-04 15:48:34 -0700922
923bool HLoopInformation::HasExitEdge() const {
924 // Determine if this loop has at least one exit edge.
925 HBlocksInLoopReversePostOrderIterator it_loop(*this);
926 for (; !it_loop.Done(); it_loop.Advance()) {
927 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
928 if (!Contains(*successor)) {
929 return true;
930 }
931 }
932 }
933 return false;
934}
935
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100936bool HBasicBlock::Dominates(HBasicBlock* other) const {
937 // Walk up the dominator tree from `other`, to find out if `this`
938 // is an ancestor.
939 HBasicBlock* current = other;
940 while (current != nullptr) {
941 if (current == this) {
942 return true;
943 }
944 current = current->GetDominator();
945 }
946 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100947}
948
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100949static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100950 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100951 for (size_t i = 0; i < inputs.size(); ++i) {
952 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100953 }
954 // Environment should be created later.
955 DCHECK(!instruction->HasEnvironment());
956}
957
Artem Serovcced8ba2017-07-19 18:18:09 +0100958void HBasicBlock::ReplaceAndRemovePhiWith(HPhi* initial, HPhi* replacement) {
959 DCHECK(initial->GetBlock() == this);
960 InsertPhiAfter(replacement, initial);
961 initial->ReplaceWith(replacement);
962 RemovePhi(initial);
963}
964
Roland Levillainccc07a92014-09-16 14:48:16 +0100965void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
966 HInstruction* replacement) {
967 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400968 if (initial->IsControlFlow()) {
969 // We can only replace a control flow instruction with another control flow instruction.
970 DCHECK(replacement->IsControlFlow());
971 DCHECK_EQ(replacement->GetId(), -1);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100972 DCHECK_EQ(replacement->GetType(), DataType::Type::kVoid);
Mark Mendell805b3b52015-09-18 14:10:29 -0400973 DCHECK_EQ(initial->GetBlock(), this);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100974 DCHECK_EQ(initial->GetType(), DataType::Type::kVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100975 DCHECK(initial->GetUses().empty());
976 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400977 replacement->SetBlock(this);
978 replacement->SetId(GetGraph()->GetNextInstructionId());
979 instructions_.InsertInstructionBefore(replacement, initial);
980 UpdateInputsUsers(replacement);
981 } else {
982 InsertInstructionBefore(replacement, initial);
983 initial->ReplaceWith(replacement);
984 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100985 RemoveInstruction(initial);
986}
987
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100988static void Add(HInstructionList* instruction_list,
989 HBasicBlock* block,
990 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000991 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000992 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100993 instruction->SetBlock(block);
994 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100995 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100996 instruction_list->AddInstruction(instruction);
997}
998
999void HBasicBlock::AddInstruction(HInstruction* instruction) {
1000 Add(&instructions_, this, instruction);
1001}
1002
1003void HBasicBlock::AddPhi(HPhi* phi) {
1004 Add(&phis_, this, phi);
1005}
1006
David Brazdilc3d743f2015-04-22 13:40:50 +01001007void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1008 DCHECK(!cursor->IsPhi());
1009 DCHECK(!instruction->IsPhi());
1010 DCHECK_EQ(instruction->GetId(), -1);
1011 DCHECK_NE(cursor->GetId(), -1);
1012 DCHECK_EQ(cursor->GetBlock(), this);
1013 DCHECK(!instruction->IsControlFlow());
1014 instruction->SetBlock(this);
1015 instruction->SetId(GetGraph()->GetNextInstructionId());
1016 UpdateInputsUsers(instruction);
1017 instructions_.InsertInstructionBefore(instruction, cursor);
1018}
1019
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +01001020void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1021 DCHECK(!cursor->IsPhi());
1022 DCHECK(!instruction->IsPhi());
1023 DCHECK_EQ(instruction->GetId(), -1);
1024 DCHECK_NE(cursor->GetId(), -1);
1025 DCHECK_EQ(cursor->GetBlock(), this);
1026 DCHECK(!instruction->IsControlFlow());
1027 DCHECK(!cursor->IsControlFlow());
1028 instruction->SetBlock(this);
1029 instruction->SetId(GetGraph()->GetNextInstructionId());
1030 UpdateInputsUsers(instruction);
1031 instructions_.InsertInstructionAfter(instruction, cursor);
1032}
1033
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001034void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
1035 DCHECK_EQ(phi->GetId(), -1);
1036 DCHECK_NE(cursor->GetId(), -1);
1037 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001038 phi->SetBlock(this);
1039 phi->SetId(GetGraph()->GetNextInstructionId());
1040 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +01001041 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001042}
1043
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001044static void Remove(HInstructionList* instruction_list,
1045 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +00001046 HInstruction* instruction,
1047 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001048 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001049 instruction->SetBlock(nullptr);
1050 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +00001051 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001052 DCHECK(instruction->GetUses().empty());
1053 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +00001054 RemoveAsUser(instruction);
1055 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001056}
1057
David Brazdil1abb4192015-02-17 18:33:36 +00001058void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +01001059 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +00001060 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001061}
1062
David Brazdil1abb4192015-02-17 18:33:36 +00001063void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
1064 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001065}
1066
David Brazdilc7508e92015-04-27 13:28:57 +01001067void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
1068 if (instruction->IsPhi()) {
1069 RemovePhi(instruction->AsPhi(), ensure_safety);
1070 } else {
1071 RemoveInstruction(instruction, ensure_safety);
1072 }
1073}
1074
Vladimir Marko69d310e2017-10-09 14:12:23 +01001075void HEnvironment::CopyFrom(ArrayRef<HInstruction* const> locals) {
Vladimir Marko71bf8092015-09-15 15:33:14 +01001076 for (size_t i = 0; i < locals.size(); i++) {
1077 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +01001078 SetRawEnvAt(i, instruction);
1079 if (instruction != nullptr) {
1080 instruction->AddEnvUseAt(this, i);
1081 }
1082 }
1083}
1084
David Brazdiled596192015-01-23 10:39:45 +00001085void HEnvironment::CopyFrom(HEnvironment* env) {
1086 for (size_t i = 0; i < env->Size(); i++) {
1087 HInstruction* instruction = env->GetInstructionAt(i);
1088 SetRawEnvAt(i, instruction);
1089 if (instruction != nullptr) {
1090 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001091 }
David Brazdiled596192015-01-23 10:39:45 +00001092 }
1093}
1094
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001095void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
1096 HBasicBlock* loop_header) {
1097 DCHECK(loop_header->IsLoopHeader());
1098 for (size_t i = 0; i < env->Size(); i++) {
1099 HInstruction* instruction = env->GetInstructionAt(i);
1100 SetRawEnvAt(i, instruction);
1101 if (instruction == nullptr) {
1102 continue;
1103 }
1104 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
1105 // At the end of the loop pre-header, the corresponding value for instruction
1106 // is the first input of the phi.
1107 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001108 SetRawEnvAt(i, initial);
1109 initial->AddEnvUseAt(this, i);
1110 } else {
1111 instruction->AddEnvUseAt(this, i);
1112 }
1113 }
1114}
1115
David Brazdil1abb4192015-02-17 18:33:36 +00001116void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +01001117 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
1118 HInstruction* user = env_use.GetInstruction();
1119 auto before_env_use_node = env_use.GetBeforeUseNode();
1120 user->env_uses_.erase_after(before_env_use_node);
1121 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001122}
1123
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001124HInstruction::InstructionKind HInstruction::GetKind() const {
1125 return GetKindInternal();
1126}
1127
Calin Juravle77520bc2015-01-12 18:45:46 +00001128HInstruction* HInstruction::GetNextDisregardingMoves() const {
1129 HInstruction* next = GetNext();
1130 while (next != nullptr && next->IsParallelMove()) {
1131 next = next->GetNext();
1132 }
1133 return next;
1134}
1135
1136HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1137 HInstruction* previous = GetPrevious();
1138 while (previous != nullptr && previous->IsParallelMove()) {
1139 previous = previous->GetPrevious();
1140 }
1141 return previous;
1142}
1143
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001144void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001145 if (first_instruction_ == nullptr) {
1146 DCHECK(last_instruction_ == nullptr);
1147 first_instruction_ = last_instruction_ = instruction;
1148 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001149 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001150 last_instruction_->next_ = instruction;
1151 instruction->previous_ = last_instruction_;
1152 last_instruction_ = instruction;
1153 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001154}
1155
David Brazdilc3d743f2015-04-22 13:40:50 +01001156void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1157 DCHECK(Contains(cursor));
1158 if (cursor == first_instruction_) {
1159 cursor->previous_ = instruction;
1160 instruction->next_ = cursor;
1161 first_instruction_ = instruction;
1162 } else {
1163 instruction->previous_ = cursor->previous_;
1164 instruction->next_ = cursor;
1165 cursor->previous_ = instruction;
1166 instruction->previous_->next_ = instruction;
1167 }
1168}
1169
1170void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1171 DCHECK(Contains(cursor));
1172 if (cursor == last_instruction_) {
1173 cursor->next_ = instruction;
1174 instruction->previous_ = cursor;
1175 last_instruction_ = instruction;
1176 } else {
1177 instruction->next_ = cursor->next_;
1178 instruction->previous_ = cursor;
1179 cursor->next_ = instruction;
1180 instruction->next_->previous_ = instruction;
1181 }
1182}
1183
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001184void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1185 if (instruction->previous_ != nullptr) {
1186 instruction->previous_->next_ = instruction->next_;
1187 }
1188 if (instruction->next_ != nullptr) {
1189 instruction->next_->previous_ = instruction->previous_;
1190 }
1191 if (instruction == first_instruction_) {
1192 first_instruction_ = instruction->next_;
1193 }
1194 if (instruction == last_instruction_) {
1195 last_instruction_ = instruction->previous_;
1196 }
1197}
1198
Roland Levillain6b469232014-09-25 10:10:38 +01001199bool HInstructionList::Contains(HInstruction* instruction) const {
1200 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1201 if (it.Current() == instruction) {
1202 return true;
1203 }
1204 }
1205 return false;
1206}
1207
Roland Levillainccc07a92014-09-16 14:48:16 +01001208bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1209 const HInstruction* instruction2) const {
1210 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1211 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1212 if (it.Current() == instruction1) {
1213 return true;
1214 }
1215 if (it.Current() == instruction2) {
1216 return false;
1217 }
1218 }
1219 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1220 return true;
1221}
1222
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001223bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
Roland Levillain6c82d402014-10-13 16:10:27 +01001224 if (other_instruction == this) {
1225 // An instruction does not strictly dominate itself.
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001226 return false;
Roland Levillain6c82d402014-10-13 16:10:27 +01001227 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001228 HBasicBlock* block = GetBlock();
1229 HBasicBlock* other_block = other_instruction->GetBlock();
1230 if (block != other_block) {
1231 return GetBlock()->Dominates(other_instruction->GetBlock());
1232 } else {
1233 // If both instructions are in the same block, ensure this
1234 // instruction comes before `other_instruction`.
1235 if (IsPhi()) {
1236 if (!other_instruction->IsPhi()) {
1237 // Phis appear before non phi-instructions so this instruction
1238 // dominates `other_instruction`.
1239 return true;
1240 } else {
1241 // There is no order among phis.
1242 LOG(FATAL) << "There is no dominance between phis of a same block.";
1243 return false;
1244 }
1245 } else {
1246 // `this` is not a phi.
1247 if (other_instruction->IsPhi()) {
1248 // Phis appear before non phi-instructions so this instruction
1249 // does not dominate `other_instruction`.
1250 return false;
1251 } else {
1252 // Check whether this instruction comes before
1253 // `other_instruction` in the instruction list.
1254 return block->GetInstructions().FoundBefore(this, other_instruction);
1255 }
1256 }
1257 }
1258}
1259
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001260void HInstruction::RemoveEnvironment() {
1261 RemoveEnvironmentUses(this);
1262 environment_ = nullptr;
1263}
1264
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001265void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001266 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001267 // Note: fixup_end remains valid across splice_after().
1268 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1269 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1270 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001271
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001272 // Note: env_fixup_end remains valid across splice_after().
1273 auto env_fixup_end =
1274 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1275 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1276 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001277
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001278 DCHECK(uses_.empty());
1279 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001280}
1281
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001282void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001283 const HUseList<HInstruction*>& uses = GetUses();
1284 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1285 HInstruction* user = it->GetUser();
1286 size_t index = it->GetIndex();
1287 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1288 ++it;
Nicolas Geoffray04366f32017-12-14 15:15:19 +00001289 if (dominator->StrictlyDominates(user)) {
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001290 user->ReplaceInput(replacement, index);
1291 }
1292 }
1293}
1294
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001295void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001296 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001297 if (input_use.GetInstruction() == replacement) {
1298 // Nothing to do.
1299 return;
1300 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001301 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001302 // Note: fixup_end remains valid across splice_after().
1303 auto fixup_end =
1304 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1305 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1306 input_use.GetInstruction()->uses_,
1307 before_use_node);
1308 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1309 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001310}
1311
Nicolas Geoffray39468442014-09-02 15:17:15 +01001312size_t HInstruction::EnvironmentSize() const {
1313 return HasEnvironment() ? environment_->Size() : 0;
1314}
1315
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001316void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001317 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001318 inputs_.push_back(HUserRecord<HInstruction*>(input));
1319 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001320}
1321
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001322void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1323 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1324 input->AddUseAt(this, index);
1325 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1326 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1327 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1328 inputs_[i].GetUseNode()->SetIndex(i);
1329 }
1330}
1331
1332void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001333 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001334 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001335 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1336 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1337 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1338 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001339 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001340}
1341
Igor Murashkind01745e2017-04-05 16:40:31 -07001342void HVariableInputSizeInstruction::RemoveAllInputs() {
1343 RemoveAsUserOfAllInputs();
1344 DCHECK(!HasNonEnvironmentUses());
1345
1346 inputs_.clear();
1347 DCHECK_EQ(0u, InputCount());
1348}
1349
Igor Murashkin6ef45672017-08-08 13:59:55 -07001350size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001351 DCHECK(instruction->GetBlock() != nullptr);
1352 // Removing constructor fences only makes sense for instructions with an object return type.
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001353 DCHECK_EQ(DataType::Type::kReference, instruction->GetType());
Igor Murashkind01745e2017-04-05 16:40:31 -07001354
Igor Murashkin6ef45672017-08-08 13:59:55 -07001355 // Return how many instructions were removed for statistic purposes.
1356 size_t remove_count = 0;
1357
Igor Murashkind01745e2017-04-05 16:40:31 -07001358 // Efficient implementation that simultaneously (in one pass):
1359 // * Scans the uses list for all constructor fences.
1360 // * Deletes that constructor fence from the uses list of `instruction`.
1361 // * Deletes `instruction` from the constructor fence's inputs.
1362 // * Deletes the constructor fence if it now has 0 inputs.
1363
1364 const HUseList<HInstruction*>& uses = instruction->GetUses();
1365 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1366 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1367 const HUseListNode<HInstruction*>& use_node = *it;
1368 HInstruction* const use_instruction = use_node.GetUser();
1369
1370 // Advance the iterator immediately once we fetch the use_node.
1371 // Warning: If the input is removed, the current iterator becomes invalid.
1372 ++it;
1373
1374 if (use_instruction->IsConstructorFence()) {
1375 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1376 size_t input_index = use_node.GetIndex();
1377
1378 // Process the candidate instruction for removal
1379 // from the graph.
1380
1381 // Constructor fence instructions are never
1382 // used by other instructions.
1383 //
1384 // If we wanted to make this more generic, it
1385 // could be a runtime if statement.
1386 DCHECK(!ctor_fence->HasUses());
1387
1388 // A constructor fence's return type is "kPrimVoid"
1389 // and therefore it can't have any environment uses.
1390 DCHECK(!ctor_fence->HasEnvironmentUses());
1391
1392 // Remove the inputs first, otherwise removing the instruction
1393 // will try to remove its uses while we are already removing uses
1394 // and this operation will fail.
1395 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1396
1397 // Removing the input will also remove the `use_node`.
1398 // (Do not look at `use_node` after this, it will be a dangling reference).
1399 ctor_fence->RemoveInputAt(input_index);
1400
1401 // Once all inputs are removed, the fence is considered dead and
1402 // is removed.
1403 if (ctor_fence->InputCount() == 0u) {
1404 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
Igor Murashkin6ef45672017-08-08 13:59:55 -07001405 ++remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001406 }
1407 }
1408 }
1409
1410 if (kIsDebugBuild) {
1411 // Post-condition checks:
1412 // * None of the uses of `instruction` are a constructor fence.
1413 // * The `instruction` itself did not get removed from a block.
1414 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1415 CHECK(!use_node.GetUser()->IsConstructorFence());
1416 }
1417 CHECK(instruction->GetBlock() != nullptr);
1418 }
Igor Murashkin6ef45672017-08-08 13:59:55 -07001419
1420 return remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001421}
1422
Igor Murashkindd018df2017-08-09 10:38:31 -07001423void HConstructorFence::Merge(HConstructorFence* other) {
1424 // Do not delete yourself from the graph.
1425 DCHECK(this != other);
1426 // Don't try to merge with an instruction not associated with a block.
1427 DCHECK(other->GetBlock() != nullptr);
1428 // A constructor fence's return type is "kPrimVoid"
1429 // and therefore it cannot have any environment uses.
1430 DCHECK(!other->HasEnvironmentUses());
1431
1432 auto has_input = [](HInstruction* haystack, HInstruction* needle) {
1433 // Check if `haystack` has `needle` as any of its inputs.
1434 for (size_t input_count = 0; input_count < haystack->InputCount(); ++input_count) {
1435 if (haystack->InputAt(input_count) == needle) {
1436 return true;
1437 }
1438 }
1439 return false;
1440 };
1441
1442 // Add any inputs from `other` into `this` if it wasn't already an input.
1443 for (size_t input_count = 0; input_count < other->InputCount(); ++input_count) {
1444 HInstruction* other_input = other->InputAt(input_count);
1445 if (!has_input(this, other_input)) {
1446 AddInput(other_input);
1447 }
1448 }
1449
1450 other->GetBlock()->RemoveInstruction(other);
1451}
1452
1453HInstruction* HConstructorFence::GetAssociatedAllocation(bool ignore_inputs) {
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001454 HInstruction* new_instance_inst = GetPrevious();
1455 // Check if the immediately preceding instruction is a new-instance/new-array.
1456 // Otherwise this fence is for protecting final fields.
1457 if (new_instance_inst != nullptr &&
1458 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
Igor Murashkindd018df2017-08-09 10:38:31 -07001459 if (ignore_inputs) {
1460 // If inputs are ignored, simply check if the predecessor is
1461 // *any* HNewInstance/HNewArray.
1462 //
1463 // Inputs are normally only ignored for prepare_for_register_allocation,
1464 // at which point *any* prior HNewInstance/Array can be considered
1465 // associated.
1466 return new_instance_inst;
1467 } else {
1468 // Normal case: There must be exactly 1 input and the previous instruction
1469 // must be that input.
1470 if (InputCount() == 1u && InputAt(0) == new_instance_inst) {
1471 return new_instance_inst;
1472 }
1473 }
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001474 }
Igor Murashkindd018df2017-08-09 10:38:31 -07001475 return nullptr;
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001476}
1477
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001478#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001479void H##name::Accept(HGraphVisitor* visitor) { \
1480 visitor->Visit##name(this); \
1481}
1482
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001483FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001484
1485#undef DEFINE_ACCEPT
1486
1487void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001488 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1489 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001490 if (block != nullptr) {
1491 VisitBasicBlock(block);
1492 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001493 }
1494}
1495
Roland Levillain633021e2014-10-01 14:12:25 +01001496void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001497 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1498 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001499 }
1500}
1501
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001502void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001503 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001504 it.Current()->Accept(this);
1505 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001506 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001507 it.Current()->Accept(this);
1508 }
1509}
1510
Mark Mendelle82549b2015-05-06 10:55:34 -04001511HConstant* HTypeConversion::TryStaticEvaluation() const {
1512 HGraph* graph = GetBlock()->GetGraph();
1513 if (GetInput()->IsIntConstant()) {
1514 int32_t value = GetInput()->AsIntConstant()->GetValue();
1515 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001516 case DataType::Type::kInt8:
1517 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1518 case DataType::Type::kUint8:
1519 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1520 case DataType::Type::kInt16:
1521 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1522 case DataType::Type::kUint16:
1523 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001524 case DataType::Type::kInt64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001525 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001526 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001527 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001528 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001529 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001530 default:
1531 return nullptr;
1532 }
1533 } else if (GetInput()->IsLongConstant()) {
1534 int64_t value = GetInput()->AsLongConstant()->GetValue();
1535 switch (GetResultType()) {
Mingyao Yang75bb2f32017-11-30 14:45:44 -08001536 case DataType::Type::kInt8:
1537 return graph->GetIntConstant(static_cast<int8_t>(value), GetDexPc());
1538 case DataType::Type::kUint8:
1539 return graph->GetIntConstant(static_cast<uint8_t>(value), GetDexPc());
1540 case DataType::Type::kInt16:
1541 return graph->GetIntConstant(static_cast<int16_t>(value), GetDexPc());
1542 case DataType::Type::kUint16:
1543 return graph->GetIntConstant(static_cast<uint16_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001544 case DataType::Type::kInt32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001545 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001546 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001547 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001548 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001549 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001550 default:
1551 return nullptr;
1552 }
1553 } else if (GetInput()->IsFloatConstant()) {
1554 float value = GetInput()->AsFloatConstant()->GetValue();
1555 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001556 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001557 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001558 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001559 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001560 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001561 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001562 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1563 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001564 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001565 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001566 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001567 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001568 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001569 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001570 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1571 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001572 case DataType::Type::kFloat64:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001573 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001574 default:
1575 return nullptr;
1576 }
1577 } else if (GetInput()->IsDoubleConstant()) {
1578 double value = GetInput()->AsDoubleConstant()->GetValue();
1579 switch (GetResultType()) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001580 case DataType::Type::kInt32:
Mark Mendelle82549b2015-05-06 10:55:34 -04001581 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001582 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001583 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001584 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001585 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001586 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1587 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001588 case DataType::Type::kInt64:
Mark Mendelle82549b2015-05-06 10:55:34 -04001589 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001590 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001591 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001592 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001593 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001594 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1595 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001596 case DataType::Type::kFloat32:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001597 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001598 default:
1599 return nullptr;
1600 }
1601 }
1602 return nullptr;
1603}
1604
Roland Levillain9240d6a2014-10-20 16:47:04 +01001605HConstant* HUnaryOperation::TryStaticEvaluation() const {
1606 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001607 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001608 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001609 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001610 } else if (kEnableFloatingPointStaticEvaluation) {
1611 if (GetInput()->IsFloatConstant()) {
1612 return Evaluate(GetInput()->AsFloatConstant());
1613 } else if (GetInput()->IsDoubleConstant()) {
1614 return Evaluate(GetInput()->AsDoubleConstant());
1615 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001616 }
1617 return nullptr;
1618}
1619
1620HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001621 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1622 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001623 } else if (GetLeft()->IsLongConstant()) {
1624 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001625 // The binop(long, int) case is only valid for shifts and rotations.
1626 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001627 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1628 } else if (GetRight()->IsLongConstant()) {
1629 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001630 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001631 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001632 // The binop(null, null) case is only valid for equal and not-equal conditions.
1633 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001634 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001635 } else if (kEnableFloatingPointStaticEvaluation) {
1636 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1637 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1638 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1639 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1640 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001641 }
1642 return nullptr;
1643}
Dave Allison20dfc792014-06-16 20:44:29 -07001644
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001645HConstant* HBinaryOperation::GetConstantRight() const {
1646 if (GetRight()->IsConstant()) {
1647 return GetRight()->AsConstant();
1648 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1649 return GetLeft()->AsConstant();
1650 } else {
1651 return nullptr;
1652 }
1653}
1654
1655// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001656// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001657HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1658 HInstruction* most_constant_right = GetConstantRight();
1659 if (most_constant_right == nullptr) {
1660 return nullptr;
1661 } else if (most_constant_right == GetLeft()) {
1662 return GetRight();
1663 } else {
1664 return GetLeft();
1665 }
1666}
1667
Roland Levillain31dd3d62016-02-16 12:21:02 +00001668std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1669 switch (rhs) {
1670 case ComparisonBias::kNoBias:
1671 return os << "no_bias";
1672 case ComparisonBias::kGtBias:
1673 return os << "gt_bias";
1674 case ComparisonBias::kLtBias:
1675 return os << "lt_bias";
1676 default:
1677 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1678 UNREACHABLE();
1679 }
1680}
1681
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001682bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1683 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001684}
1685
Vladimir Marko372f10e2016-05-17 16:30:10 +01001686bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001687 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001688 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001689 if (!InstructionDataEquals(other)) return false;
1690 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001691 HConstInputsRef inputs = GetInputs();
1692 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001693 if (inputs.size() != other_inputs.size()) return false;
1694 for (size_t i = 0; i != inputs.size(); ++i) {
1695 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001696 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001697
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001698 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001699 return true;
1700}
1701
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001702std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1703#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1704 switch (rhs) {
1705 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1706 default:
1707 os << "Unknown instruction kind " << static_cast<int>(rhs);
1708 break;
1709 }
1710#undef DECLARE_CASE
1711 return os;
1712}
1713
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001714void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1715 if (do_checks) {
1716 DCHECK(!IsPhi());
1717 DCHECK(!IsControlFlow());
1718 DCHECK(CanBeMoved() ||
1719 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1720 IsShouldDeoptimizeFlag());
1721 DCHECK(!cursor->IsPhi());
1722 }
David Brazdild6c205e2016-06-07 14:20:52 +01001723
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001724 next_->previous_ = previous_;
1725 if (previous_ != nullptr) {
1726 previous_->next_ = next_;
1727 }
1728 if (block_->instructions_.first_instruction_ == this) {
1729 block_->instructions_.first_instruction_ = next_;
1730 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001731 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001732
1733 previous_ = cursor->previous_;
1734 if (previous_ != nullptr) {
1735 previous_->next_ = this;
1736 }
1737 next_ = cursor;
1738 cursor->previous_ = this;
1739 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001740
1741 if (block_->instructions_.first_instruction_ == cursor) {
1742 block_->instructions_.first_instruction_ = this;
1743 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001744}
1745
Vladimir Markofb337ea2015-11-25 15:25:10 +00001746void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1747 DCHECK(!CanThrow());
1748 DCHECK(!HasSideEffects());
1749 DCHECK(!HasEnvironmentUses());
1750 DCHECK(HasNonEnvironmentUses());
1751 DCHECK(!IsPhi()); // Makes no sense for Phi.
1752 DCHECK_EQ(InputCount(), 0u);
1753
1754 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001755 auto uses_it = GetUses().begin();
1756 auto uses_end = GetUses().end();
1757 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1758 ++uses_it;
1759 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1760 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001761 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001762 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001763 // This instruction has uses in two or more blocks. Find the common dominator.
1764 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001765 for (; uses_it != uses_end; ++uses_it) {
1766 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001767 }
1768 target_block = finder.Get();
1769 DCHECK(target_block != nullptr);
1770 }
1771 // Move to the first dominator not in a loop.
1772 while (target_block->IsInLoop()) {
1773 target_block = target_block->GetDominator();
1774 DCHECK(target_block != nullptr);
1775 }
1776
1777 // Find insertion position.
1778 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001779 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1780 if (use.GetUser()->GetBlock() == target_block &&
1781 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1782 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001783 }
1784 }
1785 if (insert_pos == nullptr) {
1786 // No user in `target_block`, insert before the control flow instruction.
1787 insert_pos = target_block->GetLastInstruction();
1788 DCHECK(insert_pos->IsControlFlow());
1789 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1790 if (insert_pos->IsIf()) {
1791 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1792 if (if_input == insert_pos->GetPrevious()) {
1793 insert_pos = if_input;
1794 }
1795 }
1796 }
1797 MoveBefore(insert_pos);
1798}
1799
David Brazdilfc6a86a2015-06-26 10:33:45 +00001800HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001801 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001802 DCHECK_EQ(cursor->GetBlock(), this);
1803
Vladimir Markoca6fff82017-10-03 14:49:14 +01001804 HBasicBlock* new_block =
1805 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001806 new_block->instructions_.first_instruction_ = cursor;
1807 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1808 instructions_.last_instruction_ = cursor->previous_;
1809 if (cursor->previous_ == nullptr) {
1810 instructions_.first_instruction_ = nullptr;
1811 } else {
1812 cursor->previous_->next_ = nullptr;
1813 cursor->previous_ = nullptr;
1814 }
1815
1816 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Markoca6fff82017-10-03 14:49:14 +01001817 AddInstruction(new (GetGraph()->GetAllocator()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001818
Vladimir Marko60584552015-09-03 13:35:12 +00001819 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001820 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001821 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001822 new_block->successors_.swap(successors_);
1823 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001824 AddSuccessor(new_block);
1825
David Brazdil56e1acc2015-06-30 15:41:36 +01001826 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001827 return new_block;
1828}
1829
David Brazdild7558da2015-09-22 13:04:14 +01001830HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001831 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001832 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1833
Vladimir Markoca6fff82017-10-03 14:49:14 +01001834 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
David Brazdild7558da2015-09-22 13:04:14 +01001835
1836 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001837 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1838 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001839 new_block->predecessors_.swap(predecessors_);
1840 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001841 AddPredecessor(new_block);
1842
1843 GetGraph()->AddBlock(new_block);
1844 return new_block;
1845}
1846
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001847HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1848 DCHECK_EQ(cursor->GetBlock(), this);
1849
Vladimir Markoca6fff82017-10-03 14:49:14 +01001850 HBasicBlock* new_block =
1851 new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), cursor->GetDexPc());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001852 new_block->instructions_.first_instruction_ = cursor;
1853 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1854 instructions_.last_instruction_ = cursor->previous_;
1855 if (cursor->previous_ == nullptr) {
1856 instructions_.first_instruction_ = nullptr;
1857 } else {
1858 cursor->previous_->next_ = nullptr;
1859 cursor->previous_ = nullptr;
1860 }
1861
1862 new_block->instructions_.SetBlockOfInstructions(new_block);
1863
1864 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001865 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1866 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001867 new_block->successors_.swap(successors_);
1868 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001869
1870 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1871 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001872 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001873 new_block->dominated_blocks_.swap(dominated_blocks_);
1874 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001875 return new_block;
1876}
1877
1878HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001879 DCHECK(!cursor->IsControlFlow());
1880 DCHECK_NE(instructions_.last_instruction_, cursor);
1881 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001882
Vladimir Markoca6fff82017-10-03 14:49:14 +01001883 HBasicBlock* new_block = new (GetGraph()->GetAllocator()) HBasicBlock(GetGraph(), GetDexPc());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001884 new_block->instructions_.first_instruction_ = cursor->GetNext();
1885 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1886 cursor->next_->previous_ = nullptr;
1887 cursor->next_ = nullptr;
1888 instructions_.last_instruction_ = cursor;
1889
1890 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001891 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001892 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001893 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001894 new_block->successors_.swap(successors_);
1895 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001896
Vladimir Marko60584552015-09-03 13:35:12 +00001897 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001898 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001899 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001900 new_block->dominated_blocks_.swap(dominated_blocks_);
1901 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001902 return new_block;
1903}
1904
David Brazdilec16f792015-08-19 15:04:01 +01001905const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001906 if (EndsWithTryBoundary()) {
1907 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1908 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001909 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001910 return try_boundary;
1911 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001912 DCHECK(IsTryBlock());
1913 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001914 return nullptr;
1915 }
David Brazdilec16f792015-08-19 15:04:01 +01001916 } else if (IsTryBlock()) {
1917 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001918 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001919 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001920 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001921}
1922
David Brazdild7558da2015-09-22 13:04:14 +01001923bool HBasicBlock::HasThrowingInstructions() const {
1924 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1925 if (it.Current()->CanThrow()) {
1926 return true;
1927 }
1928 }
1929 return false;
1930}
1931
David Brazdilfc6a86a2015-06-26 10:33:45 +00001932static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1933 return block.GetPhis().IsEmpty()
1934 && !block.GetInstructions().IsEmpty()
1935 && block.GetFirstInstruction() == block.GetLastInstruction();
1936}
1937
David Brazdil46e2a392015-03-16 17:31:52 +00001938bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001939 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1940}
1941
Mads Ager16e52892017-07-14 13:11:37 +02001942bool HBasicBlock::IsSingleReturn() const {
1943 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
1944}
1945
Mingyao Yang46721ef2017-10-05 14:45:17 -07001946bool HBasicBlock::IsSingleReturnOrReturnVoidAllowingPhis() const {
1947 return (GetFirstInstruction() == GetLastInstruction()) &&
1948 (GetLastInstruction()->IsReturn() || GetLastInstruction()->IsReturnVoid());
1949}
1950
David Brazdilfc6a86a2015-06-26 10:33:45 +00001951bool HBasicBlock::IsSingleTryBoundary() const {
1952 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001953}
1954
David Brazdil8d5b8b22015-03-24 10:51:52 +00001955bool HBasicBlock::EndsWithControlFlowInstruction() const {
1956 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1957}
1958
David Brazdilb2bd1c52015-03-25 11:17:37 +00001959bool HBasicBlock::EndsWithIf() const {
1960 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1961}
1962
David Brazdilffee3d32015-07-06 11:48:53 +01001963bool HBasicBlock::EndsWithTryBoundary() const {
1964 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1965}
1966
David Brazdilb2bd1c52015-03-25 11:17:37 +00001967bool HBasicBlock::HasSinglePhi() const {
1968 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1969}
1970
David Brazdild26a4112015-11-10 11:07:31 +00001971ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1972 if (EndsWithTryBoundary()) {
1973 // The normal-flow successor of HTryBoundary is always stored at index zero.
1974 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1975 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1976 } else {
1977 // All successors of blocks not ending with TryBoundary are normal.
1978 return ArrayRef<HBasicBlock* const>(successors_);
1979 }
1980}
1981
1982ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1983 if (EndsWithTryBoundary()) {
1984 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1985 } else {
1986 // Blocks not ending with TryBoundary do not have exceptional successors.
1987 return ArrayRef<HBasicBlock* const>();
1988 }
1989}
1990
David Brazdilffee3d32015-07-06 11:48:53 +01001991bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001992 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1993 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1994
1995 size_t length = handlers1.size();
1996 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001997 return false;
1998 }
1999
David Brazdilb618ade2015-07-29 10:31:29 +01002000 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00002001 for (size_t i = 0; i < length; ++i) {
2002 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01002003 return false;
2004 }
2005 }
2006 return true;
2007}
2008
David Brazdil2d7352b2015-04-20 14:52:42 +01002009size_t HInstructionList::CountSize() const {
2010 size_t size = 0;
2011 HInstruction* current = first_instruction_;
2012 for (; current != nullptr; current = current->GetNext()) {
2013 size++;
2014 }
2015 return size;
2016}
2017
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002018void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
2019 for (HInstruction* current = first_instruction_;
2020 current != nullptr;
2021 current = current->GetNext()) {
2022 current->SetBlock(block);
2023 }
2024}
2025
2026void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
2027 DCHECK(Contains(cursor));
2028 if (!instruction_list.IsEmpty()) {
2029 if (cursor == last_instruction_) {
2030 last_instruction_ = instruction_list.last_instruction_;
2031 } else {
2032 cursor->next_->previous_ = instruction_list.last_instruction_;
2033 }
2034 instruction_list.last_instruction_->next_ = cursor->next_;
2035 cursor->next_ = instruction_list.first_instruction_;
2036 instruction_list.first_instruction_->previous_ = cursor;
2037 }
2038}
2039
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002040void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
2041 DCHECK(Contains(cursor));
2042 if (!instruction_list.IsEmpty()) {
2043 if (cursor == first_instruction_) {
2044 first_instruction_ = instruction_list.first_instruction_;
2045 } else {
2046 cursor->previous_->next_ = instruction_list.first_instruction_;
2047 }
2048 instruction_list.last_instruction_->next_ = cursor;
2049 instruction_list.first_instruction_->previous_ = cursor->previous_;
2050 cursor->previous_ = instruction_list.last_instruction_;
2051 }
2052}
2053
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002054void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00002055 if (IsEmpty()) {
2056 first_instruction_ = instruction_list.first_instruction_;
2057 last_instruction_ = instruction_list.last_instruction_;
2058 } else {
2059 AddAfter(last_instruction_, instruction_list);
2060 }
2061}
2062
David Brazdil04ff4e82015-12-10 13:54:52 +00002063// Should be called on instructions in a dead block in post order. This method
2064// assumes `insn` has been removed from all users with the exception of catch
2065// phis because of missing exceptional edges in the graph. It removes the
2066// instruction from catch phi uses, together with inputs of other catch phis in
2067// the catch block at the same index, as these must be dead too.
2068static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
2069 DCHECK(!insn->HasEnvironmentUses());
2070 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01002071 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
2072 size_t use_index = use.GetIndex();
2073 HBasicBlock* user_block = use.GetUser()->GetBlock();
2074 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00002075 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2076 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
2077 }
2078 }
2079}
2080
David Brazdil2d7352b2015-04-20 14:52:42 +01002081void HBasicBlock::DisconnectAndDelete() {
2082 // Dominators must be removed after all the blocks they dominate. This way
2083 // a loop header is removed last, a requirement for correct loop information
2084 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00002085 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00002086
David Brazdil9eeebf62016-03-24 11:18:15 +00002087 // The following steps gradually remove the block from all its dependants in
2088 // post order (b/27683071).
2089
2090 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
2091 // We need to do this before step (4) which destroys the predecessor list.
2092 HBasicBlock* loop_update_start = this;
2093 if (IsLoopHeader()) {
2094 HLoopInformation* loop_info = GetLoopInformation();
2095 // All other blocks in this loop should have been removed because the header
2096 // was their dominator.
2097 // Note that we do not remove `this` from `loop_info` as it is unreachable.
2098 DCHECK(!loop_info->IsIrreducible());
2099 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
2100 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
2101 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01002102 }
2103
David Brazdil9eeebf62016-03-24 11:18:15 +00002104 // (2) Disconnect the block from its successors and update their phis.
2105 for (HBasicBlock* successor : successors_) {
2106 // Delete this block from the list of predecessors.
2107 size_t this_index = successor->GetPredecessorIndexOf(this);
2108 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
2109
2110 // Check that `successor` has other predecessors, otherwise `this` is the
2111 // dominator of `successor` which violates the order DCHECKed at the top.
2112 DCHECK(!successor->predecessors_.empty());
2113
2114 // Remove this block's entries in the successor's phis. Skip exceptional
2115 // successors because catch phi inputs do not correspond to predecessor
2116 // blocks but throwing instructions. The inputs of the catch phis will be
2117 // updated in step (3).
2118 if (!successor->IsCatchBlock()) {
2119 if (successor->predecessors_.size() == 1u) {
2120 // The successor has just one predecessor left. Replace phis with the only
2121 // remaining input.
2122 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2123 HPhi* phi = phi_it.Current()->AsPhi();
2124 phi->ReplaceWith(phi->InputAt(1 - this_index));
2125 successor->RemovePhi(phi);
2126 }
2127 } else {
2128 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
2129 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
2130 }
2131 }
2132 }
2133 }
2134 successors_.clear();
2135
2136 // (3) Remove instructions and phis. Instructions should have no remaining uses
2137 // except in catch phis. If an instruction is used by a catch phi at `index`,
2138 // remove `index`-th input of all phis in the catch block since they are
2139 // guaranteed dead. Note that we may miss dead inputs this way but the
2140 // graph will always remain consistent.
2141 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
2142 HInstruction* insn = it.Current();
2143 RemoveUsesOfDeadInstruction(insn);
2144 RemoveInstruction(insn);
2145 }
2146 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
2147 HPhi* insn = it.Current()->AsPhi();
2148 RemoveUsesOfDeadInstruction(insn);
2149 RemovePhi(insn);
2150 }
2151
2152 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002153 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00002154 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00002155 // We should not see any back edges as they would have been removed by step (3).
2156 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
2157
David Brazdil2d7352b2015-04-20 14:52:42 +01002158 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002159 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
2160 // This block is the only normal-flow successor of the TryBoundary which
2161 // makes `predecessor` dead. Since DCE removes blocks in post order,
2162 // exception handlers of this TryBoundary were already visited and any
2163 // remaining handlers therefore must be live. We remove `predecessor` from
2164 // their list of predecessors.
2165 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
2166 while (predecessor->GetSuccessors().size() > 1) {
2167 HBasicBlock* handler = predecessor->GetSuccessors()[1];
2168 DCHECK(handler->IsCatchBlock());
2169 predecessor->RemoveSuccessor(handler);
2170 handler->RemovePredecessor(predecessor);
2171 }
2172 }
2173
David Brazdil2d7352b2015-04-20 14:52:42 +01002174 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04002175 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
2176 if (num_pred_successors == 1u) {
2177 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002178 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
2179 // successor. Replace those with a HGoto.
2180 DCHECK(last_instruction->IsIf() ||
2181 last_instruction->IsPackedSwitch() ||
2182 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002183 predecessor->RemoveInstruction(last_instruction);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002184 predecessor->AddInstruction(new (graph_->GetAllocator()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002185 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002186 // The predecessor has no remaining successors and therefore must be dead.
2187 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00002188 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04002189 predecessor->RemoveInstruction(last_instruction);
2190 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002191 // There are multiple successors left. The removed block might be a successor
2192 // of a PackedSwitch which will be completely removed (perhaps replaced with
2193 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2194 // case, leave `last_instruction` as is for now.
2195 DCHECK(last_instruction->IsPackedSwitch() ||
2196 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002197 }
David Brazdil46e2a392015-03-16 17:31:52 +00002198 }
Vladimir Marko60584552015-09-03 13:35:12 +00002199 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002200
David Brazdil9eeebf62016-03-24 11:18:15 +00002201 // (5) Remove the block from all loops it is included in. Skip the inner-most
2202 // loop if this is the loop header (see definition of `loop_update_start`)
2203 // because the loop header's predecessor list has been destroyed in step (4).
2204 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2205 HLoopInformation* loop_info = it.Current();
2206 loop_info->Remove(this);
2207 if (loop_info->IsBackEdge(*this)) {
2208 // If this was the last back edge of the loop, we deliberately leave the
2209 // loop in an inconsistent state and will fail GraphChecker unless the
2210 // entire loop is removed during the pass.
2211 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002212 }
2213 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002214
David Brazdil9eeebf62016-03-24 11:18:15 +00002215 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002216 dominator_->RemoveDominatedBlock(this);
2217 SetDominator(nullptr);
2218
David Brazdil9eeebf62016-03-24 11:18:15 +00002219 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002220 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002221 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002222}
2223
Aart Bik6b69e0a2017-01-11 10:20:43 -08002224void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2225 DCHECK(EndsWithControlFlowInstruction());
2226 RemoveInstruction(GetLastInstruction());
2227 instructions_.Add(other->GetInstructions());
2228 other->instructions_.SetBlockOfInstructions(this);
2229 other->instructions_.Clear();
2230}
2231
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002232void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002233 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002234 DCHECK(ContainsElement(dominated_blocks_, other));
2235 DCHECK_EQ(GetSingleSuccessor(), other);
2236 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002237 DCHECK(other->GetPhis().IsEmpty());
2238
David Brazdil2d7352b2015-04-20 14:52:42 +01002239 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002240 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002241
David Brazdil2d7352b2015-04-20 14:52:42 +01002242 // Remove `other` from the loops it is included in.
2243 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2244 HLoopInformation* loop_info = it.Current();
2245 loop_info->Remove(other);
2246 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002247 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002248 }
2249 }
2250
2251 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002252 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002253 for (HBasicBlock* successor : other->GetSuccessors()) {
2254 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002255 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002256 successors_.swap(other->successors_);
2257 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002258
David Brazdil2d7352b2015-04-20 14:52:42 +01002259 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002260 RemoveDominatedBlock(other);
2261 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002262 dominated->SetDominator(this);
2263 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002264 dominated_blocks_.insert(
2265 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002266 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002267 other->dominator_ = nullptr;
2268
2269 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002270 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002271
2272 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002273 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002274 other->SetGraph(nullptr);
2275}
2276
2277void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2278 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002279 DCHECK(GetDominatedBlocks().empty());
2280 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002281 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002282 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002283 DCHECK(other->GetPhis().IsEmpty());
2284 DCHECK(!other->IsInLoop());
2285
2286 // Move instructions from `other` to `this`.
2287 instructions_.Add(other->GetInstructions());
2288 other->instructions_.SetBlockOfInstructions(this);
2289
2290 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002291 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002292 for (HBasicBlock* successor : other->GetSuccessors()) {
2293 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002294 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002295 successors_.swap(other->successors_);
2296 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002297
2298 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002299 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002300 dominated->SetDominator(this);
2301 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002302 dominated_blocks_.insert(
2303 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002304 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002305 other->dominator_ = nullptr;
2306 other->graph_ = nullptr;
2307}
2308
2309void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002310 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002311 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002312 predecessor->ReplaceSuccessor(this, other);
2313 }
Vladimir Marko60584552015-09-03 13:35:12 +00002314 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002315 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002316 successor->ReplacePredecessor(this, other);
2317 }
Vladimir Marko60584552015-09-03 13:35:12 +00002318 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2319 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002320 }
2321 GetDominator()->ReplaceDominatedBlock(this, other);
2322 other->SetDominator(GetDominator());
2323 dominator_ = nullptr;
2324 graph_ = nullptr;
2325}
2326
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002327void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002328 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002329 DCHECK(block->GetSuccessors().empty());
2330 DCHECK(block->GetPredecessors().empty());
2331 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002332 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002333 DCHECK(block->GetInstructions().IsEmpty());
2334 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002335
David Brazdilc7af85d2015-05-26 12:05:55 +01002336 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002337 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002338 }
2339
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002340 RemoveElement(reverse_post_order_, block);
2341 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002342 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002343}
2344
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002345void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2346 HBasicBlock* reference,
2347 bool replace_if_back_edge) {
2348 if (block->IsLoopHeader()) {
2349 // Clear the information of which blocks are contained in that loop. Since the
2350 // information is stored as a bit vector based on block ids, we have to update
2351 // it, as those block ids were specific to the callee graph and we are now adding
2352 // these blocks to the caller graph.
2353 block->GetLoopInformation()->ClearAllBlocks();
2354 }
2355
2356 // If not already in a loop, update the loop information.
2357 if (!block->IsInLoop()) {
2358 block->SetLoopInformation(reference->GetLoopInformation());
2359 }
2360
2361 // If the block is in a loop, update all its outward loops.
2362 HLoopInformation* loop_info = block->GetLoopInformation();
2363 if (loop_info != nullptr) {
2364 for (HLoopInformationOutwardIterator loop_it(*block);
2365 !loop_it.Done();
2366 loop_it.Advance()) {
2367 loop_it.Current()->Add(block);
2368 }
2369 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2370 loop_info->ReplaceBackEdge(reference, block);
2371 }
2372 }
2373
2374 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2375 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2376 ? reference->GetTryCatchInformation()
2377 : nullptr;
2378 block->SetTryCatchInformation(try_catch_info);
2379}
2380
Calin Juravle2e768302015-07-28 14:41:11 +00002381HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002382 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002383 // Update the environments in this graph to have the invoke's environment
2384 // as parent.
2385 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002386 // Skip the entry block, we do not need to update the entry's suspend check.
2387 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002388 for (HInstructionIterator instr_it(block->GetInstructions());
2389 !instr_it.Done();
2390 instr_it.Advance()) {
2391 HInstruction* current = instr_it.Current();
2392 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002393 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002394 current->GetEnvironment()->SetAndCopyParentChain(
Vladimir Markoca6fff82017-10-03 14:49:14 +01002395 outer_graph->GetAllocator(), invoke->GetEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002396 }
2397 }
2398 }
2399 }
2400 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002401
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002402 if (HasBoundsChecks()) {
2403 outer_graph->SetHasBoundsChecks(true);
2404 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002405 if (HasLoops()) {
2406 outer_graph->SetHasLoops(true);
2407 }
2408 if (HasIrreducibleLoops()) {
2409 outer_graph->SetHasIrreducibleLoops(true);
2410 }
2411 if (HasTryCatch()) {
2412 outer_graph->SetHasTryCatch(true);
2413 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002414 if (HasSIMD()) {
2415 outer_graph->SetHasSIMD(true);
2416 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002417
Calin Juravle2e768302015-07-28 14:41:11 +00002418 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002419 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002420 // Inliner already made sure we don't inline methods that always throw.
2421 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002422 // Simple case of an entry block, a body block, and an exit block.
2423 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002424 HBasicBlock* body = GetBlocks()[1];
2425 DCHECK(GetBlocks()[0]->IsEntryBlock());
2426 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002427 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002428 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002429 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002430
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002431 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2432 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002433 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002434
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002435 // Replace the invoke with the return value of the inlined graph.
2436 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002437 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002438 } else {
2439 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002440 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002441
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002442 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002443 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002444 // Need to inline multiple blocks. We split `invoke`'s block
2445 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002446 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002447 // with the second half.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002448 ArenaAllocator* allocator = outer_graph->GetAllocator();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002449 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002450 // Note that we split before the invoke only to simplify polymorphic inlining.
2451 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002452
Vladimir Markoec7802a2015-10-01 20:57:57 +01002453 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002454 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002455 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002456 exit_block_->ReplaceWith(to);
2457
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002458 // Update the meta information surrounding blocks:
2459 // (1) the graph they are now in,
2460 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002461 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002462 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002463 // Note that we do not need to update catch phi inputs because they
2464 // correspond to the register file of the outer method which the inlinee
2465 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002466
2467 // We don't add the entry block, the exit block, and the first block, which
2468 // has been merged with `at`.
2469 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2470
2471 // We add the `to` block.
2472 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002473 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002474 + kNumberOfNewBlocksInCaller;
2475
2476 // Find the location of `at` in the outer graph's reverse post order. The new
2477 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002478 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002479 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2480
David Brazdil95177982015-10-30 12:56:58 -05002481 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2482 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002483 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002484 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002485 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002486 DCHECK(current->GetGraph() == this);
2487 current->SetGraph(outer_graph);
2488 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002489 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002490 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002491 }
2492 }
2493
David Brazdil95177982015-10-30 12:56:58 -05002494 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002495 to->SetGraph(outer_graph);
2496 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002497 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002498 // Only `to` can become a back edge, as the inlined blocks
2499 // are predecessors of `to`.
2500 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002501
David Brazdil3f523062016-02-29 16:53:33 +00002502 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002503 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2504 // to now get the outer graph exit block as successor. Note that the inliner
2505 // currently doesn't support inlining methods with try/catch.
2506 HPhi* return_value_phi = nullptr;
2507 bool rerun_dominance = false;
2508 bool rerun_loop_analysis = false;
2509 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2510 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002511 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002512 if (last->IsThrow()) {
2513 DCHECK(!at->IsTryBlock());
2514 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2515 --pred;
2516 // We need to re-run dominance information, as the exit block now has
2517 // a new dominator.
2518 rerun_dominance = true;
2519 if (predecessor->GetLoopInformation() != nullptr) {
2520 // The exit block and blocks post dominated by the exit block do not belong
2521 // to any loop. Because we do not compute the post dominators, we need to re-run
2522 // loop analysis to get the loop information correct.
2523 rerun_loop_analysis = true;
2524 }
2525 } else {
2526 if (last->IsReturnVoid()) {
2527 DCHECK(return_value == nullptr);
2528 DCHECK(return_value_phi == nullptr);
2529 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002530 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002531 if (return_value_phi != nullptr) {
2532 return_value_phi->AddInput(last->InputAt(0));
2533 } else if (return_value == nullptr) {
2534 return_value = last->InputAt(0);
2535 } else {
2536 // There will be multiple returns.
2537 return_value_phi = new (allocator) HPhi(
2538 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2539 to->AddPhi(return_value_phi);
2540 return_value_phi->AddInput(return_value);
2541 return_value_phi->AddInput(last->InputAt(0));
2542 return_value = return_value_phi;
2543 }
David Brazdil3f523062016-02-29 16:53:33 +00002544 }
2545 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2546 predecessor->RemoveInstruction(last);
2547 }
2548 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002549 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002550 DCHECK(!outer_graph->HasIrreducibleLoops())
2551 << "Recomputing loop information in graphs with irreducible loops "
2552 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002553 outer_graph->ClearLoopInformation();
2554 outer_graph->ClearDominanceInformation();
2555 outer_graph->BuildDominatorTree();
2556 } else if (rerun_dominance) {
2557 outer_graph->ClearDominanceInformation();
2558 outer_graph->ComputeDominanceInformation();
2559 }
David Brazdil3f523062016-02-29 16:53:33 +00002560 }
David Brazdil05144f42015-04-16 15:18:00 +01002561
2562 // Walk over the entry block and:
2563 // - Move constants from the entry block to the outer_graph's entry block,
2564 // - Replace HParameterValue instructions with their real value.
2565 // - Remove suspend checks, that hold an environment.
2566 // We must do this after the other blocks have been inlined, otherwise ids of
2567 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002568 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002569 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2570 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002571 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002572 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002573 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002574 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002575 replacement = outer_graph->GetIntConstant(
2576 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002577 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002578 replacement = outer_graph->GetLongConstant(
2579 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002580 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002581 replacement = outer_graph->GetFloatConstant(
2582 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002583 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002584 replacement = outer_graph->GetDoubleConstant(
2585 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002586 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002587 if (kIsDebugBuild
2588 && invoke->IsInvokeStaticOrDirect()
2589 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2590 // Ensure we do not use the last input of `invoke`, as it
2591 // contains a clinit check which is not an actual argument.
2592 size_t last_input_index = invoke->InputCount() - 1;
2593 DCHECK(parameter_index != last_input_index);
2594 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002595 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002596 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002597 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002598 } else {
2599 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2600 entry_block_->RemoveInstruction(current);
2601 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002602 if (replacement != nullptr) {
2603 current->ReplaceWith(replacement);
2604 // If the current is the return value then we need to update the latter.
2605 if (current == return_value) {
2606 DCHECK_EQ(entry_block_, return_value->GetBlock());
2607 return_value = replacement;
2608 }
2609 }
2610 }
2611
Calin Juravle2e768302015-07-28 14:41:11 +00002612 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002613}
2614
Mingyao Yang3584bce2015-05-19 16:01:59 -07002615/*
2616 * Loop will be transformed to:
2617 * old_pre_header
2618 * |
2619 * if_block
2620 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002621 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002622 * \ /
2623 * new_pre_header
2624 * |
2625 * header
2626 */
2627void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2628 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002629 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002630
Aart Bik3fc7f352015-11-20 22:03:03 -08002631 // Need extra block to avoid critical edge.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002632 HBasicBlock* if_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2633 HBasicBlock* true_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2634 HBasicBlock* false_block = new (allocator_) HBasicBlock(this, header->GetDexPc());
2635 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002636 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002637 AddBlock(true_block);
2638 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002639 AddBlock(new_pre_header);
2640
Aart Bik3fc7f352015-11-20 22:03:03 -08002641 header->ReplacePredecessor(old_pre_header, new_pre_header);
2642 old_pre_header->successors_.clear();
2643 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002644
Aart Bik3fc7f352015-11-20 22:03:03 -08002645 old_pre_header->AddSuccessor(if_block);
2646 if_block->AddSuccessor(true_block); // True successor
2647 if_block->AddSuccessor(false_block); // False successor
2648 true_block->AddSuccessor(new_pre_header);
2649 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002650
Aart Bik3fc7f352015-11-20 22:03:03 -08002651 old_pre_header->dominated_blocks_.push_back(if_block);
2652 if_block->SetDominator(old_pre_header);
2653 if_block->dominated_blocks_.push_back(true_block);
2654 true_block->SetDominator(if_block);
2655 if_block->dominated_blocks_.push_back(false_block);
2656 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002657 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002658 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002659 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002660 header->SetDominator(new_pre_header);
2661
Aart Bik3fc7f352015-11-20 22:03:03 -08002662 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002663 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002664 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002665 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002666 reverse_post_order_[index_of_header++] = true_block;
2667 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002668 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002669
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002670 // The pre_header can never be a back edge of a loop.
2671 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2672 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2673 UpdateLoopAndTryInformationOfNewBlock(
2674 if_block, old_pre_header, /* replace_if_back_edge */ false);
2675 UpdateLoopAndTryInformationOfNewBlock(
2676 true_block, old_pre_header, /* replace_if_back_edge */ false);
2677 UpdateLoopAndTryInformationOfNewBlock(
2678 false_block, old_pre_header, /* replace_if_back_edge */ false);
2679 UpdateLoopAndTryInformationOfNewBlock(
2680 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002681}
2682
Aart Bikf8f5a162017-02-06 15:35:29 -08002683HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2684 HBasicBlock* body,
2685 HBasicBlock* exit) {
2686 DCHECK(header->IsLoopHeader());
2687 HLoopInformation* loop = header->GetLoopInformation();
2688
2689 // Add new loop blocks.
Vladimir Markoca6fff82017-10-03 14:49:14 +01002690 HBasicBlock* new_pre_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2691 HBasicBlock* new_header = new (allocator_) HBasicBlock(this, header->GetDexPc());
2692 HBasicBlock* new_body = new (allocator_) HBasicBlock(this, header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002693 AddBlock(new_pre_header);
2694 AddBlock(new_header);
2695 AddBlock(new_body);
2696
2697 // Set up control flow.
2698 header->ReplaceSuccessor(exit, new_pre_header);
2699 new_pre_header->AddSuccessor(new_header);
2700 new_header->AddSuccessor(exit);
2701 new_header->AddSuccessor(new_body);
2702 new_body->AddSuccessor(new_header);
2703
2704 // Set up dominators.
2705 header->ReplaceDominatedBlock(exit, new_pre_header);
2706 new_pre_header->SetDominator(header);
2707 new_pre_header->dominated_blocks_.push_back(new_header);
2708 new_header->SetDominator(new_pre_header);
2709 new_header->dominated_blocks_.push_back(new_body);
2710 new_body->SetDominator(new_header);
2711 new_header->dominated_blocks_.push_back(exit);
2712 exit->SetDominator(new_header);
2713
2714 // Fix reverse post order.
2715 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2716 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2717 reverse_post_order_[++index_of_header] = new_pre_header;
2718 reverse_post_order_[++index_of_header] = new_header;
2719 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2720 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2721 reverse_post_order_[index_of_body] = new_body;
2722
Aart Bikb07d1bc2017-04-05 10:03:15 -07002723 // Add gotos and suspend check (client must add conditional in header).
Vladimir Markoca6fff82017-10-03 14:49:14 +01002724 new_pre_header->AddInstruction(new (allocator_) HGoto());
2725 HSuspendCheck* suspend_check = new (allocator_) HSuspendCheck(header->GetDexPc());
Aart Bikf8f5a162017-02-06 15:35:29 -08002726 new_header->AddInstruction(suspend_check);
Vladimir Markoca6fff82017-10-03 14:49:14 +01002727 new_body->AddInstruction(new (allocator_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002728 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2729 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002730
2731 // Update loop information.
2732 new_header->AddBackEdge(new_body);
2733 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2734 new_header->GetLoopInformation()->Populate();
2735 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2736 HLoopInformationOutwardIterator it(*new_header);
2737 for (it.Advance(); !it.Done(); it.Advance()) {
2738 it.Current()->Add(new_pre_header);
2739 it.Current()->Add(new_header);
2740 it.Current()->Add(new_body);
2741 }
2742 return new_pre_header;
2743}
2744
David Brazdilf5552582015-12-27 13:36:12 +00002745static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002746 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002747 if (rti.IsValid()) {
2748 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2749 << " upper_bound_rti: " << upper_bound_rti
2750 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002751 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2752 << " upper_bound_rti: " << upper_bound_rti
2753 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002754 }
2755}
2756
Calin Juravle2e768302015-07-28 14:41:11 +00002757void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2758 if (kIsDebugBuild) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01002759 DCHECK_EQ(GetType(), DataType::Type::kReference);
Calin Juravle2e768302015-07-28 14:41:11 +00002760 ScopedObjectAccess soa(Thread::Current());
2761 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2762 if (IsBoundType()) {
2763 // Having the test here spares us from making the method virtual just for
2764 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002765 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002766 }
2767 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002768 reference_type_handle_ = rti.GetTypeHandle();
2769 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002770}
2771
David Brazdilf5552582015-12-27 13:36:12 +00002772void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2773 if (kIsDebugBuild) {
2774 ScopedObjectAccess soa(Thread::Current());
2775 DCHECK(upper_bound.IsValid());
2776 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2777 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2778 }
2779 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002780 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002781}
2782
Vladimir Markoa1de9182016-02-25 11:37:38 +00002783ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002784 if (kIsDebugBuild) {
2785 ScopedObjectAccess soa(Thread::Current());
2786 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002787 if (!is_exact) {
2788 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2789 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2790 }
Calin Juravle2e768302015-07-28 14:41:11 +00002791 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002792 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002793}
2794
Calin Juravleacf735c2015-02-12 15:25:22 +00002795std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2796 ScopedObjectAccess soa(Thread::Current());
2797 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002798 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002799 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002800 << " is_exact=" << rhs.IsExact()
2801 << " ]";
2802 return os;
2803}
2804
Mark Mendellc4701932015-04-10 13:18:51 -04002805bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2806 // For now, assume that instructions in different blocks may use the
2807 // environment.
2808 // TODO: Use the control flow to decide if this is true.
2809 if (GetBlock() != other->GetBlock()) {
2810 return true;
2811 }
2812
2813 // We know that we are in the same block. Walk from 'this' to 'other',
2814 // checking to see if there is any instruction with an environment.
2815 HInstruction* current = this;
2816 for (; current != other && current != nullptr; current = current->GetNext()) {
2817 // This is a conservative check, as the instruction result may not be in
2818 // the referenced environment.
2819 if (current->HasEnvironment()) {
2820 return true;
2821 }
2822 }
2823
2824 // We should have been called with 'this' before 'other' in the block.
2825 // Just confirm this.
2826 DCHECK(current != nullptr);
2827 return false;
2828}
2829
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002830void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002831 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2832 IntrinsicSideEffects side_effects,
2833 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002834 intrinsic_ = intrinsic;
2835 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002836
Aart Bik5d75afe2015-12-14 11:57:01 -08002837 // Adjust method's side effects from intrinsic table.
2838 switch (side_effects) {
2839 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2840 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2841 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2842 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2843 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002844
2845 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2846 opt.SetDoesNotNeedDexCache();
2847 opt.SetDoesNotNeedEnvironment();
2848 } else {
2849 // If we need an environment, that means there will be a call, which can trigger GC.
2850 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2851 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002852 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002853 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002854}
2855
David Brazdil6de19382016-01-08 17:37:10 +00002856bool HNewInstance::IsStringAlloc() const {
2857 ScopedObjectAccess soa(Thread::Current());
2858 return GetReferenceTypeInfo().IsStringClass();
2859}
2860
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002861bool HInvoke::NeedsEnvironment() const {
2862 if (!IsIntrinsic()) {
2863 return true;
2864 }
2865 IntrinsicOptimizations opt(*this);
2866 return !opt.GetDoesNotNeedEnvironment();
2867}
2868
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002869const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2870 ArtMethod* caller = GetEnvironment()->GetMethod();
2871 ScopedObjectAccess soa(Thread::Current());
2872 // `caller` is null for a top-level graph representing a method whose declaring
2873 // class was not resolved.
2874 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2875}
2876
Vladimir Markodc151b22015-10-15 18:02:30 +01002877bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002878 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002879 return false;
2880 }
2881 if (!IsIntrinsic()) {
2882 return true;
2883 }
2884 IntrinsicOptimizations opt(*this);
2885 return !opt.GetDoesNotNeedDexCache();
2886}
2887
Vladimir Markof64242a2015-12-01 14:58:23 +00002888std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2889 switch (rhs) {
2890 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002891 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002892 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002893 return os << "Recursive";
2894 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2895 return os << "BootImageLinkTimePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002896 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
Vladimir Marko19d7d502017-05-24 13:04:14 +01002897 return os << "DirectAddress";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002898 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2899 return os << "BssEntry";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002900 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2901 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002902 default:
2903 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2904 UNREACHABLE();
2905 }
2906}
2907
Vladimir Markofbb184a2015-11-13 14:47:00 +00002908std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2909 switch (rhs) {
2910 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2911 return os << "explicit";
2912 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2913 return os << "implicit";
2914 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2915 return os << "none";
2916 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002917 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2918 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002919 }
2920}
2921
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002922bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2923 const HLoadClass* other_load_class = other->AsLoadClass();
2924 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2925 // names rather than type indexes. However, we shall also have to re-think the hash code.
2926 if (type_index_ != other_load_class->type_index_ ||
2927 GetPackedFields() != other_load_class->GetPackedFields()) {
2928 return false;
2929 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002930 switch (GetLoadKind()) {
2931 case LoadKind::kBootImageAddress:
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002932 case LoadKind::kBootImageClassTable:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002933 case LoadKind::kJitTableAddress: {
2934 ScopedObjectAccess soa(Thread::Current());
2935 return GetClass().Get() == other_load_class->GetClass().Get();
2936 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002937 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002938 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002939 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002940 }
2941}
2942
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002943std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2944 switch (rhs) {
2945 case HLoadClass::LoadKind::kReferrersClass:
2946 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002947 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2948 return os << "BootImageLinkTimePcRelative";
2949 case HLoadClass::LoadKind::kBootImageAddress:
2950 return os << "BootImageAddress";
Vladimir Marko94ec2db2017-09-06 17:21:03 +01002951 case HLoadClass::LoadKind::kBootImageClassTable:
2952 return os << "BootImageClassTable";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002953 case HLoadClass::LoadKind::kBssEntry:
2954 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002955 case HLoadClass::LoadKind::kJitTableAddress:
2956 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002957 case HLoadClass::LoadKind::kRuntimeCall:
2958 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002959 default:
2960 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2961 UNREACHABLE();
2962 }
2963}
2964
Vladimir Marko372f10e2016-05-17 16:30:10 +01002965bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2966 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002967 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2968 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002969 if (string_index_ != other_load_string->string_index_ ||
2970 GetPackedFields() != other_load_string->GetPackedFields()) {
2971 return false;
2972 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002973 switch (GetLoadKind()) {
2974 case LoadKind::kBootImageAddress:
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002975 case LoadKind::kBootImageInternTable:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002976 case LoadKind::kJitTableAddress: {
2977 ScopedObjectAccess soa(Thread::Current());
2978 return GetString().Get() == other_load_string->GetString().Get();
2979 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002980 default:
2981 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002982 }
2983}
2984
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002985std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2986 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002987 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2988 return os << "BootImageLinkTimePcRelative";
2989 case HLoadString::LoadKind::kBootImageAddress:
2990 return os << "BootImageAddress";
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002991 case HLoadString::LoadKind::kBootImageInternTable:
2992 return os << "BootImageInternTable";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002993 case HLoadString::LoadKind::kBssEntry:
2994 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002995 case HLoadString::LoadKind::kJitTableAddress:
2996 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002997 case HLoadString::LoadKind::kRuntimeCall:
2998 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002999 default:
3000 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
3001 UNREACHABLE();
3002 }
3003}
3004
Mark Mendellc4701932015-04-10 13:18:51 -04003005void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01003006 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
3007 HEnvironment* user = use.GetUser();
3008 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04003009 }
Vladimir Marko46817b82016-03-29 12:21:58 +01003010 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04003011}
3012
Artem Serovcced8ba2017-07-19 18:18:09 +01003013HInstruction* ReplaceInstrOrPhiByClone(HInstruction* instr) {
3014 HInstruction* clone = instr->Clone(instr->GetBlock()->GetGraph()->GetAllocator());
3015 HBasicBlock* block = instr->GetBlock();
3016
3017 if (instr->IsPhi()) {
3018 HPhi* phi = instr->AsPhi();
3019 DCHECK(!phi->HasEnvironment());
3020 HPhi* phi_clone = clone->AsPhi();
3021 block->ReplaceAndRemovePhiWith(phi, phi_clone);
3022 } else {
3023 block->ReplaceAndRemoveInstructionWith(instr, clone);
3024 if (instr->HasEnvironment()) {
3025 clone->CopyEnvironmentFrom(instr->GetEnvironment());
3026 HLoopInformation* loop_info = block->GetLoopInformation();
3027 if (instr->IsSuspendCheck() && loop_info != nullptr) {
3028 loop_info->SetSuspendCheck(clone->AsSuspendCheck());
3029 }
3030 }
3031 }
3032 return clone;
3033}
3034
Roland Levillainc9b21f82016-03-23 16:36:59 +00003035// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05003036HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
Vladimir Markoca6fff82017-10-03 14:49:14 +01003037 ArenaAllocator* allocator = GetAllocator();
Mark Mendellf6529172015-11-17 11:16:56 -05003038
3039 if (cond->IsCondition() &&
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01003040 !DataType::IsFloatingPointType(cond->InputAt(0)->GetType())) {
Mark Mendellf6529172015-11-17 11:16:56 -05003041 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
3042 HInstruction* lhs = cond->InputAt(0);
3043 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00003044 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05003045 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
3046 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
3047 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
3048 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
3049 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
3050 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
3051 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
3052 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
3053 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
3054 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
3055 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00003056 default:
3057 LOG(FATAL) << "Unexpected condition";
3058 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05003059 }
3060 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3061 return replacement;
3062 } else if (cond->IsIntConstant()) {
3063 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00003064 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05003065 return GetIntConstant(1);
3066 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00003067 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05003068 return GetIntConstant(0);
3069 }
3070 } else {
3071 HInstruction* replacement = new (allocator) HBooleanNot(cond);
3072 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
3073 return replacement;
3074 }
3075}
3076
Roland Levillainc9285912015-12-18 10:38:42 +00003077std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
3078 os << "["
3079 << " source=" << rhs.GetSource()
3080 << " destination=" << rhs.GetDestination()
3081 << " type=" << rhs.GetType()
3082 << " instruction=";
3083 if (rhs.GetInstruction() != nullptr) {
3084 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
3085 } else {
3086 os << "null";
3087 }
3088 os << " ]";
3089 return os;
3090}
3091
Roland Levillain86503782016-02-11 19:07:30 +00003092std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
3093 switch (rhs) {
3094 case TypeCheckKind::kUnresolvedCheck:
3095 return os << "unresolved_check";
3096 case TypeCheckKind::kExactCheck:
3097 return os << "exact_check";
3098 case TypeCheckKind::kClassHierarchyCheck:
3099 return os << "class_hierarchy_check";
3100 case TypeCheckKind::kAbstractClassCheck:
3101 return os << "abstract_class_check";
3102 case TypeCheckKind::kInterfaceCheck:
3103 return os << "interface_check";
3104 case TypeCheckKind::kArrayObjectCheck:
3105 return os << "array_object_check";
3106 case TypeCheckKind::kArrayCheck:
3107 return os << "array_check";
3108 default:
3109 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
3110 UNREACHABLE();
3111 }
3112}
3113
Andreas Gampe26de38b2016-07-27 17:53:11 -07003114std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
3115 switch (kind) {
3116 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003117 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003118 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003119 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003120 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003121 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003122 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003123 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003124 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07003125 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07003126
3127 default:
3128 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
3129 UNREACHABLE();
3130 }
3131}
3132
Nicolas Geoffray818f2102014-02-18 16:43:35 +00003133} // namespace art