blob: f4d3842ff9c40e493e6aa7023d13019079f5d2a7 [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
Mark Mendelle82549b2015-05-06 10:55:34 -040020#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000021#include "common_dominator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010022#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010023#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010024#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010025#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010026#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010027#include "mirror/class-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000028#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000029
30namespace art {
31
Roland Levillain31dd3d62016-02-16 12:21:02 +000032// Enable floating-point static evaluation during constant folding
33// only if all floating-point operations and constants evaluate in the
34// range and precision of the type used (i.e., 32-bit float, 64-bit
35// double).
36static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
37
David Brazdilbadd8262016-02-02 16:28:56 +000038void HGraph::InitializeInexactObjectRTI(StackHandleScopeCollection* handles) {
39 ScopedObjectAccess soa(Thread::Current());
40 // Create the inexact Object reference type and store it in the HGraph.
41 ClassLinker* linker = Runtime::Current()->GetClassLinker();
42 inexact_object_rti_ = ReferenceTypeInfo::Create(
43 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
44 /* is_exact */ false);
45}
46
Nicolas Geoffray818f2102014-02-18 16:43:35 +000047void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010048 block->SetBlockId(blocks_.size());
49 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000050}
51
Nicolas Geoffray804d0932014-05-02 08:46:00 +010052void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010053 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
54 DCHECK_EQ(visited->GetHighestBitSet(), -1);
55
56 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markof6a35de2016-03-21 12:01:50 +000057 ArenaBitVector visiting(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010058 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +010059 ArenaVector<size_t> successors_visited(blocks_.size(),
60 0u,
61 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010062 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko3ea5a972016-05-09 20:23:34 +010063 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 constexpr size_t kDefaultWorklistSize = 8;
65 worklist.reserve(kDefaultWorklistSize);
66 visited->SetBit(entry_block_->GetBlockId());
67 visiting.SetBit(entry_block_->GetBlockId());
68 worklist.push_back(entry_block_);
69
70 while (!worklist.empty()) {
71 HBasicBlock* current = worklist.back();
72 uint32_t current_id = current->GetBlockId();
73 if (successors_visited[current_id] == current->GetSuccessors().size()) {
74 visiting.ClearBit(current_id);
75 worklist.pop_back();
76 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010077 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
78 uint32_t successor_id = successor->GetBlockId();
79 if (visiting.IsBitSet(successor_id)) {
80 DCHECK(ContainsElement(worklist, successor));
81 successor->AddBackEdge(current);
82 } else if (!visited->IsBitSet(successor_id)) {
83 visited->SetBit(successor_id);
84 visiting.SetBit(successor_id);
85 worklist.push_back(successor);
86 }
87 }
88 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000089}
90
Vladimir Markocac5a7e2016-02-22 10:39:50 +000091static void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010092 for (HEnvironment* environment = instruction->GetEnvironment();
93 environment != nullptr;
94 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000095 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000096 if (environment->GetInstructionAt(i) != nullptr) {
97 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000098 }
99 }
100 }
101}
102
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000103static void RemoveAsUser(HInstruction* instruction) {
104 for (size_t i = 0; i < instruction->InputCount(); i++) {
105 instruction->RemoveAsUserOfInput(i);
106 }
107
108 RemoveEnvironmentUses(instruction);
109}
110
Roland Levillainfc600dc2014-12-02 17:16:31 +0000111void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100112 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000113 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100114 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000115 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100116 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000117 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
118 RemoveAsUser(it.Current());
119 }
120 }
121 }
122}
123
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100124void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100125 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000126 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100127 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000128 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100129 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000130 for (HBasicBlock* successor : block->GetSuccessors()) {
131 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000132 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100133 // Remove the block from the list of blocks, so that further analyses
134 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100135 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600136 if (block->IsExitBlock()) {
137 SetExitBlock(nullptr);
138 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000139 // Mark the block as removed. This is used by the HGraphBuilder to discard
140 // the block as a branch target.
141 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000142 }
143 }
144}
145
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000146GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000147 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000148
David Brazdil86ea7ee2016-02-16 09:26:07 +0000149 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000150 FindBackEdges(&visited);
151
David Brazdil86ea7ee2016-02-16 09:26:07 +0000152 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000153 // the initial DFS as users from other instructions, so that
154 // users can be safely removed before uses later.
155 RemoveInstructionsAsUsersFromDeadBlocks(visited);
156
David Brazdil86ea7ee2016-02-16 09:26:07 +0000157 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000158 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000159 // predecessors list of live blocks.
160 RemoveDeadBlocks(visited);
161
David Brazdil86ea7ee2016-02-16 09:26:07 +0000162 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100163 // dominators and the reverse post order.
164 SimplifyCFG();
165
David Brazdil86ea7ee2016-02-16 09:26:07 +0000166 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100167 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000168
David Brazdil86ea7ee2016-02-16 09:26:07 +0000169 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000170 // set the loop information on each block.
171 GraphAnalysisResult result = AnalyzeLoops();
172 if (result != kAnalysisSuccess) {
173 return result;
174 }
175
David Brazdil86ea7ee2016-02-16 09:26:07 +0000176 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000177 // which needs the information to build catch block phis from values of
178 // locals at throwing instructions inside try blocks.
179 ComputeTryBlockInformation();
180
181 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100182}
183
184void HGraph::ClearDominanceInformation() {
185 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
186 it.Current()->ClearDominanceInformation();
187 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100188 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100189}
190
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000191void HGraph::ClearLoopInformation() {
192 SetHasIrreducibleLoops(false);
193 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000194 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000195 }
196}
197
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100198void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000199 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100200 dominator_ = nullptr;
201}
202
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000203HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
204 HInstruction* instruction = GetFirstInstruction();
205 while (instruction->IsParallelMove()) {
206 instruction = instruction->GetNext();
207 }
208 return instruction;
209}
210
David Brazdil3f4a5222016-05-06 12:46:21 +0100211static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
212 DCHECK(ContainsElement(block->GetSuccessors(), successor));
213
214 HBasicBlock* old_dominator = successor->GetDominator();
215 HBasicBlock* new_dominator =
216 (old_dominator == nullptr) ? block
217 : CommonDominator::ForPair(old_dominator, block);
218
219 if (old_dominator == new_dominator) {
220 return false;
221 } else {
222 successor->SetDominator(new_dominator);
223 return true;
224 }
225}
226
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100227void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100228 DCHECK(reverse_post_order_.empty());
229 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100230 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100231
232 // Number of visits of a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100233 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100234 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100235 ArenaVector<size_t> successors_visited(blocks_.size(),
236 0u,
237 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100238 // Nodes for which we need to visit successors.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100239 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100240 constexpr size_t kDefaultWorklistSize = 8;
241 worklist.reserve(kDefaultWorklistSize);
242 worklist.push_back(entry_block_);
243
244 while (!worklist.empty()) {
245 HBasicBlock* current = worklist.back();
246 uint32_t current_id = current->GetBlockId();
247 if (successors_visited[current_id] == current->GetSuccessors().size()) {
248 worklist.pop_back();
249 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100250 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100251 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100252
253 // Once all the forward edges have been visited, we know the immediate
254 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100255 if (++visits[successor->GetBlockId()] ==
256 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100257 reverse_post_order_.push_back(successor);
258 worklist.push_back(successor);
259 }
260 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000261 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000262
David Brazdil3f4a5222016-05-06 12:46:21 +0100263 // Check if the graph has back edges not dominated by their respective headers.
264 // If so, we need to update the dominators of those headers and recursively of
265 // their successors. We do that with a fix-point iteration over all blocks.
266 // The algorithm is guaranteed to terminate because it loops only if the sum
267 // of all dominator chains has decreased in the current iteration.
268 bool must_run_fix_point = false;
269 for (HBasicBlock* block : blocks_) {
270 if (block != nullptr &&
271 block->IsLoopHeader() &&
272 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
273 must_run_fix_point = true;
274 break;
275 }
276 }
277 if (must_run_fix_point) {
278 bool update_occurred = true;
279 while (update_occurred) {
280 update_occurred = false;
281 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
282 HBasicBlock* block = it.Current();
283 for (HBasicBlock* successor : block->GetSuccessors()) {
284 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
285 }
286 }
287 }
288 }
289
290 // Make sure that there are no remaining blocks whose dominator information
291 // needs to be updated.
292 if (kIsDebugBuild) {
293 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
294 HBasicBlock* block = it.Current();
295 for (HBasicBlock* successor : block->GetSuccessors()) {
296 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
297 }
298 }
299 }
300
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000301 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000302 // The potential presence of irreducible loops requires to do it after.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000303 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
304 HBasicBlock* block = it.Current();
305 if (!block->IsEntryBlock()) {
306 block->GetDominator()->AddDominatedBlock(block);
307 }
308 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000309}
310
David Brazdilfc6a86a2015-06-26 10:33:45 +0000311HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000312 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
313 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000314 // Use `InsertBetween` to ensure the predecessor index and successor index of
315 // `block` and `successor` are preserved.
316 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000317 return new_block;
318}
319
320void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
321 // Insert a new node between `block` and `successor` to split the
322 // critical edge.
323 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600324 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100325 if (successor->IsLoopHeader()) {
326 // If we split at a back edge boundary, make the new block the back edge.
327 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000328 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100329 info->RemoveBackEdge(block);
330 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100331 }
332 }
333}
334
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100335void HGraph::SimplifyLoop(HBasicBlock* header) {
336 HLoopInformation* info = header->GetLoopInformation();
337
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100338 // Make sure the loop has only one pre header. This simplifies SSA building by having
339 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000340 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
341 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000342 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000343 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100344 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100345 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600346 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100347
Vladimir Marko60584552015-09-03 13:35:12 +0000348 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100349 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100350 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100351 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100352 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100353 }
354 }
355 pre_header->AddSuccessor(header);
356 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100357
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100358 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100359 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
360 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000361 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100362 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100363 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000364 header->predecessors_[pred] = to_swap;
365 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100366 break;
367 }
368 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100369 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100370
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100371 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000372 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
373 // Called from DeadBlockElimination. Update SuspendCheck pointer.
374 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100375 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100376}
377
David Brazdilffee3d32015-07-06 11:48:53 +0100378void HGraph::ComputeTryBlockInformation() {
379 // Iterate in reverse post order to propagate try membership information from
380 // predecessors to their successors.
381 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
382 HBasicBlock* block = it.Current();
383 if (block->IsEntryBlock() || block->IsCatchBlock()) {
384 // Catch blocks after simplification have only exceptional predecessors
385 // and hence are never in tries.
386 continue;
387 }
388
389 // Infer try membership from the first predecessor. Having simplified loops,
390 // the first predecessor can never be a back edge and therefore it must have
391 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100392 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100393 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100394 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000395 if (try_entry != nullptr &&
396 (block->GetTryCatchInformation() == nullptr ||
397 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
398 // We are either setting try block membership for the first time or it
399 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100400 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
401 }
David Brazdilffee3d32015-07-06 11:48:53 +0100402 }
403}
404
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100405void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000406// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100407 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000408 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100409 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
410 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
411 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
412 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100413 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000414 if (block->GetSuccessors().size() > 1) {
415 // Only split normal-flow edges. We cannot split exceptional edges as they
416 // are synthesized (approximate real control flow), and we do not need to
417 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000418 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
419 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
420 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100421 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000422 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000423 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
424 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000425 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000426 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100427 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000428 // SplitCriticalEdge could have invalidated the `normal_successors`
429 // ArrayRef. We must re-acquire it.
430 normal_successors = block->GetNormalSuccessors();
431 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
432 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100433 }
434 }
435 }
436 if (block->IsLoopHeader()) {
437 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000438 } else if (!block->IsEntryBlock() &&
439 block->GetFirstInstruction() != nullptr &&
440 block->GetFirstInstruction()->IsSuspendCheck()) {
441 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000442 // a loop got dismantled. Just remove the suspend check.
443 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100444 }
445 }
446}
447
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000448GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100449 // We iterate post order to ensure we visit inner loops before outer loops.
450 // `PopulateRecursive` needs this guarantee to know whether a natural loop
451 // contains an irreducible loop.
452 for (HPostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100453 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100454 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100455 if (block->IsCatchBlock()) {
456 // TODO: Dealing with exceptional back edges could be tricky because
457 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000458 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100459 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000460 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100461 }
462 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000463 return kAnalysisSuccess;
464}
465
466void HLoopInformation::Dump(std::ostream& os) {
467 os << "header: " << header_->GetBlockId() << std::endl;
468 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
469 for (HBasicBlock* block : back_edges_) {
470 os << "back edge: " << block->GetBlockId() << std::endl;
471 }
472 for (HBasicBlock* block : header_->GetPredecessors()) {
473 os << "predecessor: " << block->GetBlockId() << std::endl;
474 }
475 for (uint32_t idx : blocks_.Indexes()) {
476 os << " in loop: " << idx << std::endl;
477 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100478}
479
David Brazdil8d5b8b22015-03-24 10:51:52 +0000480void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000481 // New constants are inserted before the SuspendCheck at the bottom of the
482 // entry block. Note that this method can be called from the graph builder and
483 // the entry block therefore may not end with SuspendCheck->Goto yet.
484 HInstruction* insert_before = nullptr;
485
486 HInstruction* gota = entry_block_->GetLastInstruction();
487 if (gota != nullptr && gota->IsGoto()) {
488 HInstruction* suspend_check = gota->GetPrevious();
489 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
490 insert_before = suspend_check;
491 } else {
492 insert_before = gota;
493 }
494 }
495
496 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000497 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000498 } else {
499 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000500 }
501}
502
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600503HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100504 // For simplicity, don't bother reviving the cached null constant if it is
505 // not null and not in a block. Otherwise, we need to clear the instruction
506 // id and/or any invariants the graph is assuming when adding new instructions.
507 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600508 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000509 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000510 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000511 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000512 if (kIsDebugBuild) {
513 ScopedObjectAccess soa(Thread::Current());
514 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
515 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000516 return cached_null_constant_;
517}
518
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100519HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100520 // For simplicity, don't bother reviving the cached current method if it is
521 // not null and not in a block. Otherwise, we need to clear the instruction
522 // id and/or any invariants the graph is assuming when adding new instructions.
523 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700524 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600525 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
526 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100527 if (entry_block_->GetFirstInstruction() == nullptr) {
528 entry_block_->AddInstruction(cached_current_method_);
529 } else {
530 entry_block_->InsertInstructionBefore(
531 cached_current_method_, entry_block_->GetFirstInstruction());
532 }
533 }
534 return cached_current_method_;
535}
536
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600537HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000538 switch (type) {
539 case Primitive::Type::kPrimBoolean:
540 DCHECK(IsUint<1>(value));
541 FALLTHROUGH_INTENDED;
542 case Primitive::Type::kPrimByte:
543 case Primitive::Type::kPrimChar:
544 case Primitive::Type::kPrimShort:
545 case Primitive::Type::kPrimInt:
546 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600547 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000548
549 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600550 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000551
552 default:
553 LOG(FATAL) << "Unsupported constant type";
554 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000555 }
David Brazdil46e2a392015-03-16 17:31:52 +0000556}
557
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000558void HGraph::CacheFloatConstant(HFloatConstant* constant) {
559 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
560 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
561 cached_float_constants_.Overwrite(value, constant);
562}
563
564void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
565 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
566 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
567 cached_double_constants_.Overwrite(value, constant);
568}
569
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000570void HLoopInformation::Add(HBasicBlock* block) {
571 blocks_.SetBit(block->GetBlockId());
572}
573
David Brazdil46e2a392015-03-16 17:31:52 +0000574void HLoopInformation::Remove(HBasicBlock* block) {
575 blocks_.ClearBit(block->GetBlockId());
576}
577
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100578void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
579 if (blocks_.IsBitSet(block->GetBlockId())) {
580 return;
581 }
582
583 blocks_.SetBit(block->GetBlockId());
584 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100585 if (block->IsLoopHeader()) {
586 // We're visiting loops in post-order, so inner loops must have been
587 // populated already.
588 DCHECK(block->GetLoopInformation()->IsPopulated());
589 if (block->GetLoopInformation()->IsIrreducible()) {
590 contains_irreducible_loop_ = true;
591 }
592 }
Vladimir Marko60584552015-09-03 13:35:12 +0000593 for (HBasicBlock* predecessor : block->GetPredecessors()) {
594 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100595 }
596}
597
David Brazdilc2e8af92016-04-05 17:15:19 +0100598void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
599 size_t block_id = block->GetBlockId();
600
601 // If `block` is in `finalized`, we know its membership in the loop has been
602 // decided and it does not need to be revisited.
603 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000604 return;
605 }
606
David Brazdilc2e8af92016-04-05 17:15:19 +0100607 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000608 if (block->IsLoopHeader()) {
609 // If we hit a loop header in an irreducible loop, we first check if the
610 // pre header of that loop belongs to the currently analyzed loop. If it does,
611 // then we visit the back edges.
612 // Note that we cannot use GetPreHeader, as the loop may have not been populated
613 // yet.
614 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100615 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000616 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000617 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100618 blocks_.SetBit(block_id);
619 finalized->SetBit(block_id);
620 is_finalized = true;
621
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000622 HLoopInformation* info = block->GetLoopInformation();
623 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100624 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000625 }
626 }
627 } else {
628 // Visit all predecessors. If one predecessor is part of the loop, this
629 // block is also part of this loop.
630 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100631 PopulateIrreducibleRecursive(predecessor, finalized);
632 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000633 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100634 blocks_.SetBit(block_id);
635 finalized->SetBit(block_id);
636 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000637 }
638 }
639 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100640
641 // All predecessors have been recursively visited. Mark finalized if not marked yet.
642 if (!is_finalized) {
643 finalized->SetBit(block_id);
644 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000645}
646
647void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100648 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000649 // Populate this loop: starting with the back edge, recursively add predecessors
650 // that are not already part of that loop. Set the header as part of the loop
651 // to end the recursion.
652 // This is a recursive implementation of the algorithm described in
653 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100654 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000655 blocks_.SetBit(header_->GetBlockId());
656 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100657
David Brazdil3f4a5222016-05-06 12:46:21 +0100658 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100659
660 if (is_irreducible_loop) {
661 ArenaBitVector visited(graph->GetArena(),
662 graph->GetBlocks().size(),
663 /* expandable */ false,
664 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100665 // Stop marking blocks at the loop header.
666 visited.SetBit(header_->GetBlockId());
667
David Brazdilc2e8af92016-04-05 17:15:19 +0100668 for (HBasicBlock* back_edge : GetBackEdges()) {
669 PopulateIrreducibleRecursive(back_edge, &visited);
670 }
671 } else {
672 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000673 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100674 }
David Brazdila4b8c212015-05-07 09:59:30 +0100675 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100676
Vladimir Markofd66c502016-04-18 15:37:01 +0100677 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
678 // When compiling in OSR mode, all loops in the compiled method may be entered
679 // from the interpreter. We treat this OSR entry point just like an extra entry
680 // to an irreducible loop, so we need to mark the method's loops as irreducible.
681 // This does not apply to inlined loops which do not act as OSR entry points.
682 if (suspend_check_ == nullptr) {
683 // Just building the graph in OSR mode, this loop is not inlined. We never build an
684 // inner graph in OSR mode as we can do OSR transition only from the outer method.
685 is_irreducible_loop = true;
686 } else {
687 // Look at the suspend check's environment to determine if the loop was inlined.
688 DCHECK(suspend_check_->HasEnvironment());
689 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
690 is_irreducible_loop = true;
691 }
692 }
693 }
694 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100695 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100696 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100697 graph->SetHasIrreducibleLoops(true);
698 }
David Brazdila4b8c212015-05-07 09:59:30 +0100699}
700
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100701HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000702 HBasicBlock* block = header_->GetPredecessors()[0];
703 DCHECK(irreducible_ || (block == header_->GetDominator()));
704 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100705}
706
707bool HLoopInformation::Contains(const HBasicBlock& block) const {
708 return blocks_.IsBitSet(block.GetBlockId());
709}
710
711bool HLoopInformation::IsIn(const HLoopInformation& other) const {
712 return other.blocks_.IsBitSet(header_->GetBlockId());
713}
714
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800715bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
716 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700717}
718
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100719size_t HLoopInformation::GetLifetimeEnd() const {
720 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100721 for (HBasicBlock* back_edge : GetBackEdges()) {
722 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100723 }
724 return last_position;
725}
726
David Brazdil3f4a5222016-05-06 12:46:21 +0100727bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
728 for (HBasicBlock* back_edge : GetBackEdges()) {
729 DCHECK(back_edge->GetDominator() != nullptr);
730 if (!header_->Dominates(back_edge)) {
731 return true;
732 }
733 }
734 return false;
735}
736
Anton Shaminf89381f2016-05-16 16:44:13 +0600737bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
738 for (HBasicBlock* back_edge : GetBackEdges()) {
739 if (!block->Dominates(back_edge)) {
740 return false;
741 }
742 }
743 return true;
744}
745
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100746bool HBasicBlock::Dominates(HBasicBlock* other) const {
747 // Walk up the dominator tree from `other`, to find out if `this`
748 // is an ancestor.
749 HBasicBlock* current = other;
750 while (current != nullptr) {
751 if (current == this) {
752 return true;
753 }
754 current = current->GetDominator();
755 }
756 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100757}
758
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100759static void UpdateInputsUsers(HInstruction* instruction) {
760 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
761 instruction->InputAt(i)->AddUseAt(instruction, i);
762 }
763 // Environment should be created later.
764 DCHECK(!instruction->HasEnvironment());
765}
766
Roland Levillainccc07a92014-09-16 14:48:16 +0100767void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
768 HInstruction* replacement) {
769 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400770 if (initial->IsControlFlow()) {
771 // We can only replace a control flow instruction with another control flow instruction.
772 DCHECK(replacement->IsControlFlow());
773 DCHECK_EQ(replacement->GetId(), -1);
774 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
775 DCHECK_EQ(initial->GetBlock(), this);
776 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100777 DCHECK(initial->GetUses().empty());
778 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400779 replacement->SetBlock(this);
780 replacement->SetId(GetGraph()->GetNextInstructionId());
781 instructions_.InsertInstructionBefore(replacement, initial);
782 UpdateInputsUsers(replacement);
783 } else {
784 InsertInstructionBefore(replacement, initial);
785 initial->ReplaceWith(replacement);
786 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100787 RemoveInstruction(initial);
788}
789
David Brazdil74eb1b22015-12-14 11:44:01 +0000790void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
791 DCHECK(!cursor->IsPhi());
792 DCHECK(!insn->IsPhi());
793 DCHECK(!insn->IsControlFlow());
794 DCHECK(insn->CanBeMoved());
795 DCHECK(!insn->HasSideEffects());
796
797 HBasicBlock* from_block = insn->GetBlock();
798 HBasicBlock* to_block = cursor->GetBlock();
799 DCHECK(from_block != to_block);
800
801 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
802 insn->SetBlock(to_block);
803 to_block->instructions_.InsertInstructionBefore(insn, cursor);
804}
805
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100806static void Add(HInstructionList* instruction_list,
807 HBasicBlock* block,
808 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000809 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000810 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100811 instruction->SetBlock(block);
812 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100813 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100814 instruction_list->AddInstruction(instruction);
815}
816
817void HBasicBlock::AddInstruction(HInstruction* instruction) {
818 Add(&instructions_, this, instruction);
819}
820
821void HBasicBlock::AddPhi(HPhi* phi) {
822 Add(&phis_, this, phi);
823}
824
David Brazdilc3d743f2015-04-22 13:40:50 +0100825void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
826 DCHECK(!cursor->IsPhi());
827 DCHECK(!instruction->IsPhi());
828 DCHECK_EQ(instruction->GetId(), -1);
829 DCHECK_NE(cursor->GetId(), -1);
830 DCHECK_EQ(cursor->GetBlock(), this);
831 DCHECK(!instruction->IsControlFlow());
832 instruction->SetBlock(this);
833 instruction->SetId(GetGraph()->GetNextInstructionId());
834 UpdateInputsUsers(instruction);
835 instructions_.InsertInstructionBefore(instruction, cursor);
836}
837
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100838void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
839 DCHECK(!cursor->IsPhi());
840 DCHECK(!instruction->IsPhi());
841 DCHECK_EQ(instruction->GetId(), -1);
842 DCHECK_NE(cursor->GetId(), -1);
843 DCHECK_EQ(cursor->GetBlock(), this);
844 DCHECK(!instruction->IsControlFlow());
845 DCHECK(!cursor->IsControlFlow());
846 instruction->SetBlock(this);
847 instruction->SetId(GetGraph()->GetNextInstructionId());
848 UpdateInputsUsers(instruction);
849 instructions_.InsertInstructionAfter(instruction, cursor);
850}
851
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100852void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
853 DCHECK_EQ(phi->GetId(), -1);
854 DCHECK_NE(cursor->GetId(), -1);
855 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100856 phi->SetBlock(this);
857 phi->SetId(GetGraph()->GetNextInstructionId());
858 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100859 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100860}
861
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100862static void Remove(HInstructionList* instruction_list,
863 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000864 HInstruction* instruction,
865 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100866 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100867 instruction->SetBlock(nullptr);
868 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000869 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100870 DCHECK(instruction->GetUses().empty());
871 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000872 RemoveAsUser(instruction);
873 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100874}
875
David Brazdil1abb4192015-02-17 18:33:36 +0000876void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100877 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000878 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100879}
880
David Brazdil1abb4192015-02-17 18:33:36 +0000881void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
882 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100883}
884
David Brazdilc7508e92015-04-27 13:28:57 +0100885void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
886 if (instruction->IsPhi()) {
887 RemovePhi(instruction->AsPhi(), ensure_safety);
888 } else {
889 RemoveInstruction(instruction, ensure_safety);
890 }
891}
892
Vladimir Marko71bf8092015-09-15 15:33:14 +0100893void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
894 for (size_t i = 0; i < locals.size(); i++) {
895 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100896 SetRawEnvAt(i, instruction);
897 if (instruction != nullptr) {
898 instruction->AddEnvUseAt(this, i);
899 }
900 }
901}
902
David Brazdiled596192015-01-23 10:39:45 +0000903void HEnvironment::CopyFrom(HEnvironment* env) {
904 for (size_t i = 0; i < env->Size(); i++) {
905 HInstruction* instruction = env->GetInstructionAt(i);
906 SetRawEnvAt(i, instruction);
907 if (instruction != nullptr) {
908 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100909 }
David Brazdiled596192015-01-23 10:39:45 +0000910 }
911}
912
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700913void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
914 HBasicBlock* loop_header) {
915 DCHECK(loop_header->IsLoopHeader());
916 for (size_t i = 0; i < env->Size(); i++) {
917 HInstruction* instruction = env->GetInstructionAt(i);
918 SetRawEnvAt(i, instruction);
919 if (instruction == nullptr) {
920 continue;
921 }
922 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
923 // At the end of the loop pre-header, the corresponding value for instruction
924 // is the first input of the phi.
925 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700926 SetRawEnvAt(i, initial);
927 initial->AddEnvUseAt(this, i);
928 } else {
929 instruction->AddEnvUseAt(this, i);
930 }
931 }
932}
933
David Brazdil1abb4192015-02-17 18:33:36 +0000934void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100935 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
936 HInstruction* user = env_use.GetInstruction();
937 auto before_env_use_node = env_use.GetBeforeUseNode();
938 user->env_uses_.erase_after(before_env_use_node);
939 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100940}
941
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000942HInstruction::InstructionKind HInstruction::GetKind() const {
943 return GetKindInternal();
944}
945
Calin Juravle77520bc2015-01-12 18:45:46 +0000946HInstruction* HInstruction::GetNextDisregardingMoves() const {
947 HInstruction* next = GetNext();
948 while (next != nullptr && next->IsParallelMove()) {
949 next = next->GetNext();
950 }
951 return next;
952}
953
954HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
955 HInstruction* previous = GetPrevious();
956 while (previous != nullptr && previous->IsParallelMove()) {
957 previous = previous->GetPrevious();
958 }
959 return previous;
960}
961
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100962void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000963 if (first_instruction_ == nullptr) {
964 DCHECK(last_instruction_ == nullptr);
965 first_instruction_ = last_instruction_ = instruction;
966 } else {
967 last_instruction_->next_ = instruction;
968 instruction->previous_ = last_instruction_;
969 last_instruction_ = instruction;
970 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000971}
972
David Brazdilc3d743f2015-04-22 13:40:50 +0100973void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
974 DCHECK(Contains(cursor));
975 if (cursor == first_instruction_) {
976 cursor->previous_ = instruction;
977 instruction->next_ = cursor;
978 first_instruction_ = instruction;
979 } else {
980 instruction->previous_ = cursor->previous_;
981 instruction->next_ = cursor;
982 cursor->previous_ = instruction;
983 instruction->previous_->next_ = instruction;
984 }
985}
986
987void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
988 DCHECK(Contains(cursor));
989 if (cursor == last_instruction_) {
990 cursor->next_ = instruction;
991 instruction->previous_ = cursor;
992 last_instruction_ = instruction;
993 } else {
994 instruction->next_ = cursor->next_;
995 instruction->previous_ = cursor;
996 cursor->next_ = instruction;
997 instruction->next_->previous_ = instruction;
998 }
999}
1000
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001001void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1002 if (instruction->previous_ != nullptr) {
1003 instruction->previous_->next_ = instruction->next_;
1004 }
1005 if (instruction->next_ != nullptr) {
1006 instruction->next_->previous_ = instruction->previous_;
1007 }
1008 if (instruction == first_instruction_) {
1009 first_instruction_ = instruction->next_;
1010 }
1011 if (instruction == last_instruction_) {
1012 last_instruction_ = instruction->previous_;
1013 }
1014}
1015
Roland Levillain6b469232014-09-25 10:10:38 +01001016bool HInstructionList::Contains(HInstruction* instruction) const {
1017 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1018 if (it.Current() == instruction) {
1019 return true;
1020 }
1021 }
1022 return false;
1023}
1024
Roland Levillainccc07a92014-09-16 14:48:16 +01001025bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1026 const HInstruction* instruction2) const {
1027 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1028 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1029 if (it.Current() == instruction1) {
1030 return true;
1031 }
1032 if (it.Current() == instruction2) {
1033 return false;
1034 }
1035 }
1036 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1037 return true;
1038}
1039
Roland Levillain6c82d402014-10-13 16:10:27 +01001040bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1041 if (other_instruction == this) {
1042 // An instruction does not strictly dominate itself.
1043 return false;
1044 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001045 HBasicBlock* block = GetBlock();
1046 HBasicBlock* other_block = other_instruction->GetBlock();
1047 if (block != other_block) {
1048 return GetBlock()->Dominates(other_instruction->GetBlock());
1049 } else {
1050 // If both instructions are in the same block, ensure this
1051 // instruction comes before `other_instruction`.
1052 if (IsPhi()) {
1053 if (!other_instruction->IsPhi()) {
1054 // Phis appear before non phi-instructions so this instruction
1055 // dominates `other_instruction`.
1056 return true;
1057 } else {
1058 // There is no order among phis.
1059 LOG(FATAL) << "There is no dominance between phis of a same block.";
1060 return false;
1061 }
1062 } else {
1063 // `this` is not a phi.
1064 if (other_instruction->IsPhi()) {
1065 // Phis appear before non phi-instructions so this instruction
1066 // does not dominate `other_instruction`.
1067 return false;
1068 } else {
1069 // Check whether this instruction comes before
1070 // `other_instruction` in the instruction list.
1071 return block->GetInstructions().FoundBefore(this, other_instruction);
1072 }
1073 }
1074 }
1075}
1076
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001077void HInstruction::RemoveEnvironment() {
1078 RemoveEnvironmentUses(this);
1079 environment_ = nullptr;
1080}
1081
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001082void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001083 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001084 // Note: fixup_end remains valid across splice_after().
1085 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1086 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1087 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001088
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001089 // Note: env_fixup_end remains valid across splice_after().
1090 auto env_fixup_end =
1091 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1092 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1093 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001094
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001095 DCHECK(uses_.empty());
1096 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001097}
1098
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001099void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001100 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001101 if (input_use.GetInstruction() == replacement) {
1102 // Nothing to do.
1103 return;
1104 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001105 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001106 // Note: fixup_end remains valid across splice_after().
1107 auto fixup_end =
1108 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1109 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1110 input_use.GetInstruction()->uses_,
1111 before_use_node);
1112 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1113 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001114}
1115
Nicolas Geoffray39468442014-09-02 15:17:15 +01001116size_t HInstruction::EnvironmentSize() const {
1117 return HasEnvironment() ? environment_->Size() : 0;
1118}
1119
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001120void HPhi::AddInput(HInstruction* input) {
1121 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001122 inputs_.push_back(HUserRecord<HInstruction*>(input));
1123 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001124}
1125
David Brazdil2d7352b2015-04-20 14:52:42 +01001126void HPhi::RemoveInputAt(size_t index) {
1127 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001128 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001129 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001130 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001131 InputRecordAt(i).GetUseNode()->SetIndex(i);
1132 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001133}
1134
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001135#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001136void H##name::Accept(HGraphVisitor* visitor) { \
1137 visitor->Visit##name(this); \
1138}
1139
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001140FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001141
1142#undef DEFINE_ACCEPT
1143
1144void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001145 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1146 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001147 if (block != nullptr) {
1148 VisitBasicBlock(block);
1149 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001150 }
1151}
1152
Roland Levillain633021e2014-10-01 14:12:25 +01001153void HGraphVisitor::VisitReversePostOrder() {
1154 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1155 VisitBasicBlock(it.Current());
1156 }
1157}
1158
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001159void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001160 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001161 it.Current()->Accept(this);
1162 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001163 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001164 it.Current()->Accept(this);
1165 }
1166}
1167
Mark Mendelle82549b2015-05-06 10:55:34 -04001168HConstant* HTypeConversion::TryStaticEvaluation() const {
1169 HGraph* graph = GetBlock()->GetGraph();
1170 if (GetInput()->IsIntConstant()) {
1171 int32_t value = GetInput()->AsIntConstant()->GetValue();
1172 switch (GetResultType()) {
1173 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001174 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001175 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001176 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001177 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001178 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001179 default:
1180 return nullptr;
1181 }
1182 } else if (GetInput()->IsLongConstant()) {
1183 int64_t value = GetInput()->AsLongConstant()->GetValue();
1184 switch (GetResultType()) {
1185 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001186 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001187 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001188 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001189 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001190 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001191 default:
1192 return nullptr;
1193 }
1194 } else if (GetInput()->IsFloatConstant()) {
1195 float value = GetInput()->AsFloatConstant()->GetValue();
1196 switch (GetResultType()) {
1197 case Primitive::kPrimInt:
1198 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001199 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001200 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001201 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001202 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001203 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1204 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001205 case Primitive::kPrimLong:
1206 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001207 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001208 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001209 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001210 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001211 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1212 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001213 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001214 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001215 default:
1216 return nullptr;
1217 }
1218 } else if (GetInput()->IsDoubleConstant()) {
1219 double value = GetInput()->AsDoubleConstant()->GetValue();
1220 switch (GetResultType()) {
1221 case Primitive::kPrimInt:
1222 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001223 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001224 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001225 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001226 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001227 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1228 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001229 case Primitive::kPrimLong:
1230 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001231 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001232 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001233 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001234 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001235 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1236 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001237 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001238 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001239 default:
1240 return nullptr;
1241 }
1242 }
1243 return nullptr;
1244}
1245
Roland Levillain9240d6a2014-10-20 16:47:04 +01001246HConstant* HUnaryOperation::TryStaticEvaluation() const {
1247 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001248 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001249 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001250 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001251 } else if (kEnableFloatingPointStaticEvaluation) {
1252 if (GetInput()->IsFloatConstant()) {
1253 return Evaluate(GetInput()->AsFloatConstant());
1254 } else if (GetInput()->IsDoubleConstant()) {
1255 return Evaluate(GetInput()->AsDoubleConstant());
1256 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001257 }
1258 return nullptr;
1259}
1260
1261HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001262 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1263 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001264 } else if (GetLeft()->IsLongConstant()) {
1265 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001266 // The binop(long, int) case is only valid for shifts and rotations.
1267 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001268 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1269 } else if (GetRight()->IsLongConstant()) {
1270 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001271 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001272 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001273 // The binop(null, null) case is only valid for equal and not-equal conditions.
1274 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001275 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001276 } else if (kEnableFloatingPointStaticEvaluation) {
1277 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1278 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1279 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1280 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1281 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001282 }
1283 return nullptr;
1284}
Dave Allison20dfc792014-06-16 20:44:29 -07001285
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001286HConstant* HBinaryOperation::GetConstantRight() const {
1287 if (GetRight()->IsConstant()) {
1288 return GetRight()->AsConstant();
1289 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1290 return GetLeft()->AsConstant();
1291 } else {
1292 return nullptr;
1293 }
1294}
1295
1296// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001297// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001298HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1299 HInstruction* most_constant_right = GetConstantRight();
1300 if (most_constant_right == nullptr) {
1301 return nullptr;
1302 } else if (most_constant_right == GetLeft()) {
1303 return GetRight();
1304 } else {
1305 return GetLeft();
1306 }
1307}
1308
Roland Levillain31dd3d62016-02-16 12:21:02 +00001309std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1310 switch (rhs) {
1311 case ComparisonBias::kNoBias:
1312 return os << "no_bias";
1313 case ComparisonBias::kGtBias:
1314 return os << "gt_bias";
1315 case ComparisonBias::kLtBias:
1316 return os << "lt_bias";
1317 default:
1318 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1319 UNREACHABLE();
1320 }
1321}
1322
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001323bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1324 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001325}
1326
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001327bool HInstruction::Equals(HInstruction* other) const {
1328 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001329 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001330 if (!InstructionDataEquals(other)) return false;
1331 if (GetType() != other->GetType()) return false;
1332 if (InputCount() != other->InputCount()) return false;
1333
1334 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1335 if (InputAt(i) != other->InputAt(i)) return false;
1336 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001337 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001338 return true;
1339}
1340
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001341std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1342#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1343 switch (rhs) {
1344 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1345 default:
1346 os << "Unknown instruction kind " << static_cast<int>(rhs);
1347 break;
1348 }
1349#undef DECLARE_CASE
1350 return os;
1351}
1352
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001353void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001354 next_->previous_ = previous_;
1355 if (previous_ != nullptr) {
1356 previous_->next_ = next_;
1357 }
1358 if (block_->instructions_.first_instruction_ == this) {
1359 block_->instructions_.first_instruction_ = next_;
1360 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001361 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001362
1363 previous_ = cursor->previous_;
1364 if (previous_ != nullptr) {
1365 previous_->next_ = this;
1366 }
1367 next_ = cursor;
1368 cursor->previous_ = this;
1369 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001370
1371 if (block_->instructions_.first_instruction_ == cursor) {
1372 block_->instructions_.first_instruction_ = this;
1373 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001374}
1375
Vladimir Markofb337ea2015-11-25 15:25:10 +00001376void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1377 DCHECK(!CanThrow());
1378 DCHECK(!HasSideEffects());
1379 DCHECK(!HasEnvironmentUses());
1380 DCHECK(HasNonEnvironmentUses());
1381 DCHECK(!IsPhi()); // Makes no sense for Phi.
1382 DCHECK_EQ(InputCount(), 0u);
1383
1384 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001385 auto uses_it = GetUses().begin();
1386 auto uses_end = GetUses().end();
1387 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1388 ++uses_it;
1389 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1390 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001391 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001392 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001393 // This instruction has uses in two or more blocks. Find the common dominator.
1394 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001395 for (; uses_it != uses_end; ++uses_it) {
1396 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001397 }
1398 target_block = finder.Get();
1399 DCHECK(target_block != nullptr);
1400 }
1401 // Move to the first dominator not in a loop.
1402 while (target_block->IsInLoop()) {
1403 target_block = target_block->GetDominator();
1404 DCHECK(target_block != nullptr);
1405 }
1406
1407 // Find insertion position.
1408 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001409 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1410 if (use.GetUser()->GetBlock() == target_block &&
1411 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1412 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001413 }
1414 }
1415 if (insert_pos == nullptr) {
1416 // No user in `target_block`, insert before the control flow instruction.
1417 insert_pos = target_block->GetLastInstruction();
1418 DCHECK(insert_pos->IsControlFlow());
1419 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1420 if (insert_pos->IsIf()) {
1421 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1422 if (if_input == insert_pos->GetPrevious()) {
1423 insert_pos = if_input;
1424 }
1425 }
1426 }
1427 MoveBefore(insert_pos);
1428}
1429
David Brazdilfc6a86a2015-06-26 10:33:45 +00001430HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001431 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001432 DCHECK_EQ(cursor->GetBlock(), this);
1433
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001434 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1435 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001436 new_block->instructions_.first_instruction_ = cursor;
1437 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1438 instructions_.last_instruction_ = cursor->previous_;
1439 if (cursor->previous_ == nullptr) {
1440 instructions_.first_instruction_ = nullptr;
1441 } else {
1442 cursor->previous_->next_ = nullptr;
1443 cursor->previous_ = nullptr;
1444 }
1445
1446 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001447 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001448
Vladimir Marko60584552015-09-03 13:35:12 +00001449 for (HBasicBlock* successor : GetSuccessors()) {
1450 new_block->successors_.push_back(successor);
1451 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001452 }
Vladimir Marko60584552015-09-03 13:35:12 +00001453 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001454 AddSuccessor(new_block);
1455
David Brazdil56e1acc2015-06-30 15:41:36 +01001456 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001457 return new_block;
1458}
1459
David Brazdild7558da2015-09-22 13:04:14 +01001460HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001461 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001462 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1463
1464 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1465
1466 for (HBasicBlock* predecessor : GetPredecessors()) {
1467 new_block->predecessors_.push_back(predecessor);
1468 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1469 }
1470 predecessors_.clear();
1471 AddPredecessor(new_block);
1472
1473 GetGraph()->AddBlock(new_block);
1474 return new_block;
1475}
1476
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001477HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1478 DCHECK_EQ(cursor->GetBlock(), this);
1479
1480 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1481 cursor->GetDexPc());
1482 new_block->instructions_.first_instruction_ = cursor;
1483 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1484 instructions_.last_instruction_ = cursor->previous_;
1485 if (cursor->previous_ == nullptr) {
1486 instructions_.first_instruction_ = nullptr;
1487 } else {
1488 cursor->previous_->next_ = nullptr;
1489 cursor->previous_ = nullptr;
1490 }
1491
1492 new_block->instructions_.SetBlockOfInstructions(new_block);
1493
1494 for (HBasicBlock* successor : GetSuccessors()) {
1495 new_block->successors_.push_back(successor);
1496 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1497 }
1498 successors_.clear();
1499
1500 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1501 dominated->dominator_ = new_block;
1502 new_block->dominated_blocks_.push_back(dominated);
1503 }
1504 dominated_blocks_.clear();
1505 return new_block;
1506}
1507
1508HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001509 DCHECK(!cursor->IsControlFlow());
1510 DCHECK_NE(instructions_.last_instruction_, cursor);
1511 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001512
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001513 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1514 new_block->instructions_.first_instruction_ = cursor->GetNext();
1515 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1516 cursor->next_->previous_ = nullptr;
1517 cursor->next_ = nullptr;
1518 instructions_.last_instruction_ = cursor;
1519
1520 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001521 for (HBasicBlock* successor : GetSuccessors()) {
1522 new_block->successors_.push_back(successor);
1523 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001524 }
Vladimir Marko60584552015-09-03 13:35:12 +00001525 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001526
Vladimir Marko60584552015-09-03 13:35:12 +00001527 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001528 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001529 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001530 }
Vladimir Marko60584552015-09-03 13:35:12 +00001531 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001532 return new_block;
1533}
1534
David Brazdilec16f792015-08-19 15:04:01 +01001535const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001536 if (EndsWithTryBoundary()) {
1537 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1538 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001539 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001540 return try_boundary;
1541 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001542 DCHECK(IsTryBlock());
1543 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001544 return nullptr;
1545 }
David Brazdilec16f792015-08-19 15:04:01 +01001546 } else if (IsTryBlock()) {
1547 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001548 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001549 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001550 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001551}
1552
David Brazdild7558da2015-09-22 13:04:14 +01001553bool HBasicBlock::HasThrowingInstructions() const {
1554 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1555 if (it.Current()->CanThrow()) {
1556 return true;
1557 }
1558 }
1559 return false;
1560}
1561
David Brazdilfc6a86a2015-06-26 10:33:45 +00001562static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1563 return block.GetPhis().IsEmpty()
1564 && !block.GetInstructions().IsEmpty()
1565 && block.GetFirstInstruction() == block.GetLastInstruction();
1566}
1567
David Brazdil46e2a392015-03-16 17:31:52 +00001568bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001569 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1570}
1571
1572bool HBasicBlock::IsSingleTryBoundary() const {
1573 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001574}
1575
David Brazdil8d5b8b22015-03-24 10:51:52 +00001576bool HBasicBlock::EndsWithControlFlowInstruction() const {
1577 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1578}
1579
David Brazdilb2bd1c52015-03-25 11:17:37 +00001580bool HBasicBlock::EndsWithIf() const {
1581 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1582}
1583
David Brazdilffee3d32015-07-06 11:48:53 +01001584bool HBasicBlock::EndsWithTryBoundary() const {
1585 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1586}
1587
David Brazdilb2bd1c52015-03-25 11:17:37 +00001588bool HBasicBlock::HasSinglePhi() const {
1589 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1590}
1591
David Brazdild26a4112015-11-10 11:07:31 +00001592ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1593 if (EndsWithTryBoundary()) {
1594 // The normal-flow successor of HTryBoundary is always stored at index zero.
1595 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1596 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1597 } else {
1598 // All successors of blocks not ending with TryBoundary are normal.
1599 return ArrayRef<HBasicBlock* const>(successors_);
1600 }
1601}
1602
1603ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1604 if (EndsWithTryBoundary()) {
1605 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1606 } else {
1607 // Blocks not ending with TryBoundary do not have exceptional successors.
1608 return ArrayRef<HBasicBlock* const>();
1609 }
1610}
1611
David Brazdilffee3d32015-07-06 11:48:53 +01001612bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001613 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1614 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1615
1616 size_t length = handlers1.size();
1617 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001618 return false;
1619 }
1620
David Brazdilb618ade2015-07-29 10:31:29 +01001621 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001622 for (size_t i = 0; i < length; ++i) {
1623 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001624 return false;
1625 }
1626 }
1627 return true;
1628}
1629
David Brazdil2d7352b2015-04-20 14:52:42 +01001630size_t HInstructionList::CountSize() const {
1631 size_t size = 0;
1632 HInstruction* current = first_instruction_;
1633 for (; current != nullptr; current = current->GetNext()) {
1634 size++;
1635 }
1636 return size;
1637}
1638
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001639void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1640 for (HInstruction* current = first_instruction_;
1641 current != nullptr;
1642 current = current->GetNext()) {
1643 current->SetBlock(block);
1644 }
1645}
1646
1647void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1648 DCHECK(Contains(cursor));
1649 if (!instruction_list.IsEmpty()) {
1650 if (cursor == last_instruction_) {
1651 last_instruction_ = instruction_list.last_instruction_;
1652 } else {
1653 cursor->next_->previous_ = instruction_list.last_instruction_;
1654 }
1655 instruction_list.last_instruction_->next_ = cursor->next_;
1656 cursor->next_ = instruction_list.first_instruction_;
1657 instruction_list.first_instruction_->previous_ = cursor;
1658 }
1659}
1660
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001661void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1662 DCHECK(Contains(cursor));
1663 if (!instruction_list.IsEmpty()) {
1664 if (cursor == first_instruction_) {
1665 first_instruction_ = instruction_list.first_instruction_;
1666 } else {
1667 cursor->previous_->next_ = instruction_list.first_instruction_;
1668 }
1669 instruction_list.last_instruction_->next_ = cursor;
1670 instruction_list.first_instruction_->previous_ = cursor->previous_;
1671 cursor->previous_ = instruction_list.last_instruction_;
1672 }
1673}
1674
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001675void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001676 if (IsEmpty()) {
1677 first_instruction_ = instruction_list.first_instruction_;
1678 last_instruction_ = instruction_list.last_instruction_;
1679 } else {
1680 AddAfter(last_instruction_, instruction_list);
1681 }
1682}
1683
David Brazdil04ff4e82015-12-10 13:54:52 +00001684// Should be called on instructions in a dead block in post order. This method
1685// assumes `insn` has been removed from all users with the exception of catch
1686// phis because of missing exceptional edges in the graph. It removes the
1687// instruction from catch phi uses, together with inputs of other catch phis in
1688// the catch block at the same index, as these must be dead too.
1689static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1690 DCHECK(!insn->HasEnvironmentUses());
1691 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001692 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1693 size_t use_index = use.GetIndex();
1694 HBasicBlock* user_block = use.GetUser()->GetBlock();
1695 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001696 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1697 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1698 }
1699 }
1700}
1701
David Brazdil2d7352b2015-04-20 14:52:42 +01001702void HBasicBlock::DisconnectAndDelete() {
1703 // Dominators must be removed after all the blocks they dominate. This way
1704 // a loop header is removed last, a requirement for correct loop information
1705 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001706 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001707
David Brazdil9eeebf62016-03-24 11:18:15 +00001708 // The following steps gradually remove the block from all its dependants in
1709 // post order (b/27683071).
1710
1711 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1712 // We need to do this before step (4) which destroys the predecessor list.
1713 HBasicBlock* loop_update_start = this;
1714 if (IsLoopHeader()) {
1715 HLoopInformation* loop_info = GetLoopInformation();
1716 // All other blocks in this loop should have been removed because the header
1717 // was their dominator.
1718 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1719 DCHECK(!loop_info->IsIrreducible());
1720 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1721 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1722 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001723 }
1724
David Brazdil9eeebf62016-03-24 11:18:15 +00001725 // (2) Disconnect the block from its successors and update their phis.
1726 for (HBasicBlock* successor : successors_) {
1727 // Delete this block from the list of predecessors.
1728 size_t this_index = successor->GetPredecessorIndexOf(this);
1729 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1730
1731 // Check that `successor` has other predecessors, otherwise `this` is the
1732 // dominator of `successor` which violates the order DCHECKed at the top.
1733 DCHECK(!successor->predecessors_.empty());
1734
1735 // Remove this block's entries in the successor's phis. Skip exceptional
1736 // successors because catch phi inputs do not correspond to predecessor
1737 // blocks but throwing instructions. The inputs of the catch phis will be
1738 // updated in step (3).
1739 if (!successor->IsCatchBlock()) {
1740 if (successor->predecessors_.size() == 1u) {
1741 // The successor has just one predecessor left. Replace phis with the only
1742 // remaining input.
1743 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1744 HPhi* phi = phi_it.Current()->AsPhi();
1745 phi->ReplaceWith(phi->InputAt(1 - this_index));
1746 successor->RemovePhi(phi);
1747 }
1748 } else {
1749 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1750 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1751 }
1752 }
1753 }
1754 }
1755 successors_.clear();
1756
1757 // (3) Remove instructions and phis. Instructions should have no remaining uses
1758 // except in catch phis. If an instruction is used by a catch phi at `index`,
1759 // remove `index`-th input of all phis in the catch block since they are
1760 // guaranteed dead. Note that we may miss dead inputs this way but the
1761 // graph will always remain consistent.
1762 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1763 HInstruction* insn = it.Current();
1764 RemoveUsesOfDeadInstruction(insn);
1765 RemoveInstruction(insn);
1766 }
1767 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1768 HPhi* insn = it.Current()->AsPhi();
1769 RemoveUsesOfDeadInstruction(insn);
1770 RemovePhi(insn);
1771 }
1772
1773 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001774 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001775 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001776 // We should not see any back edges as they would have been removed by step (3).
1777 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1778
David Brazdil2d7352b2015-04-20 14:52:42 +01001779 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001780 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1781 // This block is the only normal-flow successor of the TryBoundary which
1782 // makes `predecessor` dead. Since DCE removes blocks in post order,
1783 // exception handlers of this TryBoundary were already visited and any
1784 // remaining handlers therefore must be live. We remove `predecessor` from
1785 // their list of predecessors.
1786 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1787 while (predecessor->GetSuccessors().size() > 1) {
1788 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1789 DCHECK(handler->IsCatchBlock());
1790 predecessor->RemoveSuccessor(handler);
1791 handler->RemovePredecessor(predecessor);
1792 }
1793 }
1794
David Brazdil2d7352b2015-04-20 14:52:42 +01001795 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001796 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1797 if (num_pred_successors == 1u) {
1798 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001799 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1800 // successor. Replace those with a HGoto.
1801 DCHECK(last_instruction->IsIf() ||
1802 last_instruction->IsPackedSwitch() ||
1803 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001804 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001805 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001806 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001807 // The predecessor has no remaining successors and therefore must be dead.
1808 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001809 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001810 predecessor->RemoveInstruction(last_instruction);
1811 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001812 // There are multiple successors left. The removed block might be a successor
1813 // of a PackedSwitch which will be completely removed (perhaps replaced with
1814 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1815 // case, leave `last_instruction` as is for now.
1816 DCHECK(last_instruction->IsPackedSwitch() ||
1817 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001818 }
David Brazdil46e2a392015-03-16 17:31:52 +00001819 }
Vladimir Marko60584552015-09-03 13:35:12 +00001820 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001821
David Brazdil9eeebf62016-03-24 11:18:15 +00001822 // (5) Remove the block from all loops it is included in. Skip the inner-most
1823 // loop if this is the loop header (see definition of `loop_update_start`)
1824 // because the loop header's predecessor list has been destroyed in step (4).
1825 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1826 HLoopInformation* loop_info = it.Current();
1827 loop_info->Remove(this);
1828 if (loop_info->IsBackEdge(*this)) {
1829 // If this was the last back edge of the loop, we deliberately leave the
1830 // loop in an inconsistent state and will fail GraphChecker unless the
1831 // entire loop is removed during the pass.
1832 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001833 }
1834 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001835
David Brazdil9eeebf62016-03-24 11:18:15 +00001836 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001837 dominator_->RemoveDominatedBlock(this);
1838 SetDominator(nullptr);
1839
David Brazdil9eeebf62016-03-24 11:18:15 +00001840 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001841 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001842 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001843}
1844
1845void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001846 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001847 DCHECK(ContainsElement(dominated_blocks_, other));
1848 DCHECK_EQ(GetSingleSuccessor(), other);
1849 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001850 DCHECK(other->GetPhis().IsEmpty());
1851
David Brazdil2d7352b2015-04-20 14:52:42 +01001852 // Move instructions from `other` to `this`.
1853 DCHECK(EndsWithControlFlowInstruction());
1854 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001855 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001856 other->instructions_.SetBlockOfInstructions(this);
1857 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001858
David Brazdil2d7352b2015-04-20 14:52:42 +01001859 // Remove `other` from the loops it is included in.
1860 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1861 HLoopInformation* loop_info = it.Current();
1862 loop_info->Remove(other);
1863 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001864 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001865 }
1866 }
1867
1868 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001869 successors_.clear();
1870 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001871 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001872 successor->ReplacePredecessor(other, this);
1873 }
1874
David Brazdil2d7352b2015-04-20 14:52:42 +01001875 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001876 RemoveDominatedBlock(other);
1877 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1878 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001879 dominated->SetDominator(this);
1880 }
Vladimir Marko60584552015-09-03 13:35:12 +00001881 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001882 other->dominator_ = nullptr;
1883
1884 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001885 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001886
1887 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001888 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001889 other->SetGraph(nullptr);
1890}
1891
1892void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1893 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001894 DCHECK(GetDominatedBlocks().empty());
1895 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001896 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001897 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001898 DCHECK(other->GetPhis().IsEmpty());
1899 DCHECK(!other->IsInLoop());
1900
1901 // Move instructions from `other` to `this`.
1902 instructions_.Add(other->GetInstructions());
1903 other->instructions_.SetBlockOfInstructions(this);
1904
1905 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001906 successors_.clear();
1907 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001908 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001909 successor->ReplacePredecessor(other, this);
1910 }
1911
1912 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001913 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1914 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001915 dominated->SetDominator(this);
1916 }
Vladimir Marko60584552015-09-03 13:35:12 +00001917 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001918 other->dominator_ = nullptr;
1919 other->graph_ = nullptr;
1920}
1921
1922void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001923 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001924 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001925 predecessor->ReplaceSuccessor(this, other);
1926 }
Vladimir Marko60584552015-09-03 13:35:12 +00001927 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001928 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001929 successor->ReplacePredecessor(this, other);
1930 }
Vladimir Marko60584552015-09-03 13:35:12 +00001931 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1932 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001933 }
1934 GetDominator()->ReplaceDominatedBlock(this, other);
1935 other->SetDominator(GetDominator());
1936 dominator_ = nullptr;
1937 graph_ = nullptr;
1938}
1939
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001940void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001941 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001942 DCHECK(block->GetSuccessors().empty());
1943 DCHECK(block->GetPredecessors().empty());
1944 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001945 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001946 DCHECK(block->GetInstructions().IsEmpty());
1947 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001948
David Brazdilc7af85d2015-05-26 12:05:55 +01001949 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06001950 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01001951 }
1952
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001953 RemoveElement(reverse_post_order_, block);
1954 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00001955 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01001956}
1957
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001958void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
1959 HBasicBlock* reference,
1960 bool replace_if_back_edge) {
1961 if (block->IsLoopHeader()) {
1962 // Clear the information of which blocks are contained in that loop. Since the
1963 // information is stored as a bit vector based on block ids, we have to update
1964 // it, as those block ids were specific to the callee graph and we are now adding
1965 // these blocks to the caller graph.
1966 block->GetLoopInformation()->ClearAllBlocks();
1967 }
1968
1969 // If not already in a loop, update the loop information.
1970 if (!block->IsInLoop()) {
1971 block->SetLoopInformation(reference->GetLoopInformation());
1972 }
1973
1974 // If the block is in a loop, update all its outward loops.
1975 HLoopInformation* loop_info = block->GetLoopInformation();
1976 if (loop_info != nullptr) {
1977 for (HLoopInformationOutwardIterator loop_it(*block);
1978 !loop_it.Done();
1979 loop_it.Advance()) {
1980 loop_it.Current()->Add(block);
1981 }
1982 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
1983 loop_info->ReplaceBackEdge(reference, block);
1984 }
1985 }
1986
1987 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
1988 TryCatchInformation* try_catch_info = reference->IsTryBlock()
1989 ? reference->GetTryCatchInformation()
1990 : nullptr;
1991 block->SetTryCatchInformation(try_catch_info);
1992}
1993
Calin Juravle2e768302015-07-28 14:41:11 +00001994HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001995 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001996 // Update the environments in this graph to have the invoke's environment
1997 // as parent.
1998 {
1999 HReversePostOrderIterator it(*this);
2000 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
2001 for (; !it.Done(); it.Advance()) {
2002 HBasicBlock* block = it.Current();
2003 for (HInstructionIterator instr_it(block->GetInstructions());
2004 !instr_it.Done();
2005 instr_it.Advance()) {
2006 HInstruction* current = instr_it.Current();
2007 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002008 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002009 current->GetEnvironment()->SetAndCopyParentChain(
2010 outer_graph->GetArena(), invoke->GetEnvironment());
2011 }
2012 }
2013 }
2014 }
2015 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
2016 if (HasBoundsChecks()) {
2017 outer_graph->SetHasBoundsChecks(true);
2018 }
2019
Calin Juravle2e768302015-07-28 14:41:11 +00002020 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002021 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002022 // Simple case of an entry block, a body block, and an exit block.
2023 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002024 HBasicBlock* body = GetBlocks()[1];
2025 DCHECK(GetBlocks()[0]->IsEntryBlock());
2026 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002027 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002028 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002029 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002030
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002031 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2032 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002033 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002034
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002035 // Replace the invoke with the return value of the inlined graph.
2036 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002037 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002038 } else {
2039 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002040 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002041
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002042 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002043 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002044 // Need to inline multiple blocks. We split `invoke`'s block
2045 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002046 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002047 // with the second half.
2048 ArenaAllocator* allocator = outer_graph->GetArena();
2049 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002050 // Note that we split before the invoke only to simplify polymorphic inlining.
2051 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002052
Vladimir Markoec7802a2015-10-01 20:57:57 +01002053 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002054 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002055 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002056 exit_block_->ReplaceWith(to);
2057
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002058 // Update the meta information surrounding blocks:
2059 // (1) the graph they are now in,
2060 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002061 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002062 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002063 // Note that we do not need to update catch phi inputs because they
2064 // correspond to the register file of the outer method which the inlinee
2065 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002066
2067 // We don't add the entry block, the exit block, and the first block, which
2068 // has been merged with `at`.
2069 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2070
2071 // We add the `to` block.
2072 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002073 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002074 + kNumberOfNewBlocksInCaller;
2075
2076 // Find the location of `at` in the outer graph's reverse post order. The new
2077 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002078 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002079 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2080
David Brazdil95177982015-10-30 12:56:58 -05002081 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2082 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002083 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
2084 HBasicBlock* current = it.Current();
2085 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002086 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002087 DCHECK(current->GetGraph() == this);
2088 current->SetGraph(outer_graph);
2089 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002090 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002091 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002092 }
2093 }
2094
David Brazdil95177982015-10-30 12:56:58 -05002095 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002096 to->SetGraph(outer_graph);
2097 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002098 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002099 // Only `to` can become a back edge, as the inlined blocks
2100 // are predecessors of `to`.
2101 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002102
David Brazdil3f523062016-02-29 16:53:33 +00002103 // Update all predecessors of the exit block (now the `to` block)
2104 // to not `HReturn` but `HGoto` instead.
2105 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
2106 if (to->GetPredecessors().size() == 1) {
2107 HBasicBlock* predecessor = to->GetPredecessors()[0];
2108 HInstruction* last = predecessor->GetLastInstruction();
2109 if (!returns_void) {
2110 return_value = last->InputAt(0);
2111 }
2112 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2113 predecessor->RemoveInstruction(last);
2114 } else {
2115 if (!returns_void) {
2116 // There will be multiple returns.
2117 return_value = new (allocator) HPhi(
2118 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2119 to->AddPhi(return_value->AsPhi());
2120 }
2121 for (HBasicBlock* predecessor : to->GetPredecessors()) {
2122 HInstruction* last = predecessor->GetLastInstruction();
2123 if (!returns_void) {
2124 DCHECK(last->IsReturn());
2125 return_value->AsPhi()->AddInput(last->InputAt(0));
2126 }
2127 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2128 predecessor->RemoveInstruction(last);
2129 }
2130 }
2131 }
David Brazdil05144f42015-04-16 15:18:00 +01002132
2133 // Walk over the entry block and:
2134 // - Move constants from the entry block to the outer_graph's entry block,
2135 // - Replace HParameterValue instructions with their real value.
2136 // - Remove suspend checks, that hold an environment.
2137 // We must do this after the other blocks have been inlined, otherwise ids of
2138 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002139 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002140 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2141 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002142 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002143 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002144 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002145 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002146 replacement = outer_graph->GetIntConstant(
2147 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002148 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002149 replacement = outer_graph->GetLongConstant(
2150 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002151 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002152 replacement = outer_graph->GetFloatConstant(
2153 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002154 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002155 replacement = outer_graph->GetDoubleConstant(
2156 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002157 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002158 if (kIsDebugBuild
2159 && invoke->IsInvokeStaticOrDirect()
2160 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2161 // Ensure we do not use the last input of `invoke`, as it
2162 // contains a clinit check which is not an actual argument.
2163 size_t last_input_index = invoke->InputCount() - 1;
2164 DCHECK(parameter_index != last_input_index);
2165 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002166 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002167 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002168 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002169 } else {
2170 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2171 entry_block_->RemoveInstruction(current);
2172 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002173 if (replacement != nullptr) {
2174 current->ReplaceWith(replacement);
2175 // If the current is the return value then we need to update the latter.
2176 if (current == return_value) {
2177 DCHECK_EQ(entry_block_, return_value->GetBlock());
2178 return_value = replacement;
2179 }
2180 }
2181 }
2182
Calin Juravle2e768302015-07-28 14:41:11 +00002183 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002184}
2185
Mingyao Yang3584bce2015-05-19 16:01:59 -07002186/*
2187 * Loop will be transformed to:
2188 * old_pre_header
2189 * |
2190 * if_block
2191 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002192 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002193 * \ /
2194 * new_pre_header
2195 * |
2196 * header
2197 */
2198void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2199 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002200 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002201
Aart Bik3fc7f352015-11-20 22:03:03 -08002202 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002203 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002204 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2205 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002206 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2207 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002208 AddBlock(true_block);
2209 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002210 AddBlock(new_pre_header);
2211
Aart Bik3fc7f352015-11-20 22:03:03 -08002212 header->ReplacePredecessor(old_pre_header, new_pre_header);
2213 old_pre_header->successors_.clear();
2214 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002215
Aart Bik3fc7f352015-11-20 22:03:03 -08002216 old_pre_header->AddSuccessor(if_block);
2217 if_block->AddSuccessor(true_block); // True successor
2218 if_block->AddSuccessor(false_block); // False successor
2219 true_block->AddSuccessor(new_pre_header);
2220 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002221
Aart Bik3fc7f352015-11-20 22:03:03 -08002222 old_pre_header->dominated_blocks_.push_back(if_block);
2223 if_block->SetDominator(old_pre_header);
2224 if_block->dominated_blocks_.push_back(true_block);
2225 true_block->SetDominator(if_block);
2226 if_block->dominated_blocks_.push_back(false_block);
2227 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002228 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002229 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002230 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002231 header->SetDominator(new_pre_header);
2232
Aart Bik3fc7f352015-11-20 22:03:03 -08002233 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002234 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002235 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002236 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002237 reverse_post_order_[index_of_header++] = true_block;
2238 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002239 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002240
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002241 // The pre_header can never be a back edge of a loop.
2242 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2243 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2244 UpdateLoopAndTryInformationOfNewBlock(
2245 if_block, old_pre_header, /* replace_if_back_edge */ false);
2246 UpdateLoopAndTryInformationOfNewBlock(
2247 true_block, old_pre_header, /* replace_if_back_edge */ false);
2248 UpdateLoopAndTryInformationOfNewBlock(
2249 false_block, old_pre_header, /* replace_if_back_edge */ false);
2250 UpdateLoopAndTryInformationOfNewBlock(
2251 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002252}
2253
David Brazdilf5552582015-12-27 13:36:12 +00002254static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2255 SHARED_REQUIRES(Locks::mutator_lock_) {
2256 if (rti.IsValid()) {
2257 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2258 << " upper_bound_rti: " << upper_bound_rti
2259 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002260 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2261 << " upper_bound_rti: " << upper_bound_rti
2262 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002263 }
2264}
2265
Calin Juravle2e768302015-07-28 14:41:11 +00002266void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2267 if (kIsDebugBuild) {
2268 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2269 ScopedObjectAccess soa(Thread::Current());
2270 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2271 if (IsBoundType()) {
2272 // Having the test here spares us from making the method virtual just for
2273 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002274 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002275 }
2276 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002277 reference_type_handle_ = rti.GetTypeHandle();
2278 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002279}
2280
David Brazdilf5552582015-12-27 13:36:12 +00002281void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2282 if (kIsDebugBuild) {
2283 ScopedObjectAccess soa(Thread::Current());
2284 DCHECK(upper_bound.IsValid());
2285 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2286 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2287 }
2288 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002289 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002290}
2291
Vladimir Markoa1de9182016-02-25 11:37:38 +00002292ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002293 if (kIsDebugBuild) {
2294 ScopedObjectAccess soa(Thread::Current());
2295 DCHECK(IsValidHandle(type_handle));
Aart Bik8b3f9b22016-04-06 11:22:12 -07002296 DCHECK(!type_handle->IsErroneous());
Aart Bikf417ff42016-04-25 12:51:37 -07002297 DCHECK(!type_handle->IsArrayClass() || !type_handle->GetComponentType()->IsErroneous());
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002298 if (!is_exact) {
2299 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2300 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2301 }
Calin Juravle2e768302015-07-28 14:41:11 +00002302 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002303 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002304}
2305
Calin Juravleacf735c2015-02-12 15:25:22 +00002306std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2307 ScopedObjectAccess soa(Thread::Current());
2308 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002309 << " is_valid=" << rhs.IsValid()
2310 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002311 << " is_exact=" << rhs.IsExact()
2312 << " ]";
2313 return os;
2314}
2315
Mark Mendellc4701932015-04-10 13:18:51 -04002316bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2317 // For now, assume that instructions in different blocks may use the
2318 // environment.
2319 // TODO: Use the control flow to decide if this is true.
2320 if (GetBlock() != other->GetBlock()) {
2321 return true;
2322 }
2323
2324 // We know that we are in the same block. Walk from 'this' to 'other',
2325 // checking to see if there is any instruction with an environment.
2326 HInstruction* current = this;
2327 for (; current != other && current != nullptr; current = current->GetNext()) {
2328 // This is a conservative check, as the instruction result may not be in
2329 // the referenced environment.
2330 if (current->HasEnvironment()) {
2331 return true;
2332 }
2333 }
2334
2335 // We should have been called with 'this' before 'other' in the block.
2336 // Just confirm this.
2337 DCHECK(current != nullptr);
2338 return false;
2339}
2340
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002341void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002342 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2343 IntrinsicSideEffects side_effects,
2344 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002345 intrinsic_ = intrinsic;
2346 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002347
Aart Bik5d75afe2015-12-14 11:57:01 -08002348 // Adjust method's side effects from intrinsic table.
2349 switch (side_effects) {
2350 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2351 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2352 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2353 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2354 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002355
2356 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2357 opt.SetDoesNotNeedDexCache();
2358 opt.SetDoesNotNeedEnvironment();
2359 } else {
2360 // If we need an environment, that means there will be a call, which can trigger GC.
2361 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2362 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002363 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002364 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002365}
2366
David Brazdil6de19382016-01-08 17:37:10 +00002367bool HNewInstance::IsStringAlloc() const {
2368 ScopedObjectAccess soa(Thread::Current());
2369 return GetReferenceTypeInfo().IsStringClass();
2370}
2371
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002372bool HInvoke::NeedsEnvironment() const {
2373 if (!IsIntrinsic()) {
2374 return true;
2375 }
2376 IntrinsicOptimizations opt(*this);
2377 return !opt.GetDoesNotNeedEnvironment();
2378}
2379
Vladimir Markodc151b22015-10-15 18:02:30 +01002380bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2381 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002382 return false;
2383 }
2384 if (!IsIntrinsic()) {
2385 return true;
2386 }
2387 IntrinsicOptimizations opt(*this);
2388 return !opt.GetDoesNotNeedDexCache();
2389}
2390
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002391void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2392 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2393 input->AddUseAt(this, index);
2394 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2395 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2396 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2397 InputRecordAt(i).GetUseNode()->SetIndex(i);
2398 }
2399}
2400
Vladimir Markob554b5a2015-11-06 12:57:55 +00002401void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2402 RemoveAsUserOfInput(index);
2403 inputs_.erase(inputs_.begin() + index);
2404 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2405 for (size_t i = index, e = InputCount(); i < e; ++i) {
2406 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2407 InputRecordAt(i).GetUseNode()->SetIndex(i);
2408 }
2409}
2410
Vladimir Markof64242a2015-12-01 14:58:23 +00002411std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2412 switch (rhs) {
2413 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2414 return os << "string_init";
2415 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2416 return os << "recursive";
2417 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2418 return os << "direct";
2419 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2420 return os << "direct_fixup";
2421 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2422 return os << "dex_cache_pc_relative";
2423 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2424 return os << "dex_cache_via_method";
2425 default:
2426 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2427 UNREACHABLE();
2428 }
2429}
2430
Vladimir Markofbb184a2015-11-13 14:47:00 +00002431std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2432 switch (rhs) {
2433 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2434 return os << "explicit";
2435 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2436 return os << "implicit";
2437 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2438 return os << "none";
2439 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002440 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2441 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002442 }
2443}
2444
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002445bool HLoadString::InstructionDataEquals(HInstruction* other) const {
2446 HLoadString* other_load_string = other->AsLoadString();
2447 if (string_index_ != other_load_string->string_index_ ||
2448 GetPackedFields() != other_load_string->GetPackedFields()) {
2449 return false;
2450 }
2451 LoadKind load_kind = GetLoadKind();
2452 if (HasAddress(load_kind)) {
2453 return GetAddress() == other_load_string->GetAddress();
2454 } else if (HasStringReference(load_kind)) {
2455 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2456 } else {
2457 DCHECK(HasDexCacheReference(load_kind)) << load_kind;
2458 // If the string indexes and dex files are the same, dex cache element offsets
2459 // must also be the same, so we don't need to compare them.
2460 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2461 }
2462}
2463
2464void HLoadString::SetLoadKindInternal(LoadKind load_kind) {
2465 // Once sharpened, the load kind should not be changed again.
2466 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2467 SetPackedField<LoadKindField>(load_kind);
2468
2469 if (load_kind != LoadKind::kDexCacheViaMethod) {
2470 RemoveAsUserOfInput(0u);
2471 SetRawInputAt(0u, nullptr);
2472 }
2473 if (!NeedsEnvironment()) {
2474 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002475 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002476 }
2477}
2478
2479std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2480 switch (rhs) {
2481 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2482 return os << "BootImageLinkTimeAddress";
2483 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2484 return os << "BootImageLinkTimePcRelative";
2485 case HLoadString::LoadKind::kBootImageAddress:
2486 return os << "BootImageAddress";
2487 case HLoadString::LoadKind::kDexCacheAddress:
2488 return os << "DexCacheAddress";
2489 case HLoadString::LoadKind::kDexCachePcRelative:
2490 return os << "DexCachePcRelative";
2491 case HLoadString::LoadKind::kDexCacheViaMethod:
2492 return os << "DexCacheViaMethod";
2493 default:
2494 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2495 UNREACHABLE();
2496 }
2497}
2498
Mark Mendellc4701932015-04-10 13:18:51 -04002499void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002500 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2501 HEnvironment* user = use.GetUser();
2502 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002503 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002504 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002505}
2506
Roland Levillainc9b21f82016-03-23 16:36:59 +00002507// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002508HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2509 ArenaAllocator* allocator = GetArena();
2510
2511 if (cond->IsCondition() &&
2512 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2513 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2514 HInstruction* lhs = cond->InputAt(0);
2515 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002516 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002517 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2518 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2519 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2520 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2521 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2522 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2523 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2524 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2525 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2526 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2527 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002528 default:
2529 LOG(FATAL) << "Unexpected condition";
2530 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002531 }
2532 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2533 return replacement;
2534 } else if (cond->IsIntConstant()) {
2535 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002536 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002537 return GetIntConstant(1);
2538 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002539 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002540 return GetIntConstant(0);
2541 }
2542 } else {
2543 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2544 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2545 return replacement;
2546 }
2547}
2548
Roland Levillainc9285912015-12-18 10:38:42 +00002549std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2550 os << "["
2551 << " source=" << rhs.GetSource()
2552 << " destination=" << rhs.GetDestination()
2553 << " type=" << rhs.GetType()
2554 << " instruction=";
2555 if (rhs.GetInstruction() != nullptr) {
2556 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2557 } else {
2558 os << "null";
2559 }
2560 os << " ]";
2561 return os;
2562}
2563
Roland Levillain86503782016-02-11 19:07:30 +00002564std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2565 switch (rhs) {
2566 case TypeCheckKind::kUnresolvedCheck:
2567 return os << "unresolved_check";
2568 case TypeCheckKind::kExactCheck:
2569 return os << "exact_check";
2570 case TypeCheckKind::kClassHierarchyCheck:
2571 return os << "class_hierarchy_check";
2572 case TypeCheckKind::kAbstractClassCheck:
2573 return os << "abstract_class_check";
2574 case TypeCheckKind::kInterfaceCheck:
2575 return os << "interface_check";
2576 case TypeCheckKind::kArrayObjectCheck:
2577 return os << "array_object_check";
2578 case TypeCheckKind::kArrayCheck:
2579 return os << "array_check";
2580 default:
2581 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2582 UNREACHABLE();
2583 }
2584}
2585
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002586} // namespace art