blob: 508027e52a1078ea64e9702c790a7b3ed2ffc235 [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
1754bool HBasicBlock::IsSingleTryBoundary() const {
1755 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001756}
1757
David Brazdil8d5b8b22015-03-24 10:51:52 +00001758bool HBasicBlock::EndsWithControlFlowInstruction() const {
1759 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1760}
1761
David Brazdilb2bd1c52015-03-25 11:17:37 +00001762bool HBasicBlock::EndsWithIf() const {
1763 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1764}
1765
David Brazdilffee3d32015-07-06 11:48:53 +01001766bool HBasicBlock::EndsWithTryBoundary() const {
1767 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1768}
1769
David Brazdilb2bd1c52015-03-25 11:17:37 +00001770bool HBasicBlock::HasSinglePhi() const {
1771 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1772}
1773
David Brazdild26a4112015-11-10 11:07:31 +00001774ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1775 if (EndsWithTryBoundary()) {
1776 // The normal-flow successor of HTryBoundary is always stored at index zero.
1777 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1778 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1779 } else {
1780 // All successors of blocks not ending with TryBoundary are normal.
1781 return ArrayRef<HBasicBlock* const>(successors_);
1782 }
1783}
1784
1785ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1786 if (EndsWithTryBoundary()) {
1787 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1788 } else {
1789 // Blocks not ending with TryBoundary do not have exceptional successors.
1790 return ArrayRef<HBasicBlock* const>();
1791 }
1792}
1793
David Brazdilffee3d32015-07-06 11:48:53 +01001794bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001795 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1796 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1797
1798 size_t length = handlers1.size();
1799 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001800 return false;
1801 }
1802
David Brazdilb618ade2015-07-29 10:31:29 +01001803 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001804 for (size_t i = 0; i < length; ++i) {
1805 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001806 return false;
1807 }
1808 }
1809 return true;
1810}
1811
David Brazdil2d7352b2015-04-20 14:52:42 +01001812size_t HInstructionList::CountSize() const {
1813 size_t size = 0;
1814 HInstruction* current = first_instruction_;
1815 for (; current != nullptr; current = current->GetNext()) {
1816 size++;
1817 }
1818 return size;
1819}
1820
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001821void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1822 for (HInstruction* current = first_instruction_;
1823 current != nullptr;
1824 current = current->GetNext()) {
1825 current->SetBlock(block);
1826 }
1827}
1828
1829void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1830 DCHECK(Contains(cursor));
1831 if (!instruction_list.IsEmpty()) {
1832 if (cursor == last_instruction_) {
1833 last_instruction_ = instruction_list.last_instruction_;
1834 } else {
1835 cursor->next_->previous_ = instruction_list.last_instruction_;
1836 }
1837 instruction_list.last_instruction_->next_ = cursor->next_;
1838 cursor->next_ = instruction_list.first_instruction_;
1839 instruction_list.first_instruction_->previous_ = cursor;
1840 }
1841}
1842
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001843void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1844 DCHECK(Contains(cursor));
1845 if (!instruction_list.IsEmpty()) {
1846 if (cursor == first_instruction_) {
1847 first_instruction_ = instruction_list.first_instruction_;
1848 } else {
1849 cursor->previous_->next_ = instruction_list.first_instruction_;
1850 }
1851 instruction_list.last_instruction_->next_ = cursor;
1852 instruction_list.first_instruction_->previous_ = cursor->previous_;
1853 cursor->previous_ = instruction_list.last_instruction_;
1854 }
1855}
1856
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001857void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001858 if (IsEmpty()) {
1859 first_instruction_ = instruction_list.first_instruction_;
1860 last_instruction_ = instruction_list.last_instruction_;
1861 } else {
1862 AddAfter(last_instruction_, instruction_list);
1863 }
1864}
1865
David Brazdil04ff4e82015-12-10 13:54:52 +00001866// Should be called on instructions in a dead block in post order. This method
1867// assumes `insn` has been removed from all users with the exception of catch
1868// phis because of missing exceptional edges in the graph. It removes the
1869// instruction from catch phi uses, together with inputs of other catch phis in
1870// the catch block at the same index, as these must be dead too.
1871static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1872 DCHECK(!insn->HasEnvironmentUses());
1873 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001874 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1875 size_t use_index = use.GetIndex();
1876 HBasicBlock* user_block = use.GetUser()->GetBlock();
1877 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001878 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1879 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1880 }
1881 }
1882}
1883
David Brazdil2d7352b2015-04-20 14:52:42 +01001884void HBasicBlock::DisconnectAndDelete() {
1885 // Dominators must be removed after all the blocks they dominate. This way
1886 // a loop header is removed last, a requirement for correct loop information
1887 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001888 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001889
David Brazdil9eeebf62016-03-24 11:18:15 +00001890 // The following steps gradually remove the block from all its dependants in
1891 // post order (b/27683071).
1892
1893 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1894 // We need to do this before step (4) which destroys the predecessor list.
1895 HBasicBlock* loop_update_start = this;
1896 if (IsLoopHeader()) {
1897 HLoopInformation* loop_info = GetLoopInformation();
1898 // All other blocks in this loop should have been removed because the header
1899 // was their dominator.
1900 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1901 DCHECK(!loop_info->IsIrreducible());
1902 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1903 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1904 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001905 }
1906
David Brazdil9eeebf62016-03-24 11:18:15 +00001907 // (2) Disconnect the block from its successors and update their phis.
1908 for (HBasicBlock* successor : successors_) {
1909 // Delete this block from the list of predecessors.
1910 size_t this_index = successor->GetPredecessorIndexOf(this);
1911 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1912
1913 // Check that `successor` has other predecessors, otherwise `this` is the
1914 // dominator of `successor` which violates the order DCHECKed at the top.
1915 DCHECK(!successor->predecessors_.empty());
1916
1917 // Remove this block's entries in the successor's phis. Skip exceptional
1918 // successors because catch phi inputs do not correspond to predecessor
1919 // blocks but throwing instructions. The inputs of the catch phis will be
1920 // updated in step (3).
1921 if (!successor->IsCatchBlock()) {
1922 if (successor->predecessors_.size() == 1u) {
1923 // The successor has just one predecessor left. Replace phis with the only
1924 // remaining input.
1925 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1926 HPhi* phi = phi_it.Current()->AsPhi();
1927 phi->ReplaceWith(phi->InputAt(1 - this_index));
1928 successor->RemovePhi(phi);
1929 }
1930 } else {
1931 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1932 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1933 }
1934 }
1935 }
1936 }
1937 successors_.clear();
1938
1939 // (3) Remove instructions and phis. Instructions should have no remaining uses
1940 // except in catch phis. If an instruction is used by a catch phi at `index`,
1941 // remove `index`-th input of all phis in the catch block since they are
1942 // guaranteed dead. Note that we may miss dead inputs this way but the
1943 // graph will always remain consistent.
1944 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1945 HInstruction* insn = it.Current();
1946 RemoveUsesOfDeadInstruction(insn);
1947 RemoveInstruction(insn);
1948 }
1949 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1950 HPhi* insn = it.Current()->AsPhi();
1951 RemoveUsesOfDeadInstruction(insn);
1952 RemovePhi(insn);
1953 }
1954
1955 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001956 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001957 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001958 // We should not see any back edges as they would have been removed by step (3).
1959 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1960
David Brazdil2d7352b2015-04-20 14:52:42 +01001961 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001962 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1963 // This block is the only normal-flow successor of the TryBoundary which
1964 // makes `predecessor` dead. Since DCE removes blocks in post order,
1965 // exception handlers of this TryBoundary were already visited and any
1966 // remaining handlers therefore must be live. We remove `predecessor` from
1967 // their list of predecessors.
1968 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1969 while (predecessor->GetSuccessors().size() > 1) {
1970 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1971 DCHECK(handler->IsCatchBlock());
1972 predecessor->RemoveSuccessor(handler);
1973 handler->RemovePredecessor(predecessor);
1974 }
1975 }
1976
David Brazdil2d7352b2015-04-20 14:52:42 +01001977 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001978 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1979 if (num_pred_successors == 1u) {
1980 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001981 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1982 // successor. Replace those with a HGoto.
1983 DCHECK(last_instruction->IsIf() ||
1984 last_instruction->IsPackedSwitch() ||
1985 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001986 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001987 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001988 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001989 // The predecessor has no remaining successors and therefore must be dead.
1990 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001991 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001992 predecessor->RemoveInstruction(last_instruction);
1993 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001994 // There are multiple successors left. The removed block might be a successor
1995 // of a PackedSwitch which will be completely removed (perhaps replaced with
1996 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1997 // case, leave `last_instruction` as is for now.
1998 DCHECK(last_instruction->IsPackedSwitch() ||
1999 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002000 }
David Brazdil46e2a392015-03-16 17:31:52 +00002001 }
Vladimir Marko60584552015-09-03 13:35:12 +00002002 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002003
David Brazdil9eeebf62016-03-24 11:18:15 +00002004 // (5) Remove the block from all loops it is included in. Skip the inner-most
2005 // loop if this is the loop header (see definition of `loop_update_start`)
2006 // because the loop header's predecessor list has been destroyed in step (4).
2007 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2008 HLoopInformation* loop_info = it.Current();
2009 loop_info->Remove(this);
2010 if (loop_info->IsBackEdge(*this)) {
2011 // If this was the last back edge of the loop, we deliberately leave the
2012 // loop in an inconsistent state and will fail GraphChecker unless the
2013 // entire loop is removed during the pass.
2014 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002015 }
2016 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002017
David Brazdil9eeebf62016-03-24 11:18:15 +00002018 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002019 dominator_->RemoveDominatedBlock(this);
2020 SetDominator(nullptr);
2021
David Brazdil9eeebf62016-03-24 11:18:15 +00002022 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002023 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002024 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002025}
2026
Aart Bik6b69e0a2017-01-11 10:20:43 -08002027void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2028 DCHECK(EndsWithControlFlowInstruction());
2029 RemoveInstruction(GetLastInstruction());
2030 instructions_.Add(other->GetInstructions());
2031 other->instructions_.SetBlockOfInstructions(this);
2032 other->instructions_.Clear();
2033}
2034
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002035void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002036 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002037 DCHECK(ContainsElement(dominated_blocks_, other));
2038 DCHECK_EQ(GetSingleSuccessor(), other);
2039 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002040 DCHECK(other->GetPhis().IsEmpty());
2041
David Brazdil2d7352b2015-04-20 14:52:42 +01002042 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002043 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002044
David Brazdil2d7352b2015-04-20 14:52:42 +01002045 // Remove `other` from the loops it is included in.
2046 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2047 HLoopInformation* loop_info = it.Current();
2048 loop_info->Remove(other);
2049 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002050 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002051 }
2052 }
2053
2054 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002055 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002056 for (HBasicBlock* successor : other->GetSuccessors()) {
2057 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002058 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002059 successors_.swap(other->successors_);
2060 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002061
David Brazdil2d7352b2015-04-20 14:52:42 +01002062 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002063 RemoveDominatedBlock(other);
2064 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002065 dominated->SetDominator(this);
2066 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002067 dominated_blocks_.insert(
2068 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002069 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002070 other->dominator_ = nullptr;
2071
2072 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002073 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002074
2075 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002076 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002077 other->SetGraph(nullptr);
2078}
2079
2080void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2081 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002082 DCHECK(GetDominatedBlocks().empty());
2083 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002084 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002085 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002086 DCHECK(other->GetPhis().IsEmpty());
2087 DCHECK(!other->IsInLoop());
2088
2089 // Move instructions from `other` to `this`.
2090 instructions_.Add(other->GetInstructions());
2091 other->instructions_.SetBlockOfInstructions(this);
2092
2093 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002094 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002095 for (HBasicBlock* successor : other->GetSuccessors()) {
2096 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002097 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002098 successors_.swap(other->successors_);
2099 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002100
2101 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002102 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002103 dominated->SetDominator(this);
2104 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002105 dominated_blocks_.insert(
2106 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002107 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002108 other->dominator_ = nullptr;
2109 other->graph_ = nullptr;
2110}
2111
2112void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002113 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002114 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002115 predecessor->ReplaceSuccessor(this, other);
2116 }
Vladimir Marko60584552015-09-03 13:35:12 +00002117 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002118 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002119 successor->ReplacePredecessor(this, other);
2120 }
Vladimir Marko60584552015-09-03 13:35:12 +00002121 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2122 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002123 }
2124 GetDominator()->ReplaceDominatedBlock(this, other);
2125 other->SetDominator(GetDominator());
2126 dominator_ = nullptr;
2127 graph_ = nullptr;
2128}
2129
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002130void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002131 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002132 DCHECK(block->GetSuccessors().empty());
2133 DCHECK(block->GetPredecessors().empty());
2134 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002135 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002136 DCHECK(block->GetInstructions().IsEmpty());
2137 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002138
David Brazdilc7af85d2015-05-26 12:05:55 +01002139 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002140 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002141 }
2142
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002143 RemoveElement(reverse_post_order_, block);
2144 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002145 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002146}
2147
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002148void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2149 HBasicBlock* reference,
2150 bool replace_if_back_edge) {
2151 if (block->IsLoopHeader()) {
2152 // Clear the information of which blocks are contained in that loop. Since the
2153 // information is stored as a bit vector based on block ids, we have to update
2154 // it, as those block ids were specific to the callee graph and we are now adding
2155 // these blocks to the caller graph.
2156 block->GetLoopInformation()->ClearAllBlocks();
2157 }
2158
2159 // If not already in a loop, update the loop information.
2160 if (!block->IsInLoop()) {
2161 block->SetLoopInformation(reference->GetLoopInformation());
2162 }
2163
2164 // If the block is in a loop, update all its outward loops.
2165 HLoopInformation* loop_info = block->GetLoopInformation();
2166 if (loop_info != nullptr) {
2167 for (HLoopInformationOutwardIterator loop_it(*block);
2168 !loop_it.Done();
2169 loop_it.Advance()) {
2170 loop_it.Current()->Add(block);
2171 }
2172 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2173 loop_info->ReplaceBackEdge(reference, block);
2174 }
2175 }
2176
2177 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2178 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2179 ? reference->GetTryCatchInformation()
2180 : nullptr;
2181 block->SetTryCatchInformation(try_catch_info);
2182}
2183
Calin Juravle2e768302015-07-28 14:41:11 +00002184HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002185 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002186 // Update the environments in this graph to have the invoke's environment
2187 // as parent.
2188 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002189 // Skip the entry block, we do not need to update the entry's suspend check.
2190 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002191 for (HInstructionIterator instr_it(block->GetInstructions());
2192 !instr_it.Done();
2193 instr_it.Advance()) {
2194 HInstruction* current = instr_it.Current();
2195 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002196 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002197 current->GetEnvironment()->SetAndCopyParentChain(
2198 outer_graph->GetArena(), invoke->GetEnvironment());
2199 }
2200 }
2201 }
2202 }
2203 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002204
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002205 if (HasBoundsChecks()) {
2206 outer_graph->SetHasBoundsChecks(true);
2207 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002208 if (HasLoops()) {
2209 outer_graph->SetHasLoops(true);
2210 }
2211 if (HasIrreducibleLoops()) {
2212 outer_graph->SetHasIrreducibleLoops(true);
2213 }
2214 if (HasTryCatch()) {
2215 outer_graph->SetHasTryCatch(true);
2216 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002217 if (HasSIMD()) {
2218 outer_graph->SetHasSIMD(true);
2219 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002220
Calin Juravle2e768302015-07-28 14:41:11 +00002221 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002222 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002223 // Inliner already made sure we don't inline methods that always throw.
2224 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002225 // Simple case of an entry block, a body block, and an exit block.
2226 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002227 HBasicBlock* body = GetBlocks()[1];
2228 DCHECK(GetBlocks()[0]->IsEntryBlock());
2229 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002230 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002231 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002232 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002233
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002234 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2235 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002236 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002237
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002238 // Replace the invoke with the return value of the inlined graph.
2239 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002240 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002241 } else {
2242 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002243 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002244
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002245 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002246 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002247 // Need to inline multiple blocks. We split `invoke`'s block
2248 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002249 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002250 // with the second half.
2251 ArenaAllocator* allocator = outer_graph->GetArena();
2252 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002253 // Note that we split before the invoke only to simplify polymorphic inlining.
2254 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002255
Vladimir Markoec7802a2015-10-01 20:57:57 +01002256 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002257 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002258 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002259 exit_block_->ReplaceWith(to);
2260
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002261 // Update the meta information surrounding blocks:
2262 // (1) the graph they are now in,
2263 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002264 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002265 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002266 // Note that we do not need to update catch phi inputs because they
2267 // correspond to the register file of the outer method which the inlinee
2268 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002269
2270 // We don't add the entry block, the exit block, and the first block, which
2271 // has been merged with `at`.
2272 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2273
2274 // We add the `to` block.
2275 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002276 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002277 + kNumberOfNewBlocksInCaller;
2278
2279 // Find the location of `at` in the outer graph's reverse post order. The new
2280 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002281 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002282 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2283
David Brazdil95177982015-10-30 12:56:58 -05002284 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2285 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002286 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002287 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002288 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002289 DCHECK(current->GetGraph() == this);
2290 current->SetGraph(outer_graph);
2291 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002292 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002293 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002294 }
2295 }
2296
David Brazdil95177982015-10-30 12:56:58 -05002297 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002298 to->SetGraph(outer_graph);
2299 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002300 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002301 // Only `to` can become a back edge, as the inlined blocks
2302 // are predecessors of `to`.
2303 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002304
David Brazdil3f523062016-02-29 16:53:33 +00002305 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002306 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2307 // to now get the outer graph exit block as successor. Note that the inliner
2308 // currently doesn't support inlining methods with try/catch.
2309 HPhi* return_value_phi = nullptr;
2310 bool rerun_dominance = false;
2311 bool rerun_loop_analysis = false;
2312 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2313 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002314 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002315 if (last->IsThrow()) {
2316 DCHECK(!at->IsTryBlock());
2317 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2318 --pred;
2319 // We need to re-run dominance information, as the exit block now has
2320 // a new dominator.
2321 rerun_dominance = true;
2322 if (predecessor->GetLoopInformation() != nullptr) {
2323 // The exit block and blocks post dominated by the exit block do not belong
2324 // to any loop. Because we do not compute the post dominators, we need to re-run
2325 // loop analysis to get the loop information correct.
2326 rerun_loop_analysis = true;
2327 }
2328 } else {
2329 if (last->IsReturnVoid()) {
2330 DCHECK(return_value == nullptr);
2331 DCHECK(return_value_phi == nullptr);
2332 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002333 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002334 if (return_value_phi != nullptr) {
2335 return_value_phi->AddInput(last->InputAt(0));
2336 } else if (return_value == nullptr) {
2337 return_value = last->InputAt(0);
2338 } else {
2339 // There will be multiple returns.
2340 return_value_phi = new (allocator) HPhi(
2341 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2342 to->AddPhi(return_value_phi);
2343 return_value_phi->AddInput(return_value);
2344 return_value_phi->AddInput(last->InputAt(0));
2345 return_value = return_value_phi;
2346 }
David Brazdil3f523062016-02-29 16:53:33 +00002347 }
2348 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2349 predecessor->RemoveInstruction(last);
2350 }
2351 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002352 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002353 DCHECK(!outer_graph->HasIrreducibleLoops())
2354 << "Recomputing loop information in graphs with irreducible loops "
2355 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002356 outer_graph->ClearLoopInformation();
2357 outer_graph->ClearDominanceInformation();
2358 outer_graph->BuildDominatorTree();
2359 } else if (rerun_dominance) {
2360 outer_graph->ClearDominanceInformation();
2361 outer_graph->ComputeDominanceInformation();
2362 }
David Brazdil3f523062016-02-29 16:53:33 +00002363 }
David Brazdil05144f42015-04-16 15:18:00 +01002364
2365 // Walk over the entry block and:
2366 // - Move constants from the entry block to the outer_graph's entry block,
2367 // - Replace HParameterValue instructions with their real value.
2368 // - Remove suspend checks, that hold an environment.
2369 // We must do this after the other blocks have been inlined, otherwise ids of
2370 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002371 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002372 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2373 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002374 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002375 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002376 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002377 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002378 replacement = outer_graph->GetIntConstant(
2379 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002380 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002381 replacement = outer_graph->GetLongConstant(
2382 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002383 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002384 replacement = outer_graph->GetFloatConstant(
2385 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002386 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002387 replacement = outer_graph->GetDoubleConstant(
2388 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002389 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002390 if (kIsDebugBuild
2391 && invoke->IsInvokeStaticOrDirect()
2392 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2393 // Ensure we do not use the last input of `invoke`, as it
2394 // contains a clinit check which is not an actual argument.
2395 size_t last_input_index = invoke->InputCount() - 1;
2396 DCHECK(parameter_index != last_input_index);
2397 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002398 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002399 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002400 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002401 } else {
2402 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2403 entry_block_->RemoveInstruction(current);
2404 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002405 if (replacement != nullptr) {
2406 current->ReplaceWith(replacement);
2407 // If the current is the return value then we need to update the latter.
2408 if (current == return_value) {
2409 DCHECK_EQ(entry_block_, return_value->GetBlock());
2410 return_value = replacement;
2411 }
2412 }
2413 }
2414
Calin Juravle2e768302015-07-28 14:41:11 +00002415 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002416}
2417
Mingyao Yang3584bce2015-05-19 16:01:59 -07002418/*
2419 * Loop will be transformed to:
2420 * old_pre_header
2421 * |
2422 * if_block
2423 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002424 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002425 * \ /
2426 * new_pre_header
2427 * |
2428 * header
2429 */
2430void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2431 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002432 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002433
Aart Bik3fc7f352015-11-20 22:03:03 -08002434 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002435 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002436 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2437 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002438 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2439 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002440 AddBlock(true_block);
2441 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002442 AddBlock(new_pre_header);
2443
Aart Bik3fc7f352015-11-20 22:03:03 -08002444 header->ReplacePredecessor(old_pre_header, new_pre_header);
2445 old_pre_header->successors_.clear();
2446 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002447
Aart Bik3fc7f352015-11-20 22:03:03 -08002448 old_pre_header->AddSuccessor(if_block);
2449 if_block->AddSuccessor(true_block); // True successor
2450 if_block->AddSuccessor(false_block); // False successor
2451 true_block->AddSuccessor(new_pre_header);
2452 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002453
Aart Bik3fc7f352015-11-20 22:03:03 -08002454 old_pre_header->dominated_blocks_.push_back(if_block);
2455 if_block->SetDominator(old_pre_header);
2456 if_block->dominated_blocks_.push_back(true_block);
2457 true_block->SetDominator(if_block);
2458 if_block->dominated_blocks_.push_back(false_block);
2459 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002460 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002461 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002462 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002463 header->SetDominator(new_pre_header);
2464
Aart Bik3fc7f352015-11-20 22:03:03 -08002465 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002466 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002467 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002468 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002469 reverse_post_order_[index_of_header++] = true_block;
2470 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002471 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002472
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002473 // The pre_header can never be a back edge of a loop.
2474 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2475 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2476 UpdateLoopAndTryInformationOfNewBlock(
2477 if_block, old_pre_header, /* replace_if_back_edge */ false);
2478 UpdateLoopAndTryInformationOfNewBlock(
2479 true_block, old_pre_header, /* replace_if_back_edge */ false);
2480 UpdateLoopAndTryInformationOfNewBlock(
2481 false_block, old_pre_header, /* replace_if_back_edge */ false);
2482 UpdateLoopAndTryInformationOfNewBlock(
2483 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002484}
2485
Aart Bikf8f5a162017-02-06 15:35:29 -08002486HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2487 HBasicBlock* body,
2488 HBasicBlock* exit) {
2489 DCHECK(header->IsLoopHeader());
2490 HLoopInformation* loop = header->GetLoopInformation();
2491
2492 // Add new loop blocks.
2493 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2494 HBasicBlock* new_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2495 HBasicBlock* new_body = new (arena_) HBasicBlock(this, header->GetDexPc());
2496 AddBlock(new_pre_header);
2497 AddBlock(new_header);
2498 AddBlock(new_body);
2499
2500 // Set up control flow.
2501 header->ReplaceSuccessor(exit, new_pre_header);
2502 new_pre_header->AddSuccessor(new_header);
2503 new_header->AddSuccessor(exit);
2504 new_header->AddSuccessor(new_body);
2505 new_body->AddSuccessor(new_header);
2506
2507 // Set up dominators.
2508 header->ReplaceDominatedBlock(exit, new_pre_header);
2509 new_pre_header->SetDominator(header);
2510 new_pre_header->dominated_blocks_.push_back(new_header);
2511 new_header->SetDominator(new_pre_header);
2512 new_header->dominated_blocks_.push_back(new_body);
2513 new_body->SetDominator(new_header);
2514 new_header->dominated_blocks_.push_back(exit);
2515 exit->SetDominator(new_header);
2516
2517 // Fix reverse post order.
2518 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2519 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2520 reverse_post_order_[++index_of_header] = new_pre_header;
2521 reverse_post_order_[++index_of_header] = new_header;
2522 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2523 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2524 reverse_post_order_[index_of_body] = new_body;
2525
Aart Bikb07d1bc2017-04-05 10:03:15 -07002526 // Add gotos and suspend check (client must add conditional in header).
Aart Bikf8f5a162017-02-06 15:35:29 -08002527 new_pre_header->AddInstruction(new (arena_) HGoto());
2528 HSuspendCheck* suspend_check = new (arena_) HSuspendCheck(header->GetDexPc());
2529 new_header->AddInstruction(suspend_check);
2530 new_body->AddInstruction(new (arena_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002531 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2532 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002533
2534 // Update loop information.
2535 new_header->AddBackEdge(new_body);
2536 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2537 new_header->GetLoopInformation()->Populate();
2538 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2539 HLoopInformationOutwardIterator it(*new_header);
2540 for (it.Advance(); !it.Done(); it.Advance()) {
2541 it.Current()->Add(new_pre_header);
2542 it.Current()->Add(new_header);
2543 it.Current()->Add(new_body);
2544 }
2545 return new_pre_header;
2546}
2547
David Brazdilf5552582015-12-27 13:36:12 +00002548static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002549 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002550 if (rti.IsValid()) {
2551 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2552 << " upper_bound_rti: " << upper_bound_rti
2553 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002554 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2555 << " upper_bound_rti: " << upper_bound_rti
2556 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002557 }
2558}
2559
Calin Juravle2e768302015-07-28 14:41:11 +00002560void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2561 if (kIsDebugBuild) {
2562 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2563 ScopedObjectAccess soa(Thread::Current());
2564 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2565 if (IsBoundType()) {
2566 // Having the test here spares us from making the method virtual just for
2567 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002568 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002569 }
2570 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002571 reference_type_handle_ = rti.GetTypeHandle();
2572 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002573}
2574
David Brazdilf5552582015-12-27 13:36:12 +00002575void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2576 if (kIsDebugBuild) {
2577 ScopedObjectAccess soa(Thread::Current());
2578 DCHECK(upper_bound.IsValid());
2579 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2580 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2581 }
2582 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002583 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002584}
2585
Vladimir Markoa1de9182016-02-25 11:37:38 +00002586ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002587 if (kIsDebugBuild) {
2588 ScopedObjectAccess soa(Thread::Current());
2589 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002590 if (!is_exact) {
2591 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2592 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2593 }
Calin Juravle2e768302015-07-28 14:41:11 +00002594 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002595 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002596}
2597
Calin Juravleacf735c2015-02-12 15:25:22 +00002598std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2599 ScopedObjectAccess soa(Thread::Current());
2600 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002601 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002602 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002603 << " is_exact=" << rhs.IsExact()
2604 << " ]";
2605 return os;
2606}
2607
Mark Mendellc4701932015-04-10 13:18:51 -04002608bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2609 // For now, assume that instructions in different blocks may use the
2610 // environment.
2611 // TODO: Use the control flow to decide if this is true.
2612 if (GetBlock() != other->GetBlock()) {
2613 return true;
2614 }
2615
2616 // We know that we are in the same block. Walk from 'this' to 'other',
2617 // checking to see if there is any instruction with an environment.
2618 HInstruction* current = this;
2619 for (; current != other && current != nullptr; current = current->GetNext()) {
2620 // This is a conservative check, as the instruction result may not be in
2621 // the referenced environment.
2622 if (current->HasEnvironment()) {
2623 return true;
2624 }
2625 }
2626
2627 // We should have been called with 'this' before 'other' in the block.
2628 // Just confirm this.
2629 DCHECK(current != nullptr);
2630 return false;
2631}
2632
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002633void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002634 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2635 IntrinsicSideEffects side_effects,
2636 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002637 intrinsic_ = intrinsic;
2638 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002639
Aart Bik5d75afe2015-12-14 11:57:01 -08002640 // Adjust method's side effects from intrinsic table.
2641 switch (side_effects) {
2642 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2643 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2644 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2645 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2646 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002647
2648 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2649 opt.SetDoesNotNeedDexCache();
2650 opt.SetDoesNotNeedEnvironment();
2651 } else {
2652 // If we need an environment, that means there will be a call, which can trigger GC.
2653 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2654 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002655 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002656 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002657}
2658
David Brazdil6de19382016-01-08 17:37:10 +00002659bool HNewInstance::IsStringAlloc() const {
2660 ScopedObjectAccess soa(Thread::Current());
2661 return GetReferenceTypeInfo().IsStringClass();
2662}
2663
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002664bool HInvoke::NeedsEnvironment() const {
2665 if (!IsIntrinsic()) {
2666 return true;
2667 }
2668 IntrinsicOptimizations opt(*this);
2669 return !opt.GetDoesNotNeedEnvironment();
2670}
2671
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002672const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2673 ArtMethod* caller = GetEnvironment()->GetMethod();
2674 ScopedObjectAccess soa(Thread::Current());
2675 // `caller` is null for a top-level graph representing a method whose declaring
2676 // class was not resolved.
2677 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2678}
2679
Vladimir Markodc151b22015-10-15 18:02:30 +01002680bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002681 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002682 return false;
2683 }
2684 if (!IsIntrinsic()) {
2685 return true;
2686 }
2687 IntrinsicOptimizations opt(*this);
2688 return !opt.GetDoesNotNeedDexCache();
2689}
2690
Vladimir Markof64242a2015-12-01 14:58:23 +00002691std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2692 switch (rhs) {
2693 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002694 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002695 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002696 return os << "Recursive";
2697 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2698 return os << "BootImageLinkTimePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002699 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
Vladimir Marko19d7d502017-05-24 13:04:14 +01002700 return os << "DirectAddress";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002701 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2702 return os << "BssEntry";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002703 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2704 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002705 default:
2706 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2707 UNREACHABLE();
2708 }
2709}
2710
Vladimir Markofbb184a2015-11-13 14:47:00 +00002711std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2712 switch (rhs) {
2713 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2714 return os << "explicit";
2715 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2716 return os << "implicit";
2717 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2718 return os << "none";
2719 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002720 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2721 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002722 }
2723}
2724
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002725bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2726 const HLoadClass* other_load_class = other->AsLoadClass();
2727 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2728 // names rather than type indexes. However, we shall also have to re-think the hash code.
2729 if (type_index_ != other_load_class->type_index_ ||
2730 GetPackedFields() != other_load_class->GetPackedFields()) {
2731 return false;
2732 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002733 switch (GetLoadKind()) {
2734 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002735 case LoadKind::kJitTableAddress: {
2736 ScopedObjectAccess soa(Thread::Current());
2737 return GetClass().Get() == other_load_class->GetClass().Get();
2738 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002739 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002740 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002741 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002742 }
2743}
2744
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002745void HLoadClass::SetLoadKind(LoadKind load_kind) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002746 SetPackedField<LoadKindField>(load_kind);
2747
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002748 if (load_kind != LoadKind::kRuntimeCall &&
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002749 load_kind != LoadKind::kReferrersClass) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002750 RemoveAsUserOfInput(0u);
2751 SetRawInputAt(0u, nullptr);
2752 }
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002753
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002754 if (!NeedsEnvironment()) {
2755 RemoveEnvironment();
2756 SetSideEffects(SideEffects::None());
2757 }
2758}
2759
2760std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2761 switch (rhs) {
2762 case HLoadClass::LoadKind::kReferrersClass:
2763 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002764 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2765 return os << "BootImageLinkTimePcRelative";
2766 case HLoadClass::LoadKind::kBootImageAddress:
2767 return os << "BootImageAddress";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002768 case HLoadClass::LoadKind::kBssEntry:
2769 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002770 case HLoadClass::LoadKind::kJitTableAddress:
2771 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002772 case HLoadClass::LoadKind::kRuntimeCall:
2773 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002774 default:
2775 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2776 UNREACHABLE();
2777 }
2778}
2779
Vladimir Marko372f10e2016-05-17 16:30:10 +01002780bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2781 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002782 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2783 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002784 if (string_index_ != other_load_string->string_index_ ||
2785 GetPackedFields() != other_load_string->GetPackedFields()) {
2786 return false;
2787 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002788 switch (GetLoadKind()) {
2789 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002790 case LoadKind::kJitTableAddress: {
2791 ScopedObjectAccess soa(Thread::Current());
2792 return GetString().Get() == other_load_string->GetString().Get();
2793 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002794 default:
2795 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002796 }
2797}
2798
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002799void HLoadString::SetLoadKind(LoadKind load_kind) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002800 // Once sharpened, the load kind should not be changed again.
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002801 DCHECK_EQ(GetLoadKind(), LoadKind::kRuntimeCall);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002802 SetPackedField<LoadKindField>(load_kind);
2803
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002804 if (load_kind != LoadKind::kRuntimeCall) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002805 RemoveAsUserOfInput(0u);
2806 SetRawInputAt(0u, nullptr);
2807 }
2808 if (!NeedsEnvironment()) {
2809 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002810 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002811 }
2812}
2813
2814std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2815 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002816 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2817 return os << "BootImageLinkTimePcRelative";
2818 case HLoadString::LoadKind::kBootImageAddress:
2819 return os << "BootImageAddress";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002820 case HLoadString::LoadKind::kBssEntry:
2821 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002822 case HLoadString::LoadKind::kJitTableAddress:
2823 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002824 case HLoadString::LoadKind::kRuntimeCall:
2825 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002826 default:
2827 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2828 UNREACHABLE();
2829 }
2830}
2831
Mark Mendellc4701932015-04-10 13:18:51 -04002832void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002833 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2834 HEnvironment* user = use.GetUser();
2835 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002836 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002837 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002838}
2839
Roland Levillainc9b21f82016-03-23 16:36:59 +00002840// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002841HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2842 ArenaAllocator* allocator = GetArena();
2843
2844 if (cond->IsCondition() &&
2845 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2846 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2847 HInstruction* lhs = cond->InputAt(0);
2848 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002849 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002850 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2851 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2852 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2853 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2854 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2855 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2856 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2857 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2858 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2859 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2860 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002861 default:
2862 LOG(FATAL) << "Unexpected condition";
2863 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002864 }
2865 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2866 return replacement;
2867 } else if (cond->IsIntConstant()) {
2868 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002869 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002870 return GetIntConstant(1);
2871 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002872 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002873 return GetIntConstant(0);
2874 }
2875 } else {
2876 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2877 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2878 return replacement;
2879 }
2880}
2881
Roland Levillainc9285912015-12-18 10:38:42 +00002882std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2883 os << "["
2884 << " source=" << rhs.GetSource()
2885 << " destination=" << rhs.GetDestination()
2886 << " type=" << rhs.GetType()
2887 << " instruction=";
2888 if (rhs.GetInstruction() != nullptr) {
2889 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2890 } else {
2891 os << "null";
2892 }
2893 os << " ]";
2894 return os;
2895}
2896
Roland Levillain86503782016-02-11 19:07:30 +00002897std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2898 switch (rhs) {
2899 case TypeCheckKind::kUnresolvedCheck:
2900 return os << "unresolved_check";
2901 case TypeCheckKind::kExactCheck:
2902 return os << "exact_check";
2903 case TypeCheckKind::kClassHierarchyCheck:
2904 return os << "class_hierarchy_check";
2905 case TypeCheckKind::kAbstractClassCheck:
2906 return os << "abstract_class_check";
2907 case TypeCheckKind::kInterfaceCheck:
2908 return os << "interface_check";
2909 case TypeCheckKind::kArrayObjectCheck:
2910 return os << "array_object_check";
2911 case TypeCheckKind::kArrayCheck:
2912 return os << "array_check";
2913 default:
2914 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2915 UNREACHABLE();
2916 }
2917}
2918
Andreas Gampe26de38b2016-07-27 17:53:11 -07002919std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2920 switch (kind) {
2921 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002922 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002923 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002924 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002925 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002926 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002927 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002928 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002929 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002930 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002931
2932 default:
2933 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
2934 UNREACHABLE();
2935 }
2936}
2937
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002938} // namespace art