blob: ebbea27e08bd3b2c096aeaea28d5e49e0308773d [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
58 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markof6a35de2016-03-21 12:01:50 +000059 ArenaBitVector visiting(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010060 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +010061 ArenaVector<size_t> successors_visited(blocks_.size(),
62 0u,
63 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko3ea5a972016-05-09 20:23:34 +010065 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010066 constexpr size_t kDefaultWorklistSize = 8;
67 worklist.reserve(kDefaultWorklistSize);
68 visited->SetBit(entry_block_->GetBlockId());
69 visiting.SetBit(entry_block_->GetBlockId());
70 worklist.push_back(entry_block_);
71
72 while (!worklist.empty()) {
73 HBasicBlock* current = worklist.back();
74 uint32_t current_id = current->GetBlockId();
75 if (successors_visited[current_id] == current->GetSuccessors().size()) {
76 visiting.ClearBit(current_id);
77 worklist.pop_back();
78 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010079 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
80 uint32_t successor_id = successor->GetBlockId();
81 if (visiting.IsBitSet(successor_id)) {
82 DCHECK(ContainsElement(worklist, successor));
83 successor->AddBackEdge(current);
84 } else if (!visited->IsBitSet(successor_id)) {
85 visited->SetBit(successor_id);
86 visiting.SetBit(successor_id);
87 worklist.push_back(successor);
88 }
89 }
90 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000091}
92
Artem Serov21c7e6f2017-07-27 16:04:42 +010093// Remove the environment use records of the instruction for users.
94void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010095 for (HEnvironment* environment = instruction->GetEnvironment();
96 environment != nullptr;
97 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000098 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000099 if (environment->GetInstructionAt(i) != nullptr) {
100 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000101 }
102 }
103 }
104}
105
Artem Serov21c7e6f2017-07-27 16:04:42 +0100106// Return whether the instruction has an environment and it's used by others.
107bool HasEnvironmentUsedByOthers(HInstruction* instruction) {
108 for (HEnvironment* environment = instruction->GetEnvironment();
109 environment != nullptr;
110 environment = environment->GetParent()) {
111 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
112 HInstruction* user = environment->GetInstructionAt(i);
113 if (user != nullptr) {
114 return true;
115 }
116 }
117 }
118 return false;
119}
120
121// Reset environment records of the instruction itself.
122void ResetEnvironmentInputRecords(HInstruction* instruction) {
123 for (HEnvironment* environment = instruction->GetEnvironment();
124 environment != nullptr;
125 environment = environment->GetParent()) {
126 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
127 DCHECK(environment->GetHolder() == instruction);
128 if (environment->GetInstructionAt(i) != nullptr) {
129 environment->SetRawEnvAt(i, nullptr);
130 }
131 }
132 }
133}
134
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000135static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100136 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000137 RemoveEnvironmentUses(instruction);
138}
139
Roland Levillainfc600dc2014-12-02 17:16:31 +0000140void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100141 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000142 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100143 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000144 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100145 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000146 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
147 RemoveAsUser(it.Current());
148 }
149 }
150 }
151}
152
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100153void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100154 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000155 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100156 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000157 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100158 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000159 for (HBasicBlock* successor : block->GetSuccessors()) {
160 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000161 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100162 // Remove the block from the list of blocks, so that further analyses
163 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100164 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600165 if (block->IsExitBlock()) {
166 SetExitBlock(nullptr);
167 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000168 // Mark the block as removed. This is used by the HGraphBuilder to discard
169 // the block as a branch target.
170 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000171 }
172 }
173}
174
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000175GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000176 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000177
David Brazdil86ea7ee2016-02-16 09:26:07 +0000178 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000179 FindBackEdges(&visited);
180
David Brazdil86ea7ee2016-02-16 09:26:07 +0000181 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000182 // the initial DFS as users from other instructions, so that
183 // users can be safely removed before uses later.
184 RemoveInstructionsAsUsersFromDeadBlocks(visited);
185
David Brazdil86ea7ee2016-02-16 09:26:07 +0000186 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000187 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000188 // predecessors list of live blocks.
189 RemoveDeadBlocks(visited);
190
David Brazdil86ea7ee2016-02-16 09:26:07 +0000191 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100192 // dominators and the reverse post order.
193 SimplifyCFG();
194
David Brazdil86ea7ee2016-02-16 09:26:07 +0000195 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100196 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000197
David Brazdil86ea7ee2016-02-16 09:26:07 +0000198 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000199 // set the loop information on each block.
200 GraphAnalysisResult result = AnalyzeLoops();
201 if (result != kAnalysisSuccess) {
202 return result;
203 }
204
David Brazdil86ea7ee2016-02-16 09:26:07 +0000205 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000206 // which needs the information to build catch block phis from values of
207 // locals at throwing instructions inside try blocks.
208 ComputeTryBlockInformation();
209
210 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100211}
212
213void HGraph::ClearDominanceInformation() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100214 for (HBasicBlock* block : GetReversePostOrder()) {
215 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100216 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100217 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100218}
219
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000220void HGraph::ClearLoopInformation() {
221 SetHasIrreducibleLoops(false);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100222 for (HBasicBlock* block : GetReversePostOrder()) {
223 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000224 }
225}
226
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100227void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000228 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100229 dominator_ = nullptr;
230}
231
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000232HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
233 HInstruction* instruction = GetFirstInstruction();
234 while (instruction->IsParallelMove()) {
235 instruction = instruction->GetNext();
236 }
237 return instruction;
238}
239
David Brazdil3f4a5222016-05-06 12:46:21 +0100240static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
241 DCHECK(ContainsElement(block->GetSuccessors(), successor));
242
243 HBasicBlock* old_dominator = successor->GetDominator();
244 HBasicBlock* new_dominator =
245 (old_dominator == nullptr) ? block
246 : CommonDominator::ForPair(old_dominator, block);
247
248 if (old_dominator == new_dominator) {
249 return false;
250 } else {
251 successor->SetDominator(new_dominator);
252 return true;
253 }
254}
255
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100256void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100257 DCHECK(reverse_post_order_.empty());
258 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100259 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100260
261 // Number of visits of a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100262 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100263 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100264 ArenaVector<size_t> successors_visited(blocks_.size(),
265 0u,
266 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100267 // Nodes for which we need to visit successors.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100268 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100269 constexpr size_t kDefaultWorklistSize = 8;
270 worklist.reserve(kDefaultWorklistSize);
271 worklist.push_back(entry_block_);
272
273 while (!worklist.empty()) {
274 HBasicBlock* current = worklist.back();
275 uint32_t current_id = current->GetBlockId();
276 if (successors_visited[current_id] == current->GetSuccessors().size()) {
277 worklist.pop_back();
278 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100279 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100280 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100281
282 // Once all the forward edges have been visited, we know the immediate
283 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100284 if (++visits[successor->GetBlockId()] ==
285 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100286 reverse_post_order_.push_back(successor);
287 worklist.push_back(successor);
288 }
289 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000290 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000291
David Brazdil3f4a5222016-05-06 12:46:21 +0100292 // Check if the graph has back edges not dominated by their respective headers.
293 // If so, we need to update the dominators of those headers and recursively of
294 // their successors. We do that with a fix-point iteration over all blocks.
295 // The algorithm is guaranteed to terminate because it loops only if the sum
296 // of all dominator chains has decreased in the current iteration.
297 bool must_run_fix_point = false;
298 for (HBasicBlock* block : blocks_) {
299 if (block != nullptr &&
300 block->IsLoopHeader() &&
301 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
302 must_run_fix_point = true;
303 break;
304 }
305 }
306 if (must_run_fix_point) {
307 bool update_occurred = true;
308 while (update_occurred) {
309 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100310 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100311 for (HBasicBlock* successor : block->GetSuccessors()) {
312 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
313 }
314 }
315 }
316 }
317
318 // Make sure that there are no remaining blocks whose dominator information
319 // needs to be updated.
320 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100321 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100322 for (HBasicBlock* successor : block->GetSuccessors()) {
323 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
324 }
325 }
326 }
327
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000328 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000329 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100330 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000331 if (!block->IsEntryBlock()) {
332 block->GetDominator()->AddDominatedBlock(block);
333 }
334 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000335}
336
David Brazdilfc6a86a2015-06-26 10:33:45 +0000337HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000338 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
339 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000340 // Use `InsertBetween` to ensure the predecessor index and successor index of
341 // `block` and `successor` are preserved.
342 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000343 return new_block;
344}
345
346void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
347 // Insert a new node between `block` and `successor` to split the
348 // critical edge.
349 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600350 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100351 if (successor->IsLoopHeader()) {
352 // If we split at a back edge boundary, make the new block the back edge.
353 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000354 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100355 info->RemoveBackEdge(block);
356 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100357 }
358 }
359}
360
Artem Serovc73ee372017-07-31 15:08:40 +0100361// Reorder phi inputs to match reordering of the block's predecessors.
362static void FixPhisAfterPredecessorsReodering(HBasicBlock* block, size_t first, size_t second) {
363 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
364 HPhi* phi = it.Current()->AsPhi();
365 HInstruction* first_instr = phi->InputAt(first);
366 HInstruction* second_instr = phi->InputAt(second);
367 phi->ReplaceInput(first_instr, second);
368 phi->ReplaceInput(second_instr, first);
369 }
370}
371
372// Make sure that the first predecessor of a loop header is the incoming block.
373void HGraph::OrderLoopHeaderPredecessors(HBasicBlock* header) {
374 DCHECK(header->IsLoopHeader());
375 HLoopInformation* info = header->GetLoopInformation();
376 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
377 HBasicBlock* to_swap = header->GetPredecessors()[0];
378 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
379 HBasicBlock* predecessor = header->GetPredecessors()[pred];
380 if (!info->IsBackEdge(*predecessor)) {
381 header->predecessors_[pred] = to_swap;
382 header->predecessors_[0] = predecessor;
383 FixPhisAfterPredecessorsReodering(header, 0, pred);
384 break;
385 }
386 }
387 }
388}
389
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100390void HGraph::SimplifyLoop(HBasicBlock* header) {
391 HLoopInformation* info = header->GetLoopInformation();
392
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100393 // Make sure the loop has only one pre header. This simplifies SSA building by having
394 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000395 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
396 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000397 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000398 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100399 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100400 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600401 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100402
Vladimir Marko60584552015-09-03 13:35:12 +0000403 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100404 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100405 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100406 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100407 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100408 }
409 }
410 pre_header->AddSuccessor(header);
411 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100412
Artem Serovc73ee372017-07-31 15:08:40 +0100413 OrderLoopHeaderPredecessors(header);
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100414
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100415 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000416 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
417 // Called from DeadBlockElimination. Update SuspendCheck pointer.
418 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100419 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100420}
421
David Brazdilffee3d32015-07-06 11:48:53 +0100422void HGraph::ComputeTryBlockInformation() {
423 // Iterate in reverse post order to propagate try membership information from
424 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100425 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100426 if (block->IsEntryBlock() || block->IsCatchBlock()) {
427 // Catch blocks after simplification have only exceptional predecessors
428 // and hence are never in tries.
429 continue;
430 }
431
432 // Infer try membership from the first predecessor. Having simplified loops,
433 // the first predecessor can never be a back edge and therefore it must have
434 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100435 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100436 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100437 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000438 if (try_entry != nullptr &&
439 (block->GetTryCatchInformation() == nullptr ||
440 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
441 // We are either setting try block membership for the first time or it
442 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100443 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
444 }
David Brazdilffee3d32015-07-06 11:48:53 +0100445 }
446}
447
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100448void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000449// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100450 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000451 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100452 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
453 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
454 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
455 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100456 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000457 if (block->GetSuccessors().size() > 1) {
458 // Only split normal-flow edges. We cannot split exceptional edges as they
459 // are synthesized (approximate real control flow), and we do not need to
460 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000461 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
462 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
463 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100464 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000465 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000466 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
467 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000468 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000469 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100470 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000471 // SplitCriticalEdge could have invalidated the `normal_successors`
472 // ArrayRef. We must re-acquire it.
473 normal_successors = block->GetNormalSuccessors();
474 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
475 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100476 }
477 }
478 }
479 if (block->IsLoopHeader()) {
480 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000481 } else if (!block->IsEntryBlock() &&
482 block->GetFirstInstruction() != nullptr &&
483 block->GetFirstInstruction()->IsSuspendCheck()) {
484 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000485 // a loop got dismantled. Just remove the suspend check.
486 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100487 }
488 }
489}
490
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000491GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100492 // We iterate post order to ensure we visit inner loops before outer loops.
493 // `PopulateRecursive` needs this guarantee to know whether a natural loop
494 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100495 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100496 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100497 if (block->IsCatchBlock()) {
498 // TODO: Dealing with exceptional back edges could be tricky because
499 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000500 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100501 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000502 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100503 }
504 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000505 return kAnalysisSuccess;
506}
507
508void HLoopInformation::Dump(std::ostream& os) {
509 os << "header: " << header_->GetBlockId() << std::endl;
510 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
511 for (HBasicBlock* block : back_edges_) {
512 os << "back edge: " << block->GetBlockId() << std::endl;
513 }
514 for (HBasicBlock* block : header_->GetPredecessors()) {
515 os << "predecessor: " << block->GetBlockId() << std::endl;
516 }
517 for (uint32_t idx : blocks_.Indexes()) {
518 os << " in loop: " << idx << std::endl;
519 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100520}
521
David Brazdil8d5b8b22015-03-24 10:51:52 +0000522void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000523 // New constants are inserted before the SuspendCheck at the bottom of the
524 // entry block. Note that this method can be called from the graph builder and
525 // the entry block therefore may not end with SuspendCheck->Goto yet.
526 HInstruction* insert_before = nullptr;
527
528 HInstruction* gota = entry_block_->GetLastInstruction();
529 if (gota != nullptr && gota->IsGoto()) {
530 HInstruction* suspend_check = gota->GetPrevious();
531 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
532 insert_before = suspend_check;
533 } else {
534 insert_before = gota;
535 }
536 }
537
538 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000539 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000540 } else {
541 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000542 }
543}
544
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600545HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100546 // For simplicity, don't bother reviving the cached null constant if it is
547 // not null and not in a block. Otherwise, we need to clear the instruction
548 // id and/or any invariants the graph is assuming when adding new instructions.
549 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600550 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000551 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000552 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000553 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000554 if (kIsDebugBuild) {
555 ScopedObjectAccess soa(Thread::Current());
556 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
557 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000558 return cached_null_constant_;
559}
560
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100561HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100562 // For simplicity, don't bother reviving the cached current method if it is
563 // not null and not in a block. Otherwise, we need to clear the instruction
564 // id and/or any invariants the graph is assuming when adding new instructions.
565 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700566 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600567 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
568 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100569 if (entry_block_->GetFirstInstruction() == nullptr) {
570 entry_block_->AddInstruction(cached_current_method_);
571 } else {
572 entry_block_->InsertInstructionBefore(
573 cached_current_method_, entry_block_->GetFirstInstruction());
574 }
575 }
576 return cached_current_method_;
577}
578
Igor Murashkind01745e2017-04-05 16:40:31 -0700579const char* HGraph::GetMethodName() const {
580 const DexFile::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
581 return dex_file_.GetMethodName(method_id);
582}
583
584std::string HGraph::PrettyMethod(bool with_signature) const {
585 return dex_file_.PrettyMethod(method_idx_, with_signature);
586}
587
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600588HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000589 switch (type) {
590 case Primitive::Type::kPrimBoolean:
591 DCHECK(IsUint<1>(value));
592 FALLTHROUGH_INTENDED;
593 case Primitive::Type::kPrimByte:
594 case Primitive::Type::kPrimChar:
595 case Primitive::Type::kPrimShort:
596 case Primitive::Type::kPrimInt:
597 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600598 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000599
600 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600601 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000602
603 default:
604 LOG(FATAL) << "Unsupported constant type";
605 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000606 }
David Brazdil46e2a392015-03-16 17:31:52 +0000607}
608
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000609void HGraph::CacheFloatConstant(HFloatConstant* constant) {
610 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
611 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
612 cached_float_constants_.Overwrite(value, constant);
613}
614
615void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
616 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
617 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
618 cached_double_constants_.Overwrite(value, constant);
619}
620
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000621void HLoopInformation::Add(HBasicBlock* block) {
622 blocks_.SetBit(block->GetBlockId());
623}
624
David Brazdil46e2a392015-03-16 17:31:52 +0000625void HLoopInformation::Remove(HBasicBlock* block) {
626 blocks_.ClearBit(block->GetBlockId());
627}
628
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100629void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
630 if (blocks_.IsBitSet(block->GetBlockId())) {
631 return;
632 }
633
634 blocks_.SetBit(block->GetBlockId());
635 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100636 if (block->IsLoopHeader()) {
637 // We're visiting loops in post-order, so inner loops must have been
638 // populated already.
639 DCHECK(block->GetLoopInformation()->IsPopulated());
640 if (block->GetLoopInformation()->IsIrreducible()) {
641 contains_irreducible_loop_ = true;
642 }
643 }
Vladimir Marko60584552015-09-03 13:35:12 +0000644 for (HBasicBlock* predecessor : block->GetPredecessors()) {
645 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100646 }
647}
648
David Brazdilc2e8af92016-04-05 17:15:19 +0100649void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
650 size_t block_id = block->GetBlockId();
651
652 // If `block` is in `finalized`, we know its membership in the loop has been
653 // decided and it does not need to be revisited.
654 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000655 return;
656 }
657
David Brazdilc2e8af92016-04-05 17:15:19 +0100658 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000659 if (block->IsLoopHeader()) {
660 // If we hit a loop header in an irreducible loop, we first check if the
661 // pre header of that loop belongs to the currently analyzed loop. If it does,
662 // then we visit the back edges.
663 // Note that we cannot use GetPreHeader, as the loop may have not been populated
664 // yet.
665 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100666 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000667 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000668 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100669 blocks_.SetBit(block_id);
670 finalized->SetBit(block_id);
671 is_finalized = true;
672
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000673 HLoopInformation* info = block->GetLoopInformation();
674 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100675 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000676 }
677 }
678 } else {
679 // Visit all predecessors. If one predecessor is part of the loop, this
680 // block is also part of this loop.
681 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100682 PopulateIrreducibleRecursive(predecessor, finalized);
683 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000684 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100685 blocks_.SetBit(block_id);
686 finalized->SetBit(block_id);
687 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000688 }
689 }
690 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100691
692 // All predecessors have been recursively visited. Mark finalized if not marked yet.
693 if (!is_finalized) {
694 finalized->SetBit(block_id);
695 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000696}
697
698void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100699 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000700 // Populate this loop: starting with the back edge, recursively add predecessors
701 // that are not already part of that loop. Set the header as part of the loop
702 // to end the recursion.
703 // This is a recursive implementation of the algorithm described in
704 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100705 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000706 blocks_.SetBit(header_->GetBlockId());
707 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100708
David Brazdil3f4a5222016-05-06 12:46:21 +0100709 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100710
711 if (is_irreducible_loop) {
712 ArenaBitVector visited(graph->GetArena(),
713 graph->GetBlocks().size(),
714 /* expandable */ false,
715 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100716 // Stop marking blocks at the loop header.
717 visited.SetBit(header_->GetBlockId());
718
David Brazdilc2e8af92016-04-05 17:15:19 +0100719 for (HBasicBlock* back_edge : GetBackEdges()) {
720 PopulateIrreducibleRecursive(back_edge, &visited);
721 }
722 } else {
723 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000724 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100725 }
David Brazdila4b8c212015-05-07 09:59:30 +0100726 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100727
Vladimir Markofd66c502016-04-18 15:37:01 +0100728 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
729 // When compiling in OSR mode, all loops in the compiled method may be entered
730 // from the interpreter. We treat this OSR entry point just like an extra entry
731 // to an irreducible loop, so we need to mark the method's loops as irreducible.
732 // This does not apply to inlined loops which do not act as OSR entry points.
733 if (suspend_check_ == nullptr) {
734 // Just building the graph in OSR mode, this loop is not inlined. We never build an
735 // inner graph in OSR mode as we can do OSR transition only from the outer method.
736 is_irreducible_loop = true;
737 } else {
738 // Look at the suspend check's environment to determine if the loop was inlined.
739 DCHECK(suspend_check_->HasEnvironment());
740 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
741 is_irreducible_loop = true;
742 }
743 }
744 }
745 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100746 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100747 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100748 graph->SetHasIrreducibleLoops(true);
749 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800750 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +0100751}
752
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100753HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000754 HBasicBlock* block = header_->GetPredecessors()[0];
755 DCHECK(irreducible_ || (block == header_->GetDominator()));
756 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100757}
758
759bool HLoopInformation::Contains(const HBasicBlock& block) const {
760 return blocks_.IsBitSet(block.GetBlockId());
761}
762
763bool HLoopInformation::IsIn(const HLoopInformation& other) const {
764 return other.blocks_.IsBitSet(header_->GetBlockId());
765}
766
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800767bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
768 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700769}
770
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100771size_t HLoopInformation::GetLifetimeEnd() const {
772 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100773 for (HBasicBlock* back_edge : GetBackEdges()) {
774 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100775 }
776 return last_position;
777}
778
David Brazdil3f4a5222016-05-06 12:46:21 +0100779bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
780 for (HBasicBlock* back_edge : GetBackEdges()) {
781 DCHECK(back_edge->GetDominator() != nullptr);
782 if (!header_->Dominates(back_edge)) {
783 return true;
784 }
785 }
786 return false;
787}
788
Anton Shaminf89381f2016-05-16 16:44:13 +0600789bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
790 for (HBasicBlock* back_edge : GetBackEdges()) {
791 if (!block->Dominates(back_edge)) {
792 return false;
793 }
794 }
795 return true;
796}
797
David Sehrc757dec2016-11-04 15:48:34 -0700798
799bool HLoopInformation::HasExitEdge() const {
800 // Determine if this loop has at least one exit edge.
801 HBlocksInLoopReversePostOrderIterator it_loop(*this);
802 for (; !it_loop.Done(); it_loop.Advance()) {
803 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
804 if (!Contains(*successor)) {
805 return true;
806 }
807 }
808 }
809 return false;
810}
811
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100812bool HBasicBlock::Dominates(HBasicBlock* other) const {
813 // Walk up the dominator tree from `other`, to find out if `this`
814 // is an ancestor.
815 HBasicBlock* current = other;
816 while (current != nullptr) {
817 if (current == this) {
818 return true;
819 }
820 current = current->GetDominator();
821 }
822 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100823}
824
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100825static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100826 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100827 for (size_t i = 0; i < inputs.size(); ++i) {
828 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100829 }
830 // Environment should be created later.
831 DCHECK(!instruction->HasEnvironment());
832}
833
Roland Levillainccc07a92014-09-16 14:48:16 +0100834void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
835 HInstruction* replacement) {
836 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400837 if (initial->IsControlFlow()) {
838 // We can only replace a control flow instruction with another control flow instruction.
839 DCHECK(replacement->IsControlFlow());
840 DCHECK_EQ(replacement->GetId(), -1);
841 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
842 DCHECK_EQ(initial->GetBlock(), this);
843 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100844 DCHECK(initial->GetUses().empty());
845 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400846 replacement->SetBlock(this);
847 replacement->SetId(GetGraph()->GetNextInstructionId());
848 instructions_.InsertInstructionBefore(replacement, initial);
849 UpdateInputsUsers(replacement);
850 } else {
851 InsertInstructionBefore(replacement, initial);
852 initial->ReplaceWith(replacement);
853 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100854 RemoveInstruction(initial);
855}
856
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100857static void Add(HInstructionList* instruction_list,
858 HBasicBlock* block,
859 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000860 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000861 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100862 instruction->SetBlock(block);
863 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100864 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100865 instruction_list->AddInstruction(instruction);
866}
867
868void HBasicBlock::AddInstruction(HInstruction* instruction) {
869 Add(&instructions_, this, instruction);
870}
871
872void HBasicBlock::AddPhi(HPhi* phi) {
873 Add(&phis_, this, phi);
874}
875
David Brazdilc3d743f2015-04-22 13:40:50 +0100876void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
877 DCHECK(!cursor->IsPhi());
878 DCHECK(!instruction->IsPhi());
879 DCHECK_EQ(instruction->GetId(), -1);
880 DCHECK_NE(cursor->GetId(), -1);
881 DCHECK_EQ(cursor->GetBlock(), this);
882 DCHECK(!instruction->IsControlFlow());
883 instruction->SetBlock(this);
884 instruction->SetId(GetGraph()->GetNextInstructionId());
885 UpdateInputsUsers(instruction);
886 instructions_.InsertInstructionBefore(instruction, cursor);
887}
888
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100889void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
890 DCHECK(!cursor->IsPhi());
891 DCHECK(!instruction->IsPhi());
892 DCHECK_EQ(instruction->GetId(), -1);
893 DCHECK_NE(cursor->GetId(), -1);
894 DCHECK_EQ(cursor->GetBlock(), this);
895 DCHECK(!instruction->IsControlFlow());
896 DCHECK(!cursor->IsControlFlow());
897 instruction->SetBlock(this);
898 instruction->SetId(GetGraph()->GetNextInstructionId());
899 UpdateInputsUsers(instruction);
900 instructions_.InsertInstructionAfter(instruction, cursor);
901}
902
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100903void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
904 DCHECK_EQ(phi->GetId(), -1);
905 DCHECK_NE(cursor->GetId(), -1);
906 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100907 phi->SetBlock(this);
908 phi->SetId(GetGraph()->GetNextInstructionId());
909 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100910 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100911}
912
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100913static void Remove(HInstructionList* instruction_list,
914 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000915 HInstruction* instruction,
916 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100917 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100918 instruction->SetBlock(nullptr);
919 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000920 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100921 DCHECK(instruction->GetUses().empty());
922 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000923 RemoveAsUser(instruction);
924 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100925}
926
David Brazdil1abb4192015-02-17 18:33:36 +0000927void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100928 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000929 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100930}
931
David Brazdil1abb4192015-02-17 18:33:36 +0000932void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
933 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100934}
935
David Brazdilc7508e92015-04-27 13:28:57 +0100936void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
937 if (instruction->IsPhi()) {
938 RemovePhi(instruction->AsPhi(), ensure_safety);
939 } else {
940 RemoveInstruction(instruction, ensure_safety);
941 }
942}
943
Vladimir Marko71bf8092015-09-15 15:33:14 +0100944void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
945 for (size_t i = 0; i < locals.size(); i++) {
946 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100947 SetRawEnvAt(i, instruction);
948 if (instruction != nullptr) {
949 instruction->AddEnvUseAt(this, i);
950 }
951 }
952}
953
David Brazdiled596192015-01-23 10:39:45 +0000954void HEnvironment::CopyFrom(HEnvironment* env) {
955 for (size_t i = 0; i < env->Size(); i++) {
956 HInstruction* instruction = env->GetInstructionAt(i);
957 SetRawEnvAt(i, instruction);
958 if (instruction != nullptr) {
959 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100960 }
David Brazdiled596192015-01-23 10:39:45 +0000961 }
962}
963
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700964void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
965 HBasicBlock* loop_header) {
966 DCHECK(loop_header->IsLoopHeader());
967 for (size_t i = 0; i < env->Size(); i++) {
968 HInstruction* instruction = env->GetInstructionAt(i);
969 SetRawEnvAt(i, instruction);
970 if (instruction == nullptr) {
971 continue;
972 }
973 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
974 // At the end of the loop pre-header, the corresponding value for instruction
975 // is the first input of the phi.
976 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700977 SetRawEnvAt(i, initial);
978 initial->AddEnvUseAt(this, i);
979 } else {
980 instruction->AddEnvUseAt(this, i);
981 }
982 }
983}
984
David Brazdil1abb4192015-02-17 18:33:36 +0000985void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100986 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
987 HInstruction* user = env_use.GetInstruction();
988 auto before_env_use_node = env_use.GetBeforeUseNode();
989 user->env_uses_.erase_after(before_env_use_node);
990 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100991}
992
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000993HInstruction::InstructionKind HInstruction::GetKind() const {
994 return GetKindInternal();
995}
996
Calin Juravle77520bc2015-01-12 18:45:46 +0000997HInstruction* HInstruction::GetNextDisregardingMoves() const {
998 HInstruction* next = GetNext();
999 while (next != nullptr && next->IsParallelMove()) {
1000 next = next->GetNext();
1001 }
1002 return next;
1003}
1004
1005HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
1006 HInstruction* previous = GetPrevious();
1007 while (previous != nullptr && previous->IsParallelMove()) {
1008 previous = previous->GetPrevious();
1009 }
1010 return previous;
1011}
1012
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001013void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001014 if (first_instruction_ == nullptr) {
1015 DCHECK(last_instruction_ == nullptr);
1016 first_instruction_ = last_instruction_ = instruction;
1017 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001018 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001019 last_instruction_->next_ = instruction;
1020 instruction->previous_ = last_instruction_;
1021 last_instruction_ = instruction;
1022 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001023}
1024
David Brazdilc3d743f2015-04-22 13:40:50 +01001025void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1026 DCHECK(Contains(cursor));
1027 if (cursor == first_instruction_) {
1028 cursor->previous_ = instruction;
1029 instruction->next_ = cursor;
1030 first_instruction_ = instruction;
1031 } else {
1032 instruction->previous_ = cursor->previous_;
1033 instruction->next_ = cursor;
1034 cursor->previous_ = instruction;
1035 instruction->previous_->next_ = instruction;
1036 }
1037}
1038
1039void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1040 DCHECK(Contains(cursor));
1041 if (cursor == last_instruction_) {
1042 cursor->next_ = instruction;
1043 instruction->previous_ = cursor;
1044 last_instruction_ = instruction;
1045 } else {
1046 instruction->next_ = cursor->next_;
1047 instruction->previous_ = cursor;
1048 cursor->next_ = instruction;
1049 instruction->next_->previous_ = instruction;
1050 }
1051}
1052
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001053void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1054 if (instruction->previous_ != nullptr) {
1055 instruction->previous_->next_ = instruction->next_;
1056 }
1057 if (instruction->next_ != nullptr) {
1058 instruction->next_->previous_ = instruction->previous_;
1059 }
1060 if (instruction == first_instruction_) {
1061 first_instruction_ = instruction->next_;
1062 }
1063 if (instruction == last_instruction_) {
1064 last_instruction_ = instruction->previous_;
1065 }
1066}
1067
Roland Levillain6b469232014-09-25 10:10:38 +01001068bool HInstructionList::Contains(HInstruction* instruction) const {
1069 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1070 if (it.Current() == instruction) {
1071 return true;
1072 }
1073 }
1074 return false;
1075}
1076
Roland Levillainccc07a92014-09-16 14:48:16 +01001077bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1078 const HInstruction* instruction2) const {
1079 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1080 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1081 if (it.Current() == instruction1) {
1082 return true;
1083 }
1084 if (it.Current() == instruction2) {
1085 return false;
1086 }
1087 }
1088 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1089 return true;
1090}
1091
Roland Levillain6c82d402014-10-13 16:10:27 +01001092bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1093 if (other_instruction == this) {
1094 // An instruction does not strictly dominate itself.
1095 return false;
1096 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001097 HBasicBlock* block = GetBlock();
1098 HBasicBlock* other_block = other_instruction->GetBlock();
1099 if (block != other_block) {
1100 return GetBlock()->Dominates(other_instruction->GetBlock());
1101 } else {
1102 // If both instructions are in the same block, ensure this
1103 // instruction comes before `other_instruction`.
1104 if (IsPhi()) {
1105 if (!other_instruction->IsPhi()) {
1106 // Phis appear before non phi-instructions so this instruction
1107 // dominates `other_instruction`.
1108 return true;
1109 } else {
1110 // There is no order among phis.
1111 LOG(FATAL) << "There is no dominance between phis of a same block.";
1112 return false;
1113 }
1114 } else {
1115 // `this` is not a phi.
1116 if (other_instruction->IsPhi()) {
1117 // Phis appear before non phi-instructions so this instruction
1118 // does not dominate `other_instruction`.
1119 return false;
1120 } else {
1121 // Check whether this instruction comes before
1122 // `other_instruction` in the instruction list.
1123 return block->GetInstructions().FoundBefore(this, other_instruction);
1124 }
1125 }
1126 }
1127}
1128
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001129void HInstruction::RemoveEnvironment() {
1130 RemoveEnvironmentUses(this);
1131 environment_ = nullptr;
1132}
1133
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001134void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001135 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001136 // Note: fixup_end remains valid across splice_after().
1137 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1138 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1139 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001140
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001141 // Note: env_fixup_end remains valid across splice_after().
1142 auto env_fixup_end =
1143 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1144 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1145 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001146
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001147 DCHECK(uses_.empty());
1148 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001149}
1150
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001151void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1152 const HUseList<HInstruction*>& uses = GetUses();
1153 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1154 HInstruction* user = it->GetUser();
1155 size_t index = it->GetIndex();
1156 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1157 ++it;
1158 if (dominator->StrictlyDominates(user)) {
1159 user->ReplaceInput(replacement, index);
1160 }
1161 }
1162}
1163
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001164void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001165 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001166 if (input_use.GetInstruction() == replacement) {
1167 // Nothing to do.
1168 return;
1169 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001170 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001171 // Note: fixup_end remains valid across splice_after().
1172 auto fixup_end =
1173 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1174 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1175 input_use.GetInstruction()->uses_,
1176 before_use_node);
1177 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1178 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001179}
1180
Nicolas Geoffray39468442014-09-02 15:17:15 +01001181size_t HInstruction::EnvironmentSize() const {
1182 return HasEnvironment() ? environment_->Size() : 0;
1183}
1184
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001185void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001186 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001187 inputs_.push_back(HUserRecord<HInstruction*>(input));
1188 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001189}
1190
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001191void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1192 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1193 input->AddUseAt(this, index);
1194 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1195 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1196 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1197 inputs_[i].GetUseNode()->SetIndex(i);
1198 }
1199}
1200
1201void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001202 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001203 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001204 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1205 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1206 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1207 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001208 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001209}
1210
Igor Murashkind01745e2017-04-05 16:40:31 -07001211void HVariableInputSizeInstruction::RemoveAllInputs() {
1212 RemoveAsUserOfAllInputs();
1213 DCHECK(!HasNonEnvironmentUses());
1214
1215 inputs_.clear();
1216 DCHECK_EQ(0u, InputCount());
1217}
1218
Igor Murashkin6ef45672017-08-08 13:59:55 -07001219size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001220 DCHECK(instruction->GetBlock() != nullptr);
1221 // Removing constructor fences only makes sense for instructions with an object return type.
1222 DCHECK_EQ(Primitive::kPrimNot, instruction->GetType());
1223
Igor Murashkin6ef45672017-08-08 13:59:55 -07001224 // Return how many instructions were removed for statistic purposes.
1225 size_t remove_count = 0;
1226
Igor Murashkind01745e2017-04-05 16:40:31 -07001227 // Efficient implementation that simultaneously (in one pass):
1228 // * Scans the uses list for all constructor fences.
1229 // * Deletes that constructor fence from the uses list of `instruction`.
1230 // * Deletes `instruction` from the constructor fence's inputs.
1231 // * Deletes the constructor fence if it now has 0 inputs.
1232
1233 const HUseList<HInstruction*>& uses = instruction->GetUses();
1234 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1235 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1236 const HUseListNode<HInstruction*>& use_node = *it;
1237 HInstruction* const use_instruction = use_node.GetUser();
1238
1239 // Advance the iterator immediately once we fetch the use_node.
1240 // Warning: If the input is removed, the current iterator becomes invalid.
1241 ++it;
1242
1243 if (use_instruction->IsConstructorFence()) {
1244 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1245 size_t input_index = use_node.GetIndex();
1246
1247 // Process the candidate instruction for removal
1248 // from the graph.
1249
1250 // Constructor fence instructions are never
1251 // used by other instructions.
1252 //
1253 // If we wanted to make this more generic, it
1254 // could be a runtime if statement.
1255 DCHECK(!ctor_fence->HasUses());
1256
1257 // A constructor fence's return type is "kPrimVoid"
1258 // and therefore it can't have any environment uses.
1259 DCHECK(!ctor_fence->HasEnvironmentUses());
1260
1261 // Remove the inputs first, otherwise removing the instruction
1262 // will try to remove its uses while we are already removing uses
1263 // and this operation will fail.
1264 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1265
1266 // Removing the input will also remove the `use_node`.
1267 // (Do not look at `use_node` after this, it will be a dangling reference).
1268 ctor_fence->RemoveInputAt(input_index);
1269
1270 // Once all inputs are removed, the fence is considered dead and
1271 // is removed.
1272 if (ctor_fence->InputCount() == 0u) {
1273 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
Igor Murashkin6ef45672017-08-08 13:59:55 -07001274 ++remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001275 }
1276 }
1277 }
1278
1279 if (kIsDebugBuild) {
1280 // Post-condition checks:
1281 // * None of the uses of `instruction` are a constructor fence.
1282 // * The `instruction` itself did not get removed from a block.
1283 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1284 CHECK(!use_node.GetUser()->IsConstructorFence());
1285 }
1286 CHECK(instruction->GetBlock() != nullptr);
1287 }
Igor Murashkin6ef45672017-08-08 13:59:55 -07001288
1289 return remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001290}
1291
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001292HInstruction* HConstructorFence::GetAssociatedAllocation() {
1293 HInstruction* new_instance_inst = GetPrevious();
1294 // Check if the immediately preceding instruction is a new-instance/new-array.
1295 // Otherwise this fence is for protecting final fields.
1296 if (new_instance_inst != nullptr &&
1297 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
1298 // TODO: Need to update this code to handle multiple inputs.
1299 DCHECK_EQ(InputCount(), 1u);
1300 return new_instance_inst;
1301 } else {
1302 return nullptr;
1303 }
1304}
1305
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001306#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001307void H##name::Accept(HGraphVisitor* visitor) { \
1308 visitor->Visit##name(this); \
1309}
1310
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001311FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001312
1313#undef DEFINE_ACCEPT
1314
1315void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001316 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1317 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001318 if (block != nullptr) {
1319 VisitBasicBlock(block);
1320 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001321 }
1322}
1323
Roland Levillain633021e2014-10-01 14:12:25 +01001324void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001325 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1326 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001327 }
1328}
1329
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001330void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001331 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001332 it.Current()->Accept(this);
1333 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001334 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001335 it.Current()->Accept(this);
1336 }
1337}
1338
Mark Mendelle82549b2015-05-06 10:55:34 -04001339HConstant* HTypeConversion::TryStaticEvaluation() const {
1340 HGraph* graph = GetBlock()->GetGraph();
1341 if (GetInput()->IsIntConstant()) {
1342 int32_t value = GetInput()->AsIntConstant()->GetValue();
1343 switch (GetResultType()) {
1344 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001345 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001346 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001347 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001348 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001349 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001350 default:
1351 return nullptr;
1352 }
1353 } else if (GetInput()->IsLongConstant()) {
1354 int64_t value = GetInput()->AsLongConstant()->GetValue();
1355 switch (GetResultType()) {
1356 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001357 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001358 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001359 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001360 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001361 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001362 default:
1363 return nullptr;
1364 }
1365 } else if (GetInput()->IsFloatConstant()) {
1366 float value = GetInput()->AsFloatConstant()->GetValue();
1367 switch (GetResultType()) {
1368 case Primitive::kPrimInt:
1369 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001370 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001371 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001372 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001373 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001374 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1375 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001376 case Primitive::kPrimLong:
1377 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001378 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001379 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001380 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001381 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001382 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1383 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001384 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001385 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001386 default:
1387 return nullptr;
1388 }
1389 } else if (GetInput()->IsDoubleConstant()) {
1390 double value = GetInput()->AsDoubleConstant()->GetValue();
1391 switch (GetResultType()) {
1392 case Primitive::kPrimInt:
1393 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001394 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001395 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001396 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001397 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001398 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1399 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001400 case Primitive::kPrimLong:
1401 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001402 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001403 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001404 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001405 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001406 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1407 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001408 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001409 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001410 default:
1411 return nullptr;
1412 }
1413 }
1414 return nullptr;
1415}
1416
Roland Levillain9240d6a2014-10-20 16:47:04 +01001417HConstant* HUnaryOperation::TryStaticEvaluation() const {
1418 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001419 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001420 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001421 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001422 } else if (kEnableFloatingPointStaticEvaluation) {
1423 if (GetInput()->IsFloatConstant()) {
1424 return Evaluate(GetInput()->AsFloatConstant());
1425 } else if (GetInput()->IsDoubleConstant()) {
1426 return Evaluate(GetInput()->AsDoubleConstant());
1427 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001428 }
1429 return nullptr;
1430}
1431
1432HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001433 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1434 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001435 } else if (GetLeft()->IsLongConstant()) {
1436 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001437 // The binop(long, int) case is only valid for shifts and rotations.
1438 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001439 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1440 } else if (GetRight()->IsLongConstant()) {
1441 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001442 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001443 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001444 // The binop(null, null) case is only valid for equal and not-equal conditions.
1445 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001446 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001447 } else if (kEnableFloatingPointStaticEvaluation) {
1448 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1449 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1450 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1451 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1452 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001453 }
1454 return nullptr;
1455}
Dave Allison20dfc792014-06-16 20:44:29 -07001456
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001457HConstant* HBinaryOperation::GetConstantRight() const {
1458 if (GetRight()->IsConstant()) {
1459 return GetRight()->AsConstant();
1460 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1461 return GetLeft()->AsConstant();
1462 } else {
1463 return nullptr;
1464 }
1465}
1466
1467// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001468// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001469HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1470 HInstruction* most_constant_right = GetConstantRight();
1471 if (most_constant_right == nullptr) {
1472 return nullptr;
1473 } else if (most_constant_right == GetLeft()) {
1474 return GetRight();
1475 } else {
1476 return GetLeft();
1477 }
1478}
1479
Roland Levillain31dd3d62016-02-16 12:21:02 +00001480std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1481 switch (rhs) {
1482 case ComparisonBias::kNoBias:
1483 return os << "no_bias";
1484 case ComparisonBias::kGtBias:
1485 return os << "gt_bias";
1486 case ComparisonBias::kLtBias:
1487 return os << "lt_bias";
1488 default:
1489 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1490 UNREACHABLE();
1491 }
1492}
1493
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001494bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1495 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001496}
1497
Vladimir Marko372f10e2016-05-17 16:30:10 +01001498bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001499 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001500 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001501 if (!InstructionDataEquals(other)) return false;
1502 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001503 HConstInputsRef inputs = GetInputs();
1504 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001505 if (inputs.size() != other_inputs.size()) return false;
1506 for (size_t i = 0; i != inputs.size(); ++i) {
1507 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001508 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001509
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001510 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001511 return true;
1512}
1513
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001514std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1515#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1516 switch (rhs) {
1517 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1518 default:
1519 os << "Unknown instruction kind " << static_cast<int>(rhs);
1520 break;
1521 }
1522#undef DECLARE_CASE
1523 return os;
1524}
1525
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001526void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1527 if (do_checks) {
1528 DCHECK(!IsPhi());
1529 DCHECK(!IsControlFlow());
1530 DCHECK(CanBeMoved() ||
1531 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1532 IsShouldDeoptimizeFlag());
1533 DCHECK(!cursor->IsPhi());
1534 }
David Brazdild6c205e2016-06-07 14:20:52 +01001535
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001536 next_->previous_ = previous_;
1537 if (previous_ != nullptr) {
1538 previous_->next_ = next_;
1539 }
1540 if (block_->instructions_.first_instruction_ == this) {
1541 block_->instructions_.first_instruction_ = next_;
1542 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001543 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001544
1545 previous_ = cursor->previous_;
1546 if (previous_ != nullptr) {
1547 previous_->next_ = this;
1548 }
1549 next_ = cursor;
1550 cursor->previous_ = this;
1551 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001552
1553 if (block_->instructions_.first_instruction_ == cursor) {
1554 block_->instructions_.first_instruction_ = this;
1555 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001556}
1557
Vladimir Markofb337ea2015-11-25 15:25:10 +00001558void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1559 DCHECK(!CanThrow());
1560 DCHECK(!HasSideEffects());
1561 DCHECK(!HasEnvironmentUses());
1562 DCHECK(HasNonEnvironmentUses());
1563 DCHECK(!IsPhi()); // Makes no sense for Phi.
1564 DCHECK_EQ(InputCount(), 0u);
1565
1566 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001567 auto uses_it = GetUses().begin();
1568 auto uses_end = GetUses().end();
1569 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1570 ++uses_it;
1571 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1572 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001573 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001574 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001575 // This instruction has uses in two or more blocks. Find the common dominator.
1576 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001577 for (; uses_it != uses_end; ++uses_it) {
1578 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001579 }
1580 target_block = finder.Get();
1581 DCHECK(target_block != nullptr);
1582 }
1583 // Move to the first dominator not in a loop.
1584 while (target_block->IsInLoop()) {
1585 target_block = target_block->GetDominator();
1586 DCHECK(target_block != nullptr);
1587 }
1588
1589 // Find insertion position.
1590 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001591 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1592 if (use.GetUser()->GetBlock() == target_block &&
1593 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1594 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001595 }
1596 }
1597 if (insert_pos == nullptr) {
1598 // No user in `target_block`, insert before the control flow instruction.
1599 insert_pos = target_block->GetLastInstruction();
1600 DCHECK(insert_pos->IsControlFlow());
1601 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1602 if (insert_pos->IsIf()) {
1603 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1604 if (if_input == insert_pos->GetPrevious()) {
1605 insert_pos = if_input;
1606 }
1607 }
1608 }
1609 MoveBefore(insert_pos);
1610}
1611
David Brazdilfc6a86a2015-06-26 10:33:45 +00001612HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001613 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001614 DCHECK_EQ(cursor->GetBlock(), this);
1615
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001616 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1617 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001618 new_block->instructions_.first_instruction_ = cursor;
1619 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1620 instructions_.last_instruction_ = cursor->previous_;
1621 if (cursor->previous_ == nullptr) {
1622 instructions_.first_instruction_ = nullptr;
1623 } else {
1624 cursor->previous_->next_ = nullptr;
1625 cursor->previous_ = nullptr;
1626 }
1627
1628 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001629 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001630
Vladimir Marko60584552015-09-03 13:35:12 +00001631 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001632 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001633 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001634 new_block->successors_.swap(successors_);
1635 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001636 AddSuccessor(new_block);
1637
David Brazdil56e1acc2015-06-30 15:41:36 +01001638 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001639 return new_block;
1640}
1641
David Brazdild7558da2015-09-22 13:04:14 +01001642HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001643 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001644 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1645
1646 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1647
1648 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001649 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1650 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001651 new_block->predecessors_.swap(predecessors_);
1652 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001653 AddPredecessor(new_block);
1654
1655 GetGraph()->AddBlock(new_block);
1656 return new_block;
1657}
1658
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001659HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1660 DCHECK_EQ(cursor->GetBlock(), this);
1661
1662 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1663 cursor->GetDexPc());
1664 new_block->instructions_.first_instruction_ = cursor;
1665 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1666 instructions_.last_instruction_ = cursor->previous_;
1667 if (cursor->previous_ == nullptr) {
1668 instructions_.first_instruction_ = nullptr;
1669 } else {
1670 cursor->previous_->next_ = nullptr;
1671 cursor->previous_ = nullptr;
1672 }
1673
1674 new_block->instructions_.SetBlockOfInstructions(new_block);
1675
1676 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001677 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1678 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001679 new_block->successors_.swap(successors_);
1680 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001681
1682 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1683 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001684 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001685 new_block->dominated_blocks_.swap(dominated_blocks_);
1686 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001687 return new_block;
1688}
1689
1690HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001691 DCHECK(!cursor->IsControlFlow());
1692 DCHECK_NE(instructions_.last_instruction_, cursor);
1693 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001694
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001695 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1696 new_block->instructions_.first_instruction_ = cursor->GetNext();
1697 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1698 cursor->next_->previous_ = nullptr;
1699 cursor->next_ = nullptr;
1700 instructions_.last_instruction_ = cursor;
1701
1702 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001703 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001704 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001705 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001706 new_block->successors_.swap(successors_);
1707 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001708
Vladimir Marko60584552015-09-03 13:35:12 +00001709 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001710 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001711 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001712 new_block->dominated_blocks_.swap(dominated_blocks_);
1713 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001714 return new_block;
1715}
1716
David Brazdilec16f792015-08-19 15:04:01 +01001717const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001718 if (EndsWithTryBoundary()) {
1719 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1720 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001721 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001722 return try_boundary;
1723 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001724 DCHECK(IsTryBlock());
1725 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001726 return nullptr;
1727 }
David Brazdilec16f792015-08-19 15:04:01 +01001728 } else if (IsTryBlock()) {
1729 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001730 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001731 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001732 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001733}
1734
David Brazdild7558da2015-09-22 13:04:14 +01001735bool HBasicBlock::HasThrowingInstructions() const {
1736 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1737 if (it.Current()->CanThrow()) {
1738 return true;
1739 }
1740 }
1741 return false;
1742}
1743
David Brazdilfc6a86a2015-06-26 10:33:45 +00001744static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1745 return block.GetPhis().IsEmpty()
1746 && !block.GetInstructions().IsEmpty()
1747 && block.GetFirstInstruction() == block.GetLastInstruction();
1748}
1749
David Brazdil46e2a392015-03-16 17:31:52 +00001750bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001751 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1752}
1753
Mads Ager16e52892017-07-14 13:11:37 +02001754bool HBasicBlock::IsSingleReturn() const {
1755 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsReturn();
1756}
1757
David Brazdilfc6a86a2015-06-26 10:33:45 +00001758bool HBasicBlock::IsSingleTryBoundary() const {
1759 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001760}
1761
David Brazdil8d5b8b22015-03-24 10:51:52 +00001762bool HBasicBlock::EndsWithControlFlowInstruction() const {
1763 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1764}
1765
David Brazdilb2bd1c52015-03-25 11:17:37 +00001766bool HBasicBlock::EndsWithIf() const {
1767 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1768}
1769
David Brazdilffee3d32015-07-06 11:48:53 +01001770bool HBasicBlock::EndsWithTryBoundary() const {
1771 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1772}
1773
David Brazdilb2bd1c52015-03-25 11:17:37 +00001774bool HBasicBlock::HasSinglePhi() const {
1775 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1776}
1777
David Brazdild26a4112015-11-10 11:07:31 +00001778ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1779 if (EndsWithTryBoundary()) {
1780 // The normal-flow successor of HTryBoundary is always stored at index zero.
1781 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1782 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1783 } else {
1784 // All successors of blocks not ending with TryBoundary are normal.
1785 return ArrayRef<HBasicBlock* const>(successors_);
1786 }
1787}
1788
1789ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1790 if (EndsWithTryBoundary()) {
1791 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1792 } else {
1793 // Blocks not ending with TryBoundary do not have exceptional successors.
1794 return ArrayRef<HBasicBlock* const>();
1795 }
1796}
1797
David Brazdilffee3d32015-07-06 11:48:53 +01001798bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001799 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1800 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1801
1802 size_t length = handlers1.size();
1803 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001804 return false;
1805 }
1806
David Brazdilb618ade2015-07-29 10:31:29 +01001807 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001808 for (size_t i = 0; i < length; ++i) {
1809 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001810 return false;
1811 }
1812 }
1813 return true;
1814}
1815
David Brazdil2d7352b2015-04-20 14:52:42 +01001816size_t HInstructionList::CountSize() const {
1817 size_t size = 0;
1818 HInstruction* current = first_instruction_;
1819 for (; current != nullptr; current = current->GetNext()) {
1820 size++;
1821 }
1822 return size;
1823}
1824
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001825void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1826 for (HInstruction* current = first_instruction_;
1827 current != nullptr;
1828 current = current->GetNext()) {
1829 current->SetBlock(block);
1830 }
1831}
1832
1833void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1834 DCHECK(Contains(cursor));
1835 if (!instruction_list.IsEmpty()) {
1836 if (cursor == last_instruction_) {
1837 last_instruction_ = instruction_list.last_instruction_;
1838 } else {
1839 cursor->next_->previous_ = instruction_list.last_instruction_;
1840 }
1841 instruction_list.last_instruction_->next_ = cursor->next_;
1842 cursor->next_ = instruction_list.first_instruction_;
1843 instruction_list.first_instruction_->previous_ = cursor;
1844 }
1845}
1846
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001847void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1848 DCHECK(Contains(cursor));
1849 if (!instruction_list.IsEmpty()) {
1850 if (cursor == first_instruction_) {
1851 first_instruction_ = instruction_list.first_instruction_;
1852 } else {
1853 cursor->previous_->next_ = instruction_list.first_instruction_;
1854 }
1855 instruction_list.last_instruction_->next_ = cursor;
1856 instruction_list.first_instruction_->previous_ = cursor->previous_;
1857 cursor->previous_ = instruction_list.last_instruction_;
1858 }
1859}
1860
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001861void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001862 if (IsEmpty()) {
1863 first_instruction_ = instruction_list.first_instruction_;
1864 last_instruction_ = instruction_list.last_instruction_;
1865 } else {
1866 AddAfter(last_instruction_, instruction_list);
1867 }
1868}
1869
David Brazdil04ff4e82015-12-10 13:54:52 +00001870// Should be called on instructions in a dead block in post order. This method
1871// assumes `insn` has been removed from all users with the exception of catch
1872// phis because of missing exceptional edges in the graph. It removes the
1873// instruction from catch phi uses, together with inputs of other catch phis in
1874// the catch block at the same index, as these must be dead too.
1875static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1876 DCHECK(!insn->HasEnvironmentUses());
1877 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001878 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1879 size_t use_index = use.GetIndex();
1880 HBasicBlock* user_block = use.GetUser()->GetBlock();
1881 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001882 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1883 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1884 }
1885 }
1886}
1887
David Brazdil2d7352b2015-04-20 14:52:42 +01001888void HBasicBlock::DisconnectAndDelete() {
1889 // Dominators must be removed after all the blocks they dominate. This way
1890 // a loop header is removed last, a requirement for correct loop information
1891 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001892 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001893
David Brazdil9eeebf62016-03-24 11:18:15 +00001894 // The following steps gradually remove the block from all its dependants in
1895 // post order (b/27683071).
1896
1897 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1898 // We need to do this before step (4) which destroys the predecessor list.
1899 HBasicBlock* loop_update_start = this;
1900 if (IsLoopHeader()) {
1901 HLoopInformation* loop_info = GetLoopInformation();
1902 // All other blocks in this loop should have been removed because the header
1903 // was their dominator.
1904 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1905 DCHECK(!loop_info->IsIrreducible());
1906 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1907 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1908 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001909 }
1910
David Brazdil9eeebf62016-03-24 11:18:15 +00001911 // (2) Disconnect the block from its successors and update their phis.
1912 for (HBasicBlock* successor : successors_) {
1913 // Delete this block from the list of predecessors.
1914 size_t this_index = successor->GetPredecessorIndexOf(this);
1915 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1916
1917 // Check that `successor` has other predecessors, otherwise `this` is the
1918 // dominator of `successor` which violates the order DCHECKed at the top.
1919 DCHECK(!successor->predecessors_.empty());
1920
1921 // Remove this block's entries in the successor's phis. Skip exceptional
1922 // successors because catch phi inputs do not correspond to predecessor
1923 // blocks but throwing instructions. The inputs of the catch phis will be
1924 // updated in step (3).
1925 if (!successor->IsCatchBlock()) {
1926 if (successor->predecessors_.size() == 1u) {
1927 // The successor has just one predecessor left. Replace phis with the only
1928 // remaining input.
1929 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1930 HPhi* phi = phi_it.Current()->AsPhi();
1931 phi->ReplaceWith(phi->InputAt(1 - this_index));
1932 successor->RemovePhi(phi);
1933 }
1934 } else {
1935 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1936 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1937 }
1938 }
1939 }
1940 }
1941 successors_.clear();
1942
1943 // (3) Remove instructions and phis. Instructions should have no remaining uses
1944 // except in catch phis. If an instruction is used by a catch phi at `index`,
1945 // remove `index`-th input of all phis in the catch block since they are
1946 // guaranteed dead. Note that we may miss dead inputs this way but the
1947 // graph will always remain consistent.
1948 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1949 HInstruction* insn = it.Current();
1950 RemoveUsesOfDeadInstruction(insn);
1951 RemoveInstruction(insn);
1952 }
1953 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1954 HPhi* insn = it.Current()->AsPhi();
1955 RemoveUsesOfDeadInstruction(insn);
1956 RemovePhi(insn);
1957 }
1958
1959 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001960 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001961 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001962 // We should not see any back edges as they would have been removed by step (3).
1963 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1964
David Brazdil2d7352b2015-04-20 14:52:42 +01001965 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001966 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1967 // This block is the only normal-flow successor of the TryBoundary which
1968 // makes `predecessor` dead. Since DCE removes blocks in post order,
1969 // exception handlers of this TryBoundary were already visited and any
1970 // remaining handlers therefore must be live. We remove `predecessor` from
1971 // their list of predecessors.
1972 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1973 while (predecessor->GetSuccessors().size() > 1) {
1974 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1975 DCHECK(handler->IsCatchBlock());
1976 predecessor->RemoveSuccessor(handler);
1977 handler->RemovePredecessor(predecessor);
1978 }
1979 }
1980
David Brazdil2d7352b2015-04-20 14:52:42 +01001981 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001982 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1983 if (num_pred_successors == 1u) {
1984 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001985 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1986 // successor. Replace those with a HGoto.
1987 DCHECK(last_instruction->IsIf() ||
1988 last_instruction->IsPackedSwitch() ||
1989 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001990 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001991 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001992 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001993 // The predecessor has no remaining successors and therefore must be dead.
1994 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001995 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001996 predecessor->RemoveInstruction(last_instruction);
1997 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001998 // There are multiple successors left. The removed block might be a successor
1999 // of a PackedSwitch which will be completely removed (perhaps replaced with
2000 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2001 // case, leave `last_instruction` as is for now.
2002 DCHECK(last_instruction->IsPackedSwitch() ||
2003 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002004 }
David Brazdil46e2a392015-03-16 17:31:52 +00002005 }
Vladimir Marko60584552015-09-03 13:35:12 +00002006 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002007
David Brazdil9eeebf62016-03-24 11:18:15 +00002008 // (5) Remove the block from all loops it is included in. Skip the inner-most
2009 // loop if this is the loop header (see definition of `loop_update_start`)
2010 // because the loop header's predecessor list has been destroyed in step (4).
2011 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2012 HLoopInformation* loop_info = it.Current();
2013 loop_info->Remove(this);
2014 if (loop_info->IsBackEdge(*this)) {
2015 // If this was the last back edge of the loop, we deliberately leave the
2016 // loop in an inconsistent state and will fail GraphChecker unless the
2017 // entire loop is removed during the pass.
2018 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002019 }
2020 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002021
David Brazdil9eeebf62016-03-24 11:18:15 +00002022 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002023 dominator_->RemoveDominatedBlock(this);
2024 SetDominator(nullptr);
2025
David Brazdil9eeebf62016-03-24 11:18:15 +00002026 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002027 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002028 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002029}
2030
Aart Bik6b69e0a2017-01-11 10:20:43 -08002031void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2032 DCHECK(EndsWithControlFlowInstruction());
2033 RemoveInstruction(GetLastInstruction());
2034 instructions_.Add(other->GetInstructions());
2035 other->instructions_.SetBlockOfInstructions(this);
2036 other->instructions_.Clear();
2037}
2038
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002039void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002040 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002041 DCHECK(ContainsElement(dominated_blocks_, other));
2042 DCHECK_EQ(GetSingleSuccessor(), other);
2043 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002044 DCHECK(other->GetPhis().IsEmpty());
2045
David Brazdil2d7352b2015-04-20 14:52:42 +01002046 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002047 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002048
David Brazdil2d7352b2015-04-20 14:52:42 +01002049 // Remove `other` from the loops it is included in.
2050 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2051 HLoopInformation* loop_info = it.Current();
2052 loop_info->Remove(other);
2053 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002054 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002055 }
2056 }
2057
2058 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002059 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002060 for (HBasicBlock* successor : other->GetSuccessors()) {
2061 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002062 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002063 successors_.swap(other->successors_);
2064 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002065
David Brazdil2d7352b2015-04-20 14:52:42 +01002066 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002067 RemoveDominatedBlock(other);
2068 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002069 dominated->SetDominator(this);
2070 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002071 dominated_blocks_.insert(
2072 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002073 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002074 other->dominator_ = nullptr;
2075
2076 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002077 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002078
2079 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002080 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002081 other->SetGraph(nullptr);
2082}
2083
2084void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2085 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002086 DCHECK(GetDominatedBlocks().empty());
2087 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002088 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002089 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002090 DCHECK(other->GetPhis().IsEmpty());
2091 DCHECK(!other->IsInLoop());
2092
2093 // Move instructions from `other` to `this`.
2094 instructions_.Add(other->GetInstructions());
2095 other->instructions_.SetBlockOfInstructions(this);
2096
2097 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002098 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002099 for (HBasicBlock* successor : other->GetSuccessors()) {
2100 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002101 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002102 successors_.swap(other->successors_);
2103 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002104
2105 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002106 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002107 dominated->SetDominator(this);
2108 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002109 dominated_blocks_.insert(
2110 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002111 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002112 other->dominator_ = nullptr;
2113 other->graph_ = nullptr;
2114}
2115
2116void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002117 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002118 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002119 predecessor->ReplaceSuccessor(this, other);
2120 }
Vladimir Marko60584552015-09-03 13:35:12 +00002121 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002122 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002123 successor->ReplacePredecessor(this, other);
2124 }
Vladimir Marko60584552015-09-03 13:35:12 +00002125 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2126 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002127 }
2128 GetDominator()->ReplaceDominatedBlock(this, other);
2129 other->SetDominator(GetDominator());
2130 dominator_ = nullptr;
2131 graph_ = nullptr;
2132}
2133
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002134void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002135 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002136 DCHECK(block->GetSuccessors().empty());
2137 DCHECK(block->GetPredecessors().empty());
2138 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002139 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002140 DCHECK(block->GetInstructions().IsEmpty());
2141 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002142
David Brazdilc7af85d2015-05-26 12:05:55 +01002143 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002144 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002145 }
2146
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002147 RemoveElement(reverse_post_order_, block);
2148 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002149 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002150}
2151
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002152void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2153 HBasicBlock* reference,
2154 bool replace_if_back_edge) {
2155 if (block->IsLoopHeader()) {
2156 // Clear the information of which blocks are contained in that loop. Since the
2157 // information is stored as a bit vector based on block ids, we have to update
2158 // it, as those block ids were specific to the callee graph and we are now adding
2159 // these blocks to the caller graph.
2160 block->GetLoopInformation()->ClearAllBlocks();
2161 }
2162
2163 // If not already in a loop, update the loop information.
2164 if (!block->IsInLoop()) {
2165 block->SetLoopInformation(reference->GetLoopInformation());
2166 }
2167
2168 // If the block is in a loop, update all its outward loops.
2169 HLoopInformation* loop_info = block->GetLoopInformation();
2170 if (loop_info != nullptr) {
2171 for (HLoopInformationOutwardIterator loop_it(*block);
2172 !loop_it.Done();
2173 loop_it.Advance()) {
2174 loop_it.Current()->Add(block);
2175 }
2176 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2177 loop_info->ReplaceBackEdge(reference, block);
2178 }
2179 }
2180
2181 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2182 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2183 ? reference->GetTryCatchInformation()
2184 : nullptr;
2185 block->SetTryCatchInformation(try_catch_info);
2186}
2187
Calin Juravle2e768302015-07-28 14:41:11 +00002188HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002189 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002190 // Update the environments in this graph to have the invoke's environment
2191 // as parent.
2192 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002193 // Skip the entry block, we do not need to update the entry's suspend check.
2194 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002195 for (HInstructionIterator instr_it(block->GetInstructions());
2196 !instr_it.Done();
2197 instr_it.Advance()) {
2198 HInstruction* current = instr_it.Current();
2199 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002200 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002201 current->GetEnvironment()->SetAndCopyParentChain(
2202 outer_graph->GetArena(), invoke->GetEnvironment());
2203 }
2204 }
2205 }
2206 }
2207 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002208
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002209 if (HasBoundsChecks()) {
2210 outer_graph->SetHasBoundsChecks(true);
2211 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002212 if (HasLoops()) {
2213 outer_graph->SetHasLoops(true);
2214 }
2215 if (HasIrreducibleLoops()) {
2216 outer_graph->SetHasIrreducibleLoops(true);
2217 }
2218 if (HasTryCatch()) {
2219 outer_graph->SetHasTryCatch(true);
2220 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002221 if (HasSIMD()) {
2222 outer_graph->SetHasSIMD(true);
2223 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002224
Calin Juravle2e768302015-07-28 14:41:11 +00002225 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002226 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002227 // Inliner already made sure we don't inline methods that always throw.
2228 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002229 // Simple case of an entry block, a body block, and an exit block.
2230 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002231 HBasicBlock* body = GetBlocks()[1];
2232 DCHECK(GetBlocks()[0]->IsEntryBlock());
2233 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002234 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002235 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002236 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002237
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002238 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2239 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002240 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002241
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002242 // Replace the invoke with the return value of the inlined graph.
2243 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002244 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002245 } else {
2246 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002247 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002248
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002249 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002250 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002251 // Need to inline multiple blocks. We split `invoke`'s block
2252 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002253 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002254 // with the second half.
2255 ArenaAllocator* allocator = outer_graph->GetArena();
2256 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002257 // Note that we split before the invoke only to simplify polymorphic inlining.
2258 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002259
Vladimir Markoec7802a2015-10-01 20:57:57 +01002260 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002261 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002262 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002263 exit_block_->ReplaceWith(to);
2264
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002265 // Update the meta information surrounding blocks:
2266 // (1) the graph they are now in,
2267 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002268 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002269 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002270 // Note that we do not need to update catch phi inputs because they
2271 // correspond to the register file of the outer method which the inlinee
2272 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002273
2274 // We don't add the entry block, the exit block, and the first block, which
2275 // has been merged with `at`.
2276 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2277
2278 // We add the `to` block.
2279 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002280 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002281 + kNumberOfNewBlocksInCaller;
2282
2283 // Find the location of `at` in the outer graph's reverse post order. The new
2284 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002285 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002286 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2287
David Brazdil95177982015-10-30 12:56:58 -05002288 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2289 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002290 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002291 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002292 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002293 DCHECK(current->GetGraph() == this);
2294 current->SetGraph(outer_graph);
2295 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002296 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002297 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002298 }
2299 }
2300
David Brazdil95177982015-10-30 12:56:58 -05002301 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002302 to->SetGraph(outer_graph);
2303 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002304 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002305 // Only `to` can become a back edge, as the inlined blocks
2306 // are predecessors of `to`.
2307 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002308
David Brazdil3f523062016-02-29 16:53:33 +00002309 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002310 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2311 // to now get the outer graph exit block as successor. Note that the inliner
2312 // currently doesn't support inlining methods with try/catch.
2313 HPhi* return_value_phi = nullptr;
2314 bool rerun_dominance = false;
2315 bool rerun_loop_analysis = false;
2316 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2317 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002318 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002319 if (last->IsThrow()) {
2320 DCHECK(!at->IsTryBlock());
2321 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2322 --pred;
2323 // We need to re-run dominance information, as the exit block now has
2324 // a new dominator.
2325 rerun_dominance = true;
2326 if (predecessor->GetLoopInformation() != nullptr) {
2327 // The exit block and blocks post dominated by the exit block do not belong
2328 // to any loop. Because we do not compute the post dominators, we need to re-run
2329 // loop analysis to get the loop information correct.
2330 rerun_loop_analysis = true;
2331 }
2332 } else {
2333 if (last->IsReturnVoid()) {
2334 DCHECK(return_value == nullptr);
2335 DCHECK(return_value_phi == nullptr);
2336 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002337 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002338 if (return_value_phi != nullptr) {
2339 return_value_phi->AddInput(last->InputAt(0));
2340 } else if (return_value == nullptr) {
2341 return_value = last->InputAt(0);
2342 } else {
2343 // There will be multiple returns.
2344 return_value_phi = new (allocator) HPhi(
2345 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2346 to->AddPhi(return_value_phi);
2347 return_value_phi->AddInput(return_value);
2348 return_value_phi->AddInput(last->InputAt(0));
2349 return_value = return_value_phi;
2350 }
David Brazdil3f523062016-02-29 16:53:33 +00002351 }
2352 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2353 predecessor->RemoveInstruction(last);
2354 }
2355 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002356 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002357 DCHECK(!outer_graph->HasIrreducibleLoops())
2358 << "Recomputing loop information in graphs with irreducible loops "
2359 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002360 outer_graph->ClearLoopInformation();
2361 outer_graph->ClearDominanceInformation();
2362 outer_graph->BuildDominatorTree();
2363 } else if (rerun_dominance) {
2364 outer_graph->ClearDominanceInformation();
2365 outer_graph->ComputeDominanceInformation();
2366 }
David Brazdil3f523062016-02-29 16:53:33 +00002367 }
David Brazdil05144f42015-04-16 15:18:00 +01002368
2369 // Walk over the entry block and:
2370 // - Move constants from the entry block to the outer_graph's entry block,
2371 // - Replace HParameterValue instructions with their real value.
2372 // - Remove suspend checks, that hold an environment.
2373 // We must do this after the other blocks have been inlined, otherwise ids of
2374 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002375 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002376 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2377 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002378 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002379 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002380 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002381 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002382 replacement = outer_graph->GetIntConstant(
2383 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002384 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002385 replacement = outer_graph->GetLongConstant(
2386 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002387 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002388 replacement = outer_graph->GetFloatConstant(
2389 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002390 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002391 replacement = outer_graph->GetDoubleConstant(
2392 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002393 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002394 if (kIsDebugBuild
2395 && invoke->IsInvokeStaticOrDirect()
2396 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2397 // Ensure we do not use the last input of `invoke`, as it
2398 // contains a clinit check which is not an actual argument.
2399 size_t last_input_index = invoke->InputCount() - 1;
2400 DCHECK(parameter_index != last_input_index);
2401 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002402 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002403 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002404 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002405 } else {
2406 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2407 entry_block_->RemoveInstruction(current);
2408 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002409 if (replacement != nullptr) {
2410 current->ReplaceWith(replacement);
2411 // If the current is the return value then we need to update the latter.
2412 if (current == return_value) {
2413 DCHECK_EQ(entry_block_, return_value->GetBlock());
2414 return_value = replacement;
2415 }
2416 }
2417 }
2418
Calin Juravle2e768302015-07-28 14:41:11 +00002419 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002420}
2421
Mingyao Yang3584bce2015-05-19 16:01:59 -07002422/*
2423 * Loop will be transformed to:
2424 * old_pre_header
2425 * |
2426 * if_block
2427 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002428 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002429 * \ /
2430 * new_pre_header
2431 * |
2432 * header
2433 */
2434void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2435 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002436 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002437
Aart Bik3fc7f352015-11-20 22:03:03 -08002438 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002439 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002440 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2441 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002442 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2443 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002444 AddBlock(true_block);
2445 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002446 AddBlock(new_pre_header);
2447
Aart Bik3fc7f352015-11-20 22:03:03 -08002448 header->ReplacePredecessor(old_pre_header, new_pre_header);
2449 old_pre_header->successors_.clear();
2450 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002451
Aart Bik3fc7f352015-11-20 22:03:03 -08002452 old_pre_header->AddSuccessor(if_block);
2453 if_block->AddSuccessor(true_block); // True successor
2454 if_block->AddSuccessor(false_block); // False successor
2455 true_block->AddSuccessor(new_pre_header);
2456 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002457
Aart Bik3fc7f352015-11-20 22:03:03 -08002458 old_pre_header->dominated_blocks_.push_back(if_block);
2459 if_block->SetDominator(old_pre_header);
2460 if_block->dominated_blocks_.push_back(true_block);
2461 true_block->SetDominator(if_block);
2462 if_block->dominated_blocks_.push_back(false_block);
2463 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002464 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002465 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002466 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002467 header->SetDominator(new_pre_header);
2468
Aart Bik3fc7f352015-11-20 22:03:03 -08002469 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002470 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002471 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002472 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002473 reverse_post_order_[index_of_header++] = true_block;
2474 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002475 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002476
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002477 // The pre_header can never be a back edge of a loop.
2478 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2479 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2480 UpdateLoopAndTryInformationOfNewBlock(
2481 if_block, old_pre_header, /* replace_if_back_edge */ false);
2482 UpdateLoopAndTryInformationOfNewBlock(
2483 true_block, old_pre_header, /* replace_if_back_edge */ false);
2484 UpdateLoopAndTryInformationOfNewBlock(
2485 false_block, old_pre_header, /* replace_if_back_edge */ false);
2486 UpdateLoopAndTryInformationOfNewBlock(
2487 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002488}
2489
Aart Bikf8f5a162017-02-06 15:35:29 -08002490HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2491 HBasicBlock* body,
2492 HBasicBlock* exit) {
2493 DCHECK(header->IsLoopHeader());
2494 HLoopInformation* loop = header->GetLoopInformation();
2495
2496 // Add new loop blocks.
2497 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2498 HBasicBlock* new_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2499 HBasicBlock* new_body = new (arena_) HBasicBlock(this, header->GetDexPc());
2500 AddBlock(new_pre_header);
2501 AddBlock(new_header);
2502 AddBlock(new_body);
2503
2504 // Set up control flow.
2505 header->ReplaceSuccessor(exit, new_pre_header);
2506 new_pre_header->AddSuccessor(new_header);
2507 new_header->AddSuccessor(exit);
2508 new_header->AddSuccessor(new_body);
2509 new_body->AddSuccessor(new_header);
2510
2511 // Set up dominators.
2512 header->ReplaceDominatedBlock(exit, new_pre_header);
2513 new_pre_header->SetDominator(header);
2514 new_pre_header->dominated_blocks_.push_back(new_header);
2515 new_header->SetDominator(new_pre_header);
2516 new_header->dominated_blocks_.push_back(new_body);
2517 new_body->SetDominator(new_header);
2518 new_header->dominated_blocks_.push_back(exit);
2519 exit->SetDominator(new_header);
2520
2521 // Fix reverse post order.
2522 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2523 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2524 reverse_post_order_[++index_of_header] = new_pre_header;
2525 reverse_post_order_[++index_of_header] = new_header;
2526 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2527 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2528 reverse_post_order_[index_of_body] = new_body;
2529
Aart Bikb07d1bc2017-04-05 10:03:15 -07002530 // Add gotos and suspend check (client must add conditional in header).
Aart Bikf8f5a162017-02-06 15:35:29 -08002531 new_pre_header->AddInstruction(new (arena_) HGoto());
2532 HSuspendCheck* suspend_check = new (arena_) HSuspendCheck(header->GetDexPc());
2533 new_header->AddInstruction(suspend_check);
2534 new_body->AddInstruction(new (arena_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002535 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2536 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002537
2538 // Update loop information.
2539 new_header->AddBackEdge(new_body);
2540 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2541 new_header->GetLoopInformation()->Populate();
2542 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2543 HLoopInformationOutwardIterator it(*new_header);
2544 for (it.Advance(); !it.Done(); it.Advance()) {
2545 it.Current()->Add(new_pre_header);
2546 it.Current()->Add(new_header);
2547 it.Current()->Add(new_body);
2548 }
2549 return new_pre_header;
2550}
2551
David Brazdilf5552582015-12-27 13:36:12 +00002552static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002553 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002554 if (rti.IsValid()) {
2555 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2556 << " upper_bound_rti: " << upper_bound_rti
2557 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002558 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2559 << " upper_bound_rti: " << upper_bound_rti
2560 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002561 }
2562}
2563
Calin Juravle2e768302015-07-28 14:41:11 +00002564void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2565 if (kIsDebugBuild) {
2566 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2567 ScopedObjectAccess soa(Thread::Current());
2568 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2569 if (IsBoundType()) {
2570 // Having the test here spares us from making the method virtual just for
2571 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002572 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002573 }
2574 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002575 reference_type_handle_ = rti.GetTypeHandle();
2576 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002577}
2578
David Brazdilf5552582015-12-27 13:36:12 +00002579void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2580 if (kIsDebugBuild) {
2581 ScopedObjectAccess soa(Thread::Current());
2582 DCHECK(upper_bound.IsValid());
2583 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2584 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2585 }
2586 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002587 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002588}
2589
Vladimir Markoa1de9182016-02-25 11:37:38 +00002590ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002591 if (kIsDebugBuild) {
2592 ScopedObjectAccess soa(Thread::Current());
2593 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002594 if (!is_exact) {
2595 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2596 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2597 }
Calin Juravle2e768302015-07-28 14:41:11 +00002598 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002599 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002600}
2601
Calin Juravleacf735c2015-02-12 15:25:22 +00002602std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2603 ScopedObjectAccess soa(Thread::Current());
2604 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002605 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002606 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002607 << " is_exact=" << rhs.IsExact()
2608 << " ]";
2609 return os;
2610}
2611
Mark Mendellc4701932015-04-10 13:18:51 -04002612bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2613 // For now, assume that instructions in different blocks may use the
2614 // environment.
2615 // TODO: Use the control flow to decide if this is true.
2616 if (GetBlock() != other->GetBlock()) {
2617 return true;
2618 }
2619
2620 // We know that we are in the same block. Walk from 'this' to 'other',
2621 // checking to see if there is any instruction with an environment.
2622 HInstruction* current = this;
2623 for (; current != other && current != nullptr; current = current->GetNext()) {
2624 // This is a conservative check, as the instruction result may not be in
2625 // the referenced environment.
2626 if (current->HasEnvironment()) {
2627 return true;
2628 }
2629 }
2630
2631 // We should have been called with 'this' before 'other' in the block.
2632 // Just confirm this.
2633 DCHECK(current != nullptr);
2634 return false;
2635}
2636
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002637void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002638 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2639 IntrinsicSideEffects side_effects,
2640 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002641 intrinsic_ = intrinsic;
2642 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002643
Aart Bik5d75afe2015-12-14 11:57:01 -08002644 // Adjust method's side effects from intrinsic table.
2645 switch (side_effects) {
2646 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2647 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2648 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2649 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2650 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002651
2652 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2653 opt.SetDoesNotNeedDexCache();
2654 opt.SetDoesNotNeedEnvironment();
2655 } else {
2656 // If we need an environment, that means there will be a call, which can trigger GC.
2657 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2658 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002659 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002660 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002661}
2662
David Brazdil6de19382016-01-08 17:37:10 +00002663bool HNewInstance::IsStringAlloc() const {
2664 ScopedObjectAccess soa(Thread::Current());
2665 return GetReferenceTypeInfo().IsStringClass();
2666}
2667
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002668bool HInvoke::NeedsEnvironment() const {
2669 if (!IsIntrinsic()) {
2670 return true;
2671 }
2672 IntrinsicOptimizations opt(*this);
2673 return !opt.GetDoesNotNeedEnvironment();
2674}
2675
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002676const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2677 ArtMethod* caller = GetEnvironment()->GetMethod();
2678 ScopedObjectAccess soa(Thread::Current());
2679 // `caller` is null for a top-level graph representing a method whose declaring
2680 // class was not resolved.
2681 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2682}
2683
Vladimir Markodc151b22015-10-15 18:02:30 +01002684bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002685 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002686 return false;
2687 }
2688 if (!IsIntrinsic()) {
2689 return true;
2690 }
2691 IntrinsicOptimizations opt(*this);
2692 return !opt.GetDoesNotNeedDexCache();
2693}
2694
Vladimir Markof64242a2015-12-01 14:58:23 +00002695std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2696 switch (rhs) {
2697 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002698 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002699 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002700 return os << "Recursive";
2701 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2702 return os << "BootImageLinkTimePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002703 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
Vladimir Marko19d7d502017-05-24 13:04:14 +01002704 return os << "DirectAddress";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002705 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2706 return os << "BssEntry";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002707 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2708 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002709 default:
2710 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2711 UNREACHABLE();
2712 }
2713}
2714
Vladimir Markofbb184a2015-11-13 14:47:00 +00002715std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2716 switch (rhs) {
2717 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2718 return os << "explicit";
2719 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2720 return os << "implicit";
2721 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2722 return os << "none";
2723 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002724 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2725 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002726 }
2727}
2728
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002729bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2730 const HLoadClass* other_load_class = other->AsLoadClass();
2731 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2732 // names rather than type indexes. However, we shall also have to re-think the hash code.
2733 if (type_index_ != other_load_class->type_index_ ||
2734 GetPackedFields() != other_load_class->GetPackedFields()) {
2735 return false;
2736 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002737 switch (GetLoadKind()) {
2738 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002739 case LoadKind::kJitTableAddress: {
2740 ScopedObjectAccess soa(Thread::Current());
2741 return GetClass().Get() == other_load_class->GetClass().Get();
2742 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002743 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002744 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002745 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002746 }
2747}
2748
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002749void HLoadClass::SetLoadKind(LoadKind load_kind) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002750 SetPackedField<LoadKindField>(load_kind);
2751
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002752 if (load_kind != LoadKind::kRuntimeCall &&
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002753 load_kind != LoadKind::kReferrersClass) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002754 RemoveAsUserOfInput(0u);
2755 SetRawInputAt(0u, nullptr);
2756 }
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002757
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002758 if (!NeedsEnvironment()) {
2759 RemoveEnvironment();
2760 SetSideEffects(SideEffects::None());
2761 }
2762}
2763
2764std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2765 switch (rhs) {
2766 case HLoadClass::LoadKind::kReferrersClass:
2767 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002768 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2769 return os << "BootImageLinkTimePcRelative";
2770 case HLoadClass::LoadKind::kBootImageAddress:
2771 return os << "BootImageAddress";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002772 case HLoadClass::LoadKind::kBssEntry:
2773 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002774 case HLoadClass::LoadKind::kJitTableAddress:
2775 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002776 case HLoadClass::LoadKind::kRuntimeCall:
2777 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002778 default:
2779 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2780 UNREACHABLE();
2781 }
2782}
2783
Vladimir Marko372f10e2016-05-17 16:30:10 +01002784bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2785 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002786 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2787 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002788 if (string_index_ != other_load_string->string_index_ ||
2789 GetPackedFields() != other_load_string->GetPackedFields()) {
2790 return false;
2791 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002792 switch (GetLoadKind()) {
2793 case LoadKind::kBootImageAddress:
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002794 case LoadKind::kBootImageInternTable:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002795 case LoadKind::kJitTableAddress: {
2796 ScopedObjectAccess soa(Thread::Current());
2797 return GetString().Get() == other_load_string->GetString().Get();
2798 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002799 default:
2800 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002801 }
2802}
2803
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002804void HLoadString::SetLoadKind(LoadKind load_kind) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002805 // Once sharpened, the load kind should not be changed again.
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002806 DCHECK_EQ(GetLoadKind(), LoadKind::kRuntimeCall);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002807 SetPackedField<LoadKindField>(load_kind);
2808
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002809 if (load_kind != LoadKind::kRuntimeCall) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002810 RemoveAsUserOfInput(0u);
2811 SetRawInputAt(0u, nullptr);
2812 }
2813 if (!NeedsEnvironment()) {
2814 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002815 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002816 }
2817}
2818
2819std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2820 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002821 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2822 return os << "BootImageLinkTimePcRelative";
2823 case HLoadString::LoadKind::kBootImageAddress:
2824 return os << "BootImageAddress";
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01002825 case HLoadString::LoadKind::kBootImageInternTable:
2826 return os << "BootImageInternTable";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002827 case HLoadString::LoadKind::kBssEntry:
2828 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002829 case HLoadString::LoadKind::kJitTableAddress:
2830 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002831 case HLoadString::LoadKind::kRuntimeCall:
2832 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002833 default:
2834 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2835 UNREACHABLE();
2836 }
2837}
2838
Mark Mendellc4701932015-04-10 13:18:51 -04002839void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002840 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2841 HEnvironment* user = use.GetUser();
2842 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002843 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002844 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002845}
2846
Roland Levillainc9b21f82016-03-23 16:36:59 +00002847// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002848HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2849 ArenaAllocator* allocator = GetArena();
2850
2851 if (cond->IsCondition() &&
2852 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2853 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2854 HInstruction* lhs = cond->InputAt(0);
2855 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002856 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002857 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2858 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2859 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2860 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2861 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2862 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2863 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2864 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2865 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2866 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2867 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002868 default:
2869 LOG(FATAL) << "Unexpected condition";
2870 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002871 }
2872 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2873 return replacement;
2874 } else if (cond->IsIntConstant()) {
2875 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002876 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002877 return GetIntConstant(1);
2878 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002879 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002880 return GetIntConstant(0);
2881 }
2882 } else {
2883 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2884 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2885 return replacement;
2886 }
2887}
2888
Roland Levillainc9285912015-12-18 10:38:42 +00002889std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2890 os << "["
2891 << " source=" << rhs.GetSource()
2892 << " destination=" << rhs.GetDestination()
2893 << " type=" << rhs.GetType()
2894 << " instruction=";
2895 if (rhs.GetInstruction() != nullptr) {
2896 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2897 } else {
2898 os << "null";
2899 }
2900 os << " ]";
2901 return os;
2902}
2903
Roland Levillain86503782016-02-11 19:07:30 +00002904std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2905 switch (rhs) {
2906 case TypeCheckKind::kUnresolvedCheck:
2907 return os << "unresolved_check";
2908 case TypeCheckKind::kExactCheck:
2909 return os << "exact_check";
2910 case TypeCheckKind::kClassHierarchyCheck:
2911 return os << "class_hierarchy_check";
2912 case TypeCheckKind::kAbstractClassCheck:
2913 return os << "abstract_class_check";
2914 case TypeCheckKind::kInterfaceCheck:
2915 return os << "interface_check";
2916 case TypeCheckKind::kArrayObjectCheck:
2917 return os << "array_object_check";
2918 case TypeCheckKind::kArrayCheck:
2919 return os << "array_check";
2920 default:
2921 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2922 UNREACHABLE();
2923 }
2924}
2925
Andreas Gampe26de38b2016-07-27 17:53:11 -07002926std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2927 switch (kind) {
2928 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002929 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002930 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002931 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002932 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002933 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002934 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002935 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002936 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002937 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002938
2939 default:
2940 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
2941 UNREACHABLE();
2942 }
2943}
2944
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002945} // namespace art