blob: 4332d7ed02c4319097ea11f54a8e4bc8c643198b [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 */
16
17#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000018
Mark Mendelle82549b2015-05-06 10:55:34 -040019#include "code_generator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010020#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010021#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010022#include "base/bit_utils.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000023#include "utils/growable_array.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000024#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000025
26namespace art {
27
28void HGraph::AddBlock(HBasicBlock* block) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000029 block->SetBlockId(blocks_.Size());
Nicolas Geoffray818f2102014-02-18 16:43:35 +000030 blocks_.Add(block);
31}
32
Nicolas Geoffray804d0932014-05-02 08:46:00 +010033void HGraph::FindBackEdges(ArenaBitVector* visited) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000034 ArenaBitVector visiting(arena_, blocks_.Size(), false);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000035 VisitBlockForBackEdges(entry_block_, visited, &visiting);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000036}
37
Roland Levillainfc600dc2014-12-02 17:16:31 +000038static void RemoveAsUser(HInstruction* instruction) {
39 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000040 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000041 }
42
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010043 for (HEnvironment* environment = instruction->GetEnvironment();
44 environment != nullptr;
45 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000046 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000047 if (environment->GetInstructionAt(i) != nullptr) {
48 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000049 }
50 }
51 }
52}
53
54void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
55 for (size_t i = 0; i < blocks_.Size(); ++i) {
56 if (!visited.IsBitSet(i)) {
57 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010058 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000059 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
60 RemoveAsUser(it.Current());
61 }
62 }
63 }
64}
65
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010066void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010067 for (size_t i = 0; i < blocks_.Size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000068 if (!visited.IsBitSet(i)) {
David Brazdil1abb4192015-02-17 18:33:36 +000069 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010070 // We only need to update the successor, which might be live.
David Brazdil1abb4192015-02-17 18:33:36 +000071 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
72 block->GetSuccessors().Get(j)->RemovePredecessor(block);
73 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010074 // Remove the block from the list of blocks, so that further analyses
75 // never see it.
76 blocks_.Put(i, nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000077 }
78 }
79}
80
81void HGraph::VisitBlockForBackEdges(HBasicBlock* block,
82 ArenaBitVector* visited,
Nicolas Geoffray804d0932014-05-02 08:46:00 +010083 ArenaBitVector* visiting) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000084 int id = block->GetBlockId();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000085 if (visited->IsBitSet(id)) return;
86
87 visited->SetBit(id);
88 visiting->SetBit(id);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010089 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
90 HBasicBlock* successor = block->GetSuccessors().Get(i);
Nicolas Geoffray787c3072014-03-17 10:20:19 +000091 if (visiting->IsBitSet(successor->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000092 successor->AddBackEdge(block);
93 } else {
94 VisitBlockForBackEdges(successor, visited, visiting);
95 }
96 }
97 visiting->ClearBit(id);
98}
99
100void HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100101 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
102 // edges. This invariant simplifies building SSA form because Phis cannot
103 // collect both normal- and exceptional-flow values at the same time.
104 SimplifyCatchBlocks();
105
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000106 ArenaBitVector visited(arena_, blocks_.Size(), false);
107
David Brazdilffee3d32015-07-06 11:48:53 +0100108 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000109 FindBackEdges(&visited);
110
David Brazdilffee3d32015-07-06 11:48:53 +0100111 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000112 // the initial DFS as users from other instructions, so that
113 // users can be safely removed before uses later.
114 RemoveInstructionsAsUsersFromDeadBlocks(visited);
115
David Brazdilffee3d32015-07-06 11:48:53 +0100116 // (4) Remove blocks not visited during the initial DFS.
Roland Levillainfc600dc2014-12-02 17:16:31 +0000117 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000118 // predecessors list of live blocks.
119 RemoveDeadBlocks(visited);
120
David Brazdilffee3d32015-07-06 11:48:53 +0100121 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100122 // dominators and the reverse post order.
123 SimplifyCFG();
124
David Brazdilffee3d32015-07-06 11:48:53 +0100125 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100126 ComputeDominanceInformation();
127}
128
129void HGraph::ClearDominanceInformation() {
130 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
131 it.Current()->ClearDominanceInformation();
132 }
133 reverse_post_order_.Reset();
134}
135
136void HBasicBlock::ClearDominanceInformation() {
137 dominated_blocks_.Reset();
138 dominator_ = nullptr;
139}
140
141void HGraph::ComputeDominanceInformation() {
142 DCHECK(reverse_post_order_.IsEmpty());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000143 GrowableArray<size_t> visits(arena_, blocks_.Size());
144 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100145 reverse_post_order_.Add(entry_block_);
146 for (size_t i = 0; i < entry_block_->GetSuccessors().Size(); i++) {
147 VisitBlockForDominatorTree(entry_block_->GetSuccessors().Get(i), entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000148 }
149}
150
151HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
152 ArenaBitVector visited(arena_, blocks_.Size(), false);
153 // Walk the dominator tree of the first block and mark the visited blocks.
154 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000155 visited.SetBit(first->GetBlockId());
156 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000157 }
158 // Walk the dominator tree of the second block until a marked block is found.
159 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000160 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000161 return second;
162 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000163 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000164 }
165 LOG(ERROR) << "Could not find common dominator";
166 return nullptr;
167}
168
169void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
170 HBasicBlock* predecessor,
171 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000172 if (block->GetDominator() == nullptr) {
173 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000174 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000175 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000176 }
177
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000178 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000179 // Once all the forward edges have been visited, we know the immediate
180 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000181 if (visits->Get(block->GetBlockId()) ==
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100182 block->GetPredecessors().Size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100183 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100184 reverse_post_order_.Add(block);
185 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
186 VisitBlockForDominatorTree(block->GetSuccessors().Get(i), block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000187 }
188 }
189}
190
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000191void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100192 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100193 SsaBuilder ssa_builder(this);
194 ssa_builder.BuildSsa();
195}
196
David Brazdilfc6a86a2015-06-26 10:33:45 +0000197HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000198 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
199 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000200 // Use `InsertBetween` to ensure the predecessor index and successor index of
201 // `block` and `successor` are preserved.
202 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000203 return new_block;
204}
205
206void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
207 // Insert a new node between `block` and `successor` to split the
208 // critical edge.
209 HBasicBlock* new_block = SplitEdge(block, successor);
210 new_block->AddInstruction(new (arena_) HGoto());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100211 if (successor->IsLoopHeader()) {
212 // If we split at a back edge boundary, make the new block the back edge.
213 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000214 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100215 info->RemoveBackEdge(block);
216 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100217 }
218 }
219}
220
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100221void HGraph::SimplifyLoop(HBasicBlock* header) {
222 HLoopInformation* info = header->GetLoopInformation();
223
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100224 // Make sure the loop has only one pre header. This simplifies SSA building by having
225 // to just look at the pre header to know which locals are initialized at entry of the
226 // loop.
227 size_t number_of_incomings = header->GetPredecessors().Size() - info->NumberOfBackEdges();
228 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100229 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100230 AddBlock(pre_header);
231 pre_header->AddInstruction(new (arena_) HGoto());
232
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100233 for (size_t pred = 0; pred < header->GetPredecessors().Size(); ++pred) {
234 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100235 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100236 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100237 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100238 }
239 }
240 pre_header->AddSuccessor(header);
241 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100242
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100243 // Make sure the first predecessor of a loop header is the incoming block.
244 if (info->IsBackEdge(*header->GetPredecessors().Get(0))) {
245 HBasicBlock* to_swap = header->GetPredecessors().Get(0);
246 for (size_t pred = 1, e = header->GetPredecessors().Size(); pred < e; ++pred) {
247 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
248 if (!info->IsBackEdge(*predecessor)) {
249 header->predecessors_.Put(pred, to_swap);
250 header->predecessors_.Put(0, predecessor);
251 break;
252 }
253 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100254 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100255
256 // Place the suspend check at the beginning of the header, so that live registers
257 // will be known when allocating registers. Note that code generation can still
258 // generate the suspend check at the back edge, but needs to be careful with
259 // loop phi spill slots (which are not written to at back edge).
260 HInstruction* first_instruction = header->GetFirstInstruction();
261 if (!first_instruction->IsSuspendCheck()) {
262 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
263 header->InsertInstructionBefore(check, first_instruction);
264 first_instruction = check;
265 }
266 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100267}
268
David Brazdilffee3d32015-07-06 11:48:53 +0100269static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
270 HBasicBlock* predecessor = block.GetPredecessors().Get(pred_idx);
271 if (!predecessor->EndsWithTryBoundary()) {
272 // Only edges from HTryBoundary can be exceptional.
273 return false;
274 }
275 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
276 if (try_boundary->GetNormalFlowSuccessor() == &block) {
277 // This block is the normal-flow successor of `try_boundary`, but it could
278 // also be one of its exception handlers if catch blocks have not been
279 // simplified yet. Predecessors are unordered, so we will consider the first
280 // occurrence to be the normal edge and a possible second occurrence to be
281 // the exceptional edge.
282 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
283 } else {
284 // This is not the normal-flow successor of `try_boundary`, hence it must be
285 // one of its exception handlers.
286 DCHECK(try_boundary->HasExceptionHandler(block));
287 return true;
288 }
289}
290
291void HGraph::SimplifyCatchBlocks() {
292 for (size_t i = 0; i < blocks_.Size(); ++i) {
293 HBasicBlock* catch_block = blocks_.Get(i);
294 if (!catch_block->IsCatchBlock()) {
295 continue;
296 }
297
298 bool exceptional_predecessors_only = true;
299 for (size_t j = 0; j < catch_block->GetPredecessors().Size(); ++j) {
300 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
301 exceptional_predecessors_only = false;
302 break;
303 }
304 }
305
306 if (!exceptional_predecessors_only) {
307 // Catch block has normal-flow predecessors and needs to be simplified.
308 // Splitting the block before its first instruction moves all its
309 // instructions into `normal_block` and links the two blocks with a Goto.
310 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
311 // leaving `catch_block` with the exceptional edges only.
312 // Note that catch blocks with normal-flow predecessors cannot begin with
313 // a MOVE_EXCEPTION instruction, as guaranteed by the verifier.
314 DCHECK(!catch_block->GetFirstInstruction()->IsLoadException());
315 HBasicBlock* normal_block = catch_block->SplitBefore(catch_block->GetFirstInstruction());
316 for (size_t j = 0; j < catch_block->GetPredecessors().Size(); ++j) {
317 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
318 catch_block->GetPredecessors().Get(j)->ReplaceSuccessor(catch_block, normal_block);
319 --j;
320 }
321 }
322 }
323 }
324}
325
326void HGraph::ComputeTryBlockInformation() {
327 // Iterate in reverse post order to propagate try membership information from
328 // predecessors to their successors.
329 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
330 HBasicBlock* block = it.Current();
331 if (block->IsEntryBlock() || block->IsCatchBlock()) {
332 // Catch blocks after simplification have only exceptional predecessors
333 // and hence are never in tries.
334 continue;
335 }
336
337 // Infer try membership from the first predecessor. Having simplified loops,
338 // the first predecessor can never be a back edge and therefore it must have
339 // been visited already and had its try membership set.
340 HBasicBlock* first_predecessor = block->GetPredecessors().Get(0);
341 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100342 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
343 if (try_entry != nullptr) {
344 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
345 }
David Brazdilffee3d32015-07-06 11:48:53 +0100346 }
347}
348
David Brazdilbbd733e2015-08-18 17:48:17 +0100349bool HGraph::HasTryCatch() const {
350 for (size_t i = 0, e = blocks_.Size(); i < e; ++i) {
351 HBasicBlock* block = blocks_.Get(i);
352 if (block != nullptr && (block->IsTryBlock() || block->IsCatchBlock())) {
353 return true;
354 }
355 }
356 return false;
357}
358
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100359void HGraph::SimplifyCFG() {
360 // Simplify the CFG for future analysis, and code generation:
361 // (1): Split critical edges.
362 // (2): Simplify loops by having only one back edge, and one preheader.
363 for (size_t i = 0; i < blocks_.Size(); ++i) {
364 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100365 if (block == nullptr) continue;
David Brazdilffee3d32015-07-06 11:48:53 +0100366 if (block->NumberOfNormalSuccessors() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100367 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
368 HBasicBlock* successor = block->GetSuccessors().Get(j);
David Brazdilffee3d32015-07-06 11:48:53 +0100369 DCHECK(!successor->IsCatchBlock());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100370 if (successor->GetPredecessors().Size() > 1) {
371 SplitCriticalEdge(block, successor);
372 --j;
373 }
374 }
375 }
376 if (block->IsLoopHeader()) {
377 SimplifyLoop(block);
378 }
379 }
380}
381
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000382bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100383 // Order does not matter.
384 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
385 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100386 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100387 if (block->IsCatchBlock()) {
388 // TODO: Dealing with exceptional back edges could be tricky because
389 // they only approximate the real control flow. Bail out for now.
390 return false;
391 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100392 HLoopInformation* info = block->GetLoopInformation();
393 if (!info->Populate()) {
394 // Abort if the loop is non natural. We currently bailout in such cases.
395 return false;
396 }
397 }
398 }
399 return true;
400}
401
David Brazdil8d5b8b22015-03-24 10:51:52 +0000402void HGraph::InsertConstant(HConstant* constant) {
403 // New constants are inserted before the final control-flow instruction
404 // of the graph, or at its end if called from the graph builder.
405 if (entry_block_->EndsWithControlFlowInstruction()) {
406 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000407 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000408 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000409 }
410}
411
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000412HNullConstant* HGraph::GetNullConstant() {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100413 // For simplicity, don't bother reviving the cached null constant if it is
414 // not null and not in a block. Otherwise, we need to clear the instruction
415 // id and/or any invariants the graph is assuming when adding new instructions.
416 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000417 cached_null_constant_ = new (arena_) HNullConstant();
David Brazdil8d5b8b22015-03-24 10:51:52 +0000418 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000419 }
420 return cached_null_constant_;
421}
422
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100423HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100424 // For simplicity, don't bother reviving the cached current method if it is
425 // not null and not in a block. Otherwise, we need to clear the instruction
426 // id and/or any invariants the graph is assuming when adding new instructions.
427 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700428 cached_current_method_ = new (arena_) HCurrentMethod(
429 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100430 if (entry_block_->GetFirstInstruction() == nullptr) {
431 entry_block_->AddInstruction(cached_current_method_);
432 } else {
433 entry_block_->InsertInstructionBefore(
434 cached_current_method_, entry_block_->GetFirstInstruction());
435 }
436 }
437 return cached_current_method_;
438}
439
David Brazdil8d5b8b22015-03-24 10:51:52 +0000440HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value) {
441 switch (type) {
442 case Primitive::Type::kPrimBoolean:
443 DCHECK(IsUint<1>(value));
444 FALLTHROUGH_INTENDED;
445 case Primitive::Type::kPrimByte:
446 case Primitive::Type::kPrimChar:
447 case Primitive::Type::kPrimShort:
448 case Primitive::Type::kPrimInt:
449 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
450 return GetIntConstant(static_cast<int32_t>(value));
451
452 case Primitive::Type::kPrimLong:
453 return GetLongConstant(value);
454
455 default:
456 LOG(FATAL) << "Unsupported constant type";
457 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000458 }
David Brazdil46e2a392015-03-16 17:31:52 +0000459}
460
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000461void HGraph::CacheFloatConstant(HFloatConstant* constant) {
462 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
463 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
464 cached_float_constants_.Overwrite(value, constant);
465}
466
467void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
468 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
469 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
470 cached_double_constants_.Overwrite(value, constant);
471}
472
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000473void HLoopInformation::Add(HBasicBlock* block) {
474 blocks_.SetBit(block->GetBlockId());
475}
476
David Brazdil46e2a392015-03-16 17:31:52 +0000477void HLoopInformation::Remove(HBasicBlock* block) {
478 blocks_.ClearBit(block->GetBlockId());
479}
480
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100481void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
482 if (blocks_.IsBitSet(block->GetBlockId())) {
483 return;
484 }
485
486 blocks_.SetBit(block->GetBlockId());
487 block->SetInLoop(this);
488 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
489 PopulateRecursive(block->GetPredecessors().Get(i));
490 }
491}
492
493bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100494 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100495 for (size_t i = 0, e = GetBackEdges().Size(); i < e; ++i) {
496 HBasicBlock* back_edge = GetBackEdges().Get(i);
497 DCHECK(back_edge->GetDominator() != nullptr);
498 if (!header_->Dominates(back_edge)) {
499 // This loop is not natural. Do not bother going further.
500 return false;
501 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100502
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100503 // Populate this loop: starting with the back edge, recursively add predecessors
504 // that are not already part of that loop. Set the header as part of the loop
505 // to end the recursion.
506 // This is a recursive implementation of the algorithm described in
507 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
508 blocks_.SetBit(header_->GetBlockId());
509 PopulateRecursive(back_edge);
510 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100511 return true;
512}
513
David Brazdila4b8c212015-05-07 09:59:30 +0100514void HLoopInformation::Update() {
515 HGraph* graph = header_->GetGraph();
516 for (uint32_t id : blocks_.Indexes()) {
517 HBasicBlock* block = graph->GetBlocks().Get(id);
518 // Reset loop information of non-header blocks inside the loop, except
519 // members of inner nested loops because those should already have been
520 // updated by their own LoopInformation.
521 if (block->GetLoopInformation() == this && block != header_) {
522 block->SetLoopInformation(nullptr);
523 }
524 }
525 blocks_.ClearAllBits();
526
527 if (back_edges_.IsEmpty()) {
528 // The loop has been dismantled, delete its suspend check and remove info
529 // from the header.
530 DCHECK(HasSuspendCheck());
531 header_->RemoveInstruction(suspend_check_);
532 header_->SetLoopInformation(nullptr);
533 header_ = nullptr;
534 suspend_check_ = nullptr;
535 } else {
536 if (kIsDebugBuild) {
537 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
538 DCHECK(header_->Dominates(back_edges_.Get(i)));
539 }
540 }
541 // This loop still has reachable back edges. Repopulate the list of blocks.
542 bool populate_successful = Populate();
543 DCHECK(populate_successful);
544 }
545}
546
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100547HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100548 return header_->GetDominator();
549}
550
551bool HLoopInformation::Contains(const HBasicBlock& block) const {
552 return blocks_.IsBitSet(block.GetBlockId());
553}
554
555bool HLoopInformation::IsIn(const HLoopInformation& other) const {
556 return other.blocks_.IsBitSet(header_->GetBlockId());
557}
558
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100559size_t HLoopInformation::GetLifetimeEnd() const {
560 size_t last_position = 0;
561 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
562 last_position = std::max(back_edges_.Get(i)->GetLifetimeEnd(), last_position);
563 }
564 return last_position;
565}
566
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100567bool HBasicBlock::Dominates(HBasicBlock* other) const {
568 // Walk up the dominator tree from `other`, to find out if `this`
569 // is an ancestor.
570 HBasicBlock* current = other;
571 while (current != nullptr) {
572 if (current == this) {
573 return true;
574 }
575 current = current->GetDominator();
576 }
577 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100578}
579
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100580static void UpdateInputsUsers(HInstruction* instruction) {
581 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
582 instruction->InputAt(i)->AddUseAt(instruction, i);
583 }
584 // Environment should be created later.
585 DCHECK(!instruction->HasEnvironment());
586}
587
Roland Levillainccc07a92014-09-16 14:48:16 +0100588void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
589 HInstruction* replacement) {
590 DCHECK(initial->GetBlock() == this);
591 InsertInstructionBefore(replacement, initial);
592 initial->ReplaceWith(replacement);
593 RemoveInstruction(initial);
594}
595
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100596static void Add(HInstructionList* instruction_list,
597 HBasicBlock* block,
598 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000599 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000600 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100601 instruction->SetBlock(block);
602 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100603 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100604 instruction_list->AddInstruction(instruction);
605}
606
607void HBasicBlock::AddInstruction(HInstruction* instruction) {
608 Add(&instructions_, this, instruction);
609}
610
611void HBasicBlock::AddPhi(HPhi* phi) {
612 Add(&phis_, this, phi);
613}
614
David Brazdilc3d743f2015-04-22 13:40:50 +0100615void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
616 DCHECK(!cursor->IsPhi());
617 DCHECK(!instruction->IsPhi());
618 DCHECK_EQ(instruction->GetId(), -1);
619 DCHECK_NE(cursor->GetId(), -1);
620 DCHECK_EQ(cursor->GetBlock(), this);
621 DCHECK(!instruction->IsControlFlow());
622 instruction->SetBlock(this);
623 instruction->SetId(GetGraph()->GetNextInstructionId());
624 UpdateInputsUsers(instruction);
625 instructions_.InsertInstructionBefore(instruction, cursor);
626}
627
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100628void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
629 DCHECK(!cursor->IsPhi());
630 DCHECK(!instruction->IsPhi());
631 DCHECK_EQ(instruction->GetId(), -1);
632 DCHECK_NE(cursor->GetId(), -1);
633 DCHECK_EQ(cursor->GetBlock(), this);
634 DCHECK(!instruction->IsControlFlow());
635 DCHECK(!cursor->IsControlFlow());
636 instruction->SetBlock(this);
637 instruction->SetId(GetGraph()->GetNextInstructionId());
638 UpdateInputsUsers(instruction);
639 instructions_.InsertInstructionAfter(instruction, cursor);
640}
641
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100642void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
643 DCHECK_EQ(phi->GetId(), -1);
644 DCHECK_NE(cursor->GetId(), -1);
645 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100646 phi->SetBlock(this);
647 phi->SetId(GetGraph()->GetNextInstructionId());
648 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100649 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100650}
651
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100652static void Remove(HInstructionList* instruction_list,
653 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000654 HInstruction* instruction,
655 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100656 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100657 instruction->SetBlock(nullptr);
658 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000659 if (ensure_safety) {
660 DCHECK(instruction->GetUses().IsEmpty());
661 DCHECK(instruction->GetEnvUses().IsEmpty());
662 RemoveAsUser(instruction);
663 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100664}
665
David Brazdil1abb4192015-02-17 18:33:36 +0000666void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100667 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000668 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100669}
670
David Brazdil1abb4192015-02-17 18:33:36 +0000671void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
672 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100673}
674
David Brazdilc7508e92015-04-27 13:28:57 +0100675void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
676 if (instruction->IsPhi()) {
677 RemovePhi(instruction->AsPhi(), ensure_safety);
678 } else {
679 RemoveInstruction(instruction, ensure_safety);
680 }
681}
682
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100683void HEnvironment::CopyFrom(const GrowableArray<HInstruction*>& locals) {
684 for (size_t i = 0; i < locals.Size(); i++) {
685 HInstruction* instruction = locals.Get(i);
686 SetRawEnvAt(i, instruction);
687 if (instruction != nullptr) {
688 instruction->AddEnvUseAt(this, i);
689 }
690 }
691}
692
David Brazdiled596192015-01-23 10:39:45 +0000693void HEnvironment::CopyFrom(HEnvironment* env) {
694 for (size_t i = 0; i < env->Size(); i++) {
695 HInstruction* instruction = env->GetInstructionAt(i);
696 SetRawEnvAt(i, instruction);
697 if (instruction != nullptr) {
698 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100699 }
David Brazdiled596192015-01-23 10:39:45 +0000700 }
701}
702
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700703void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
704 HBasicBlock* loop_header) {
705 DCHECK(loop_header->IsLoopHeader());
706 for (size_t i = 0; i < env->Size(); i++) {
707 HInstruction* instruction = env->GetInstructionAt(i);
708 SetRawEnvAt(i, instruction);
709 if (instruction == nullptr) {
710 continue;
711 }
712 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
713 // At the end of the loop pre-header, the corresponding value for instruction
714 // is the first input of the phi.
715 HInstruction* initial = instruction->AsPhi()->InputAt(0);
716 DCHECK(initial->GetBlock()->Dominates(loop_header));
717 SetRawEnvAt(i, initial);
718 initial->AddEnvUseAt(this, i);
719 } else {
720 instruction->AddEnvUseAt(this, i);
721 }
722 }
723}
724
David Brazdil1abb4192015-02-17 18:33:36 +0000725void HEnvironment::RemoveAsUserOfInput(size_t index) const {
726 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
727 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100728}
729
Calin Juravle77520bc2015-01-12 18:45:46 +0000730HInstruction* HInstruction::GetNextDisregardingMoves() const {
731 HInstruction* next = GetNext();
732 while (next != nullptr && next->IsParallelMove()) {
733 next = next->GetNext();
734 }
735 return next;
736}
737
738HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
739 HInstruction* previous = GetPrevious();
740 while (previous != nullptr && previous->IsParallelMove()) {
741 previous = previous->GetPrevious();
742 }
743 return previous;
744}
745
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100746void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000747 if (first_instruction_ == nullptr) {
748 DCHECK(last_instruction_ == nullptr);
749 first_instruction_ = last_instruction_ = instruction;
750 } else {
751 last_instruction_->next_ = instruction;
752 instruction->previous_ = last_instruction_;
753 last_instruction_ = instruction;
754 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000755}
756
David Brazdilc3d743f2015-04-22 13:40:50 +0100757void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
758 DCHECK(Contains(cursor));
759 if (cursor == first_instruction_) {
760 cursor->previous_ = instruction;
761 instruction->next_ = cursor;
762 first_instruction_ = instruction;
763 } else {
764 instruction->previous_ = cursor->previous_;
765 instruction->next_ = cursor;
766 cursor->previous_ = instruction;
767 instruction->previous_->next_ = instruction;
768 }
769}
770
771void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
772 DCHECK(Contains(cursor));
773 if (cursor == last_instruction_) {
774 cursor->next_ = instruction;
775 instruction->previous_ = cursor;
776 last_instruction_ = instruction;
777 } else {
778 instruction->next_ = cursor->next_;
779 instruction->previous_ = cursor;
780 cursor->next_ = instruction;
781 instruction->next_->previous_ = instruction;
782 }
783}
784
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100785void HInstructionList::RemoveInstruction(HInstruction* instruction) {
786 if (instruction->previous_ != nullptr) {
787 instruction->previous_->next_ = instruction->next_;
788 }
789 if (instruction->next_ != nullptr) {
790 instruction->next_->previous_ = instruction->previous_;
791 }
792 if (instruction == first_instruction_) {
793 first_instruction_ = instruction->next_;
794 }
795 if (instruction == last_instruction_) {
796 last_instruction_ = instruction->previous_;
797 }
798}
799
Roland Levillain6b469232014-09-25 10:10:38 +0100800bool HInstructionList::Contains(HInstruction* instruction) const {
801 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
802 if (it.Current() == instruction) {
803 return true;
804 }
805 }
806 return false;
807}
808
Roland Levillainccc07a92014-09-16 14:48:16 +0100809bool HInstructionList::FoundBefore(const HInstruction* instruction1,
810 const HInstruction* instruction2) const {
811 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
812 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
813 if (it.Current() == instruction1) {
814 return true;
815 }
816 if (it.Current() == instruction2) {
817 return false;
818 }
819 }
820 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
821 return true;
822}
823
Roland Levillain6c82d402014-10-13 16:10:27 +0100824bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
825 if (other_instruction == this) {
826 // An instruction does not strictly dominate itself.
827 return false;
828 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100829 HBasicBlock* block = GetBlock();
830 HBasicBlock* other_block = other_instruction->GetBlock();
831 if (block != other_block) {
832 return GetBlock()->Dominates(other_instruction->GetBlock());
833 } else {
834 // If both instructions are in the same block, ensure this
835 // instruction comes before `other_instruction`.
836 if (IsPhi()) {
837 if (!other_instruction->IsPhi()) {
838 // Phis appear before non phi-instructions so this instruction
839 // dominates `other_instruction`.
840 return true;
841 } else {
842 // There is no order among phis.
843 LOG(FATAL) << "There is no dominance between phis of a same block.";
844 return false;
845 }
846 } else {
847 // `this` is not a phi.
848 if (other_instruction->IsPhi()) {
849 // Phis appear before non phi-instructions so this instruction
850 // does not dominate `other_instruction`.
851 return false;
852 } else {
853 // Check whether this instruction comes before
854 // `other_instruction` in the instruction list.
855 return block->GetInstructions().FoundBefore(this, other_instruction);
856 }
857 }
858 }
859}
860
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100861void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100862 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000863 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
864 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100865 HInstruction* user = current->GetUser();
866 size_t input_index = current->GetIndex();
867 user->SetRawInputAt(input_index, other);
868 other->AddUseAt(user, input_index);
869 }
870
David Brazdiled596192015-01-23 10:39:45 +0000871 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
872 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100873 HEnvironment* user = current->GetUser();
874 size_t input_index = current->GetIndex();
875 user->SetRawEnvAt(input_index, other);
876 other->AddEnvUseAt(user, input_index);
877 }
878
David Brazdiled596192015-01-23 10:39:45 +0000879 uses_.Clear();
880 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100881}
882
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100883void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000884 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100885 SetRawInputAt(index, replacement);
886 replacement->AddUseAt(this, index);
887}
888
Nicolas Geoffray39468442014-09-02 15:17:15 +0100889size_t HInstruction::EnvironmentSize() const {
890 return HasEnvironment() ? environment_->Size() : 0;
891}
892
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100893void HPhi::AddInput(HInstruction* input) {
894 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000895 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100896 input->AddUseAt(this, inputs_.Size() - 1);
897}
898
David Brazdil2d7352b2015-04-20 14:52:42 +0100899void HPhi::RemoveInputAt(size_t index) {
900 RemoveAsUserOfInput(index);
901 inputs_.DeleteAt(index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100902 for (size_t i = index, e = InputCount(); i < e; ++i) {
903 InputRecordAt(i).GetUseNode()->SetIndex(i);
904 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100905}
906
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100907#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000908void H##name::Accept(HGraphVisitor* visitor) { \
909 visitor->Visit##name(this); \
910}
911
912FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
913
914#undef DEFINE_ACCEPT
915
916void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100917 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
918 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000919 HBasicBlock* block = blocks.Get(i);
920 if (block != nullptr) {
921 VisitBasicBlock(block);
922 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000923 }
924}
925
Roland Levillain633021e2014-10-01 14:12:25 +0100926void HGraphVisitor::VisitReversePostOrder() {
927 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
928 VisitBasicBlock(it.Current());
929 }
930}
931
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000932void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100933 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100934 it.Current()->Accept(this);
935 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100936 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000937 it.Current()->Accept(this);
938 }
939}
940
Mark Mendelle82549b2015-05-06 10:55:34 -0400941HConstant* HTypeConversion::TryStaticEvaluation() const {
942 HGraph* graph = GetBlock()->GetGraph();
943 if (GetInput()->IsIntConstant()) {
944 int32_t value = GetInput()->AsIntConstant()->GetValue();
945 switch (GetResultType()) {
946 case Primitive::kPrimLong:
947 return graph->GetLongConstant(static_cast<int64_t>(value));
948 case Primitive::kPrimFloat:
949 return graph->GetFloatConstant(static_cast<float>(value));
950 case Primitive::kPrimDouble:
951 return graph->GetDoubleConstant(static_cast<double>(value));
952 default:
953 return nullptr;
954 }
955 } else if (GetInput()->IsLongConstant()) {
956 int64_t value = GetInput()->AsLongConstant()->GetValue();
957 switch (GetResultType()) {
958 case Primitive::kPrimInt:
959 return graph->GetIntConstant(static_cast<int32_t>(value));
960 case Primitive::kPrimFloat:
961 return graph->GetFloatConstant(static_cast<float>(value));
962 case Primitive::kPrimDouble:
963 return graph->GetDoubleConstant(static_cast<double>(value));
964 default:
965 return nullptr;
966 }
967 } else if (GetInput()->IsFloatConstant()) {
968 float value = GetInput()->AsFloatConstant()->GetValue();
969 switch (GetResultType()) {
970 case Primitive::kPrimInt:
971 if (std::isnan(value))
972 return graph->GetIntConstant(0);
973 if (value >= kPrimIntMax)
974 return graph->GetIntConstant(kPrimIntMax);
975 if (value <= kPrimIntMin)
976 return graph->GetIntConstant(kPrimIntMin);
977 return graph->GetIntConstant(static_cast<int32_t>(value));
978 case Primitive::kPrimLong:
979 if (std::isnan(value))
980 return graph->GetLongConstant(0);
981 if (value >= kPrimLongMax)
982 return graph->GetLongConstant(kPrimLongMax);
983 if (value <= kPrimLongMin)
984 return graph->GetLongConstant(kPrimLongMin);
985 return graph->GetLongConstant(static_cast<int64_t>(value));
986 case Primitive::kPrimDouble:
987 return graph->GetDoubleConstant(static_cast<double>(value));
988 default:
989 return nullptr;
990 }
991 } else if (GetInput()->IsDoubleConstant()) {
992 double value = GetInput()->AsDoubleConstant()->GetValue();
993 switch (GetResultType()) {
994 case Primitive::kPrimInt:
995 if (std::isnan(value))
996 return graph->GetIntConstant(0);
997 if (value >= kPrimIntMax)
998 return graph->GetIntConstant(kPrimIntMax);
999 if (value <= kPrimLongMin)
1000 return graph->GetIntConstant(kPrimIntMin);
1001 return graph->GetIntConstant(static_cast<int32_t>(value));
1002 case Primitive::kPrimLong:
1003 if (std::isnan(value))
1004 return graph->GetLongConstant(0);
1005 if (value >= kPrimLongMax)
1006 return graph->GetLongConstant(kPrimLongMax);
1007 if (value <= kPrimLongMin)
1008 return graph->GetLongConstant(kPrimLongMin);
1009 return graph->GetLongConstant(static_cast<int64_t>(value));
1010 case Primitive::kPrimFloat:
1011 return graph->GetFloatConstant(static_cast<float>(value));
1012 default:
1013 return nullptr;
1014 }
1015 }
1016 return nullptr;
1017}
1018
Roland Levillain9240d6a2014-10-20 16:47:04 +01001019HConstant* HUnaryOperation::TryStaticEvaluation() const {
1020 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001021 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001022 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001023 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001024 }
1025 return nullptr;
1026}
1027
1028HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001029 if (GetLeft()->IsIntConstant()) {
1030 if (GetRight()->IsIntConstant()) {
1031 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1032 } else if (GetRight()->IsLongConstant()) {
1033 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1034 }
1035 } else if (GetLeft()->IsLongConstant()) {
1036 if (GetRight()->IsIntConstant()) {
1037 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1038 } else if (GetRight()->IsLongConstant()) {
1039 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001040 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001041 }
1042 return nullptr;
1043}
Dave Allison20dfc792014-06-16 20:44:29 -07001044
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001045HConstant* HBinaryOperation::GetConstantRight() const {
1046 if (GetRight()->IsConstant()) {
1047 return GetRight()->AsConstant();
1048 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1049 return GetLeft()->AsConstant();
1050 } else {
1051 return nullptr;
1052 }
1053}
1054
1055// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001056// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001057HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1058 HInstruction* most_constant_right = GetConstantRight();
1059 if (most_constant_right == nullptr) {
1060 return nullptr;
1061 } else if (most_constant_right == GetLeft()) {
1062 return GetRight();
1063 } else {
1064 return GetLeft();
1065 }
1066}
1067
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001068bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1069 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001070}
1071
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001072bool HInstruction::Equals(HInstruction* other) const {
1073 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001074 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001075 if (!InstructionDataEquals(other)) return false;
1076 if (GetType() != other->GetType()) return false;
1077 if (InputCount() != other->InputCount()) return false;
1078
1079 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1080 if (InputAt(i) != other->InputAt(i)) return false;
1081 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001082 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001083 return true;
1084}
1085
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001086std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1087#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1088 switch (rhs) {
1089 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1090 default:
1091 os << "Unknown instruction kind " << static_cast<int>(rhs);
1092 break;
1093 }
1094#undef DECLARE_CASE
1095 return os;
1096}
1097
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001098void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001099 next_->previous_ = previous_;
1100 if (previous_ != nullptr) {
1101 previous_->next_ = next_;
1102 }
1103 if (block_->instructions_.first_instruction_ == this) {
1104 block_->instructions_.first_instruction_ = next_;
1105 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001106 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001107
1108 previous_ = cursor->previous_;
1109 if (previous_ != nullptr) {
1110 previous_->next_ = this;
1111 }
1112 next_ = cursor;
1113 cursor->previous_ = this;
1114 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001115
1116 if (block_->instructions_.first_instruction_ == cursor) {
1117 block_->instructions_.first_instruction_ = this;
1118 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001119}
1120
David Brazdilfc6a86a2015-06-26 10:33:45 +00001121HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
1122 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented";
1123 DCHECK_EQ(cursor->GetBlock(), this);
1124
1125 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1126 new_block->instructions_.first_instruction_ = cursor;
1127 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1128 instructions_.last_instruction_ = cursor->previous_;
1129 if (cursor->previous_ == nullptr) {
1130 instructions_.first_instruction_ = nullptr;
1131 } else {
1132 cursor->previous_->next_ = nullptr;
1133 cursor->previous_ = nullptr;
1134 }
1135
1136 new_block->instructions_.SetBlockOfInstructions(new_block);
1137 AddInstruction(new (GetGraph()->GetArena()) HGoto());
1138
1139 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
1140 HBasicBlock* successor = GetSuccessors().Get(i);
1141 new_block->successors_.Add(successor);
1142 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
1143 }
1144 successors_.Reset();
1145 AddSuccessor(new_block);
1146
David Brazdil56e1acc2015-06-30 15:41:36 +01001147 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001148 return new_block;
1149}
1150
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001151HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1152 DCHECK(!cursor->IsControlFlow());
1153 DCHECK_NE(instructions_.last_instruction_, cursor);
1154 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001155
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001156 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1157 new_block->instructions_.first_instruction_ = cursor->GetNext();
1158 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1159 cursor->next_->previous_ = nullptr;
1160 cursor->next_ = nullptr;
1161 instructions_.last_instruction_ = cursor;
1162
1163 new_block->instructions_.SetBlockOfInstructions(new_block);
1164 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
1165 HBasicBlock* successor = GetSuccessors().Get(i);
1166 new_block->successors_.Add(successor);
1167 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
1168 }
1169 successors_.Reset();
1170
1171 for (size_t i = 0, e = GetDominatedBlocks().Size(); i < e; ++i) {
1172 HBasicBlock* dominated = GetDominatedBlocks().Get(i);
1173 dominated->dominator_ = new_block;
1174 new_block->dominated_blocks_.Add(dominated);
1175 }
1176 dominated_blocks_.Reset();
1177 return new_block;
1178}
1179
David Brazdilec16f792015-08-19 15:04:01 +01001180const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001181 if (EndsWithTryBoundary()) {
1182 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1183 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001184 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001185 return try_boundary;
1186 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001187 DCHECK(IsTryBlock());
1188 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001189 return nullptr;
1190 }
David Brazdilec16f792015-08-19 15:04:01 +01001191 } else if (IsTryBlock()) {
1192 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001193 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001194 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001195 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001196}
1197
1198static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1199 return block.GetPhis().IsEmpty()
1200 && !block.GetInstructions().IsEmpty()
1201 && block.GetFirstInstruction() == block.GetLastInstruction();
1202}
1203
David Brazdil46e2a392015-03-16 17:31:52 +00001204bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001205 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1206}
1207
1208bool HBasicBlock::IsSingleTryBoundary() const {
1209 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001210}
1211
David Brazdil8d5b8b22015-03-24 10:51:52 +00001212bool HBasicBlock::EndsWithControlFlowInstruction() const {
1213 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1214}
1215
David Brazdilb2bd1c52015-03-25 11:17:37 +00001216bool HBasicBlock::EndsWithIf() const {
1217 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1218}
1219
David Brazdilffee3d32015-07-06 11:48:53 +01001220bool HBasicBlock::EndsWithTryBoundary() const {
1221 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1222}
1223
David Brazdilb2bd1c52015-03-25 11:17:37 +00001224bool HBasicBlock::HasSinglePhi() const {
1225 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1226}
1227
David Brazdilffee3d32015-07-06 11:48:53 +01001228bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
1229 if (GetBlock()->GetSuccessors().Size() != other.GetBlock()->GetSuccessors().Size()) {
1230 return false;
1231 }
1232
David Brazdilb618ade2015-07-29 10:31:29 +01001233 // Exception handlers need to be stored in the same order.
1234 for (HExceptionHandlerIterator it1(*this), it2(other);
1235 !it1.Done();
1236 it1.Advance(), it2.Advance()) {
1237 DCHECK(!it2.Done());
1238 if (it1.Current() != it2.Current()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001239 return false;
1240 }
1241 }
1242 return true;
1243}
1244
David Brazdil2d7352b2015-04-20 14:52:42 +01001245size_t HInstructionList::CountSize() const {
1246 size_t size = 0;
1247 HInstruction* current = first_instruction_;
1248 for (; current != nullptr; current = current->GetNext()) {
1249 size++;
1250 }
1251 return size;
1252}
1253
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001254void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1255 for (HInstruction* current = first_instruction_;
1256 current != nullptr;
1257 current = current->GetNext()) {
1258 current->SetBlock(block);
1259 }
1260}
1261
1262void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1263 DCHECK(Contains(cursor));
1264 if (!instruction_list.IsEmpty()) {
1265 if (cursor == last_instruction_) {
1266 last_instruction_ = instruction_list.last_instruction_;
1267 } else {
1268 cursor->next_->previous_ = instruction_list.last_instruction_;
1269 }
1270 instruction_list.last_instruction_->next_ = cursor->next_;
1271 cursor->next_ = instruction_list.first_instruction_;
1272 instruction_list.first_instruction_->previous_ = cursor;
1273 }
1274}
1275
1276void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001277 if (IsEmpty()) {
1278 first_instruction_ = instruction_list.first_instruction_;
1279 last_instruction_ = instruction_list.last_instruction_;
1280 } else {
1281 AddAfter(last_instruction_, instruction_list);
1282 }
1283}
1284
David Brazdil2d7352b2015-04-20 14:52:42 +01001285void HBasicBlock::DisconnectAndDelete() {
1286 // Dominators must be removed after all the blocks they dominate. This way
1287 // a loop header is removed last, a requirement for correct loop information
1288 // iteration.
1289 DCHECK(dominated_blocks_.IsEmpty());
David Brazdil46e2a392015-03-16 17:31:52 +00001290
David Brazdil2d7352b2015-04-20 14:52:42 +01001291 // Remove the block from all loops it is included in.
1292 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1293 HLoopInformation* loop_info = it.Current();
1294 loop_info->Remove(this);
1295 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001296 // If this was the last back edge of the loop, we deliberately leave the
1297 // loop in an inconsistent state and will fail SSAChecker unless the
1298 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001299 loop_info->RemoveBackEdge(this);
1300 }
1301 }
1302
1303 // Disconnect the block from its predecessors and update their control-flow
1304 // instructions.
David Brazdil46e2a392015-03-16 17:31:52 +00001305 for (size_t i = 0, e = predecessors_.Size(); i < e; ++i) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001306 HBasicBlock* predecessor = predecessors_.Get(i);
1307 HInstruction* last_instruction = predecessor->GetLastInstruction();
1308 predecessor->RemoveInstruction(last_instruction);
1309 predecessor->RemoveSuccessor(this);
1310 if (predecessor->GetSuccessors().Size() == 1u) {
1311 DCHECK(last_instruction->IsIf());
1312 predecessor->AddInstruction(new (graph_->GetArena()) HGoto());
1313 } else {
1314 // The predecessor has no remaining successors and therefore must be dead.
1315 // We deliberately leave it without a control-flow instruction so that the
1316 // SSAChecker fails unless it is not removed during the pass too.
1317 DCHECK_EQ(predecessor->GetSuccessors().Size(), 0u);
1318 }
David Brazdil46e2a392015-03-16 17:31:52 +00001319 }
David Brazdil46e2a392015-03-16 17:31:52 +00001320 predecessors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +01001321
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +01001322 // Disconnect the block from its successors and update their phis.
David Brazdil2d7352b2015-04-20 14:52:42 +01001323 for (size_t i = 0, e = successors_.Size(); i < e; ++i) {
1324 HBasicBlock* successor = successors_.Get(i);
1325 // Delete this block from the list of predecessors.
1326 size_t this_index = successor->GetPredecessorIndexOf(this);
1327 successor->predecessors_.DeleteAt(this_index);
1328
1329 // Check that `successor` has other predecessors, otherwise `this` is the
1330 // dominator of `successor` which violates the order DCHECKed at the top.
1331 DCHECK(!successor->predecessors_.IsEmpty());
1332
David Brazdil2d7352b2015-04-20 14:52:42 +01001333 // Remove this block's entries in the successor's phis.
1334 if (successor->predecessors_.Size() == 1u) {
1335 // The successor has just one predecessor left. Replace phis with the only
1336 // remaining input.
1337 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1338 HPhi* phi = phi_it.Current()->AsPhi();
1339 phi->ReplaceWith(phi->InputAt(1 - this_index));
1340 successor->RemovePhi(phi);
1341 }
1342 } else {
1343 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1344 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1345 }
1346 }
1347 }
David Brazdil46e2a392015-03-16 17:31:52 +00001348 successors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +01001349
1350 // Disconnect from the dominator.
1351 dominator_->RemoveDominatedBlock(this);
1352 SetDominator(nullptr);
1353
1354 // Delete from the graph. The function safely deletes remaining instructions
1355 // and updates the reverse post order.
1356 graph_->DeleteDeadBlock(this);
1357 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001358}
1359
1360void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001361 DCHECK_EQ(GetGraph(), other->GetGraph());
1362 DCHECK(GetDominatedBlocks().Contains(other));
1363 DCHECK_EQ(GetSuccessors().Size(), 1u);
1364 DCHECK_EQ(GetSuccessors().Get(0), other);
1365 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1366 DCHECK_EQ(other->GetPredecessors().Get(0), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001367 DCHECK(other->GetPhis().IsEmpty());
1368
David Brazdil2d7352b2015-04-20 14:52:42 +01001369 // Move instructions from `other` to `this`.
1370 DCHECK(EndsWithControlFlowInstruction());
1371 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001372 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001373 other->instructions_.SetBlockOfInstructions(this);
1374 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001375
David Brazdil2d7352b2015-04-20 14:52:42 +01001376 // Remove `other` from the loops it is included in.
1377 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1378 HLoopInformation* loop_info = it.Current();
1379 loop_info->Remove(other);
1380 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001381 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001382 }
1383 }
1384
1385 // Update links to the successors of `other`.
1386 successors_.Reset();
1387 while (!other->successors_.IsEmpty()) {
1388 HBasicBlock* successor = other->successors_.Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001389 successor->ReplacePredecessor(other, this);
1390 }
1391
David Brazdil2d7352b2015-04-20 14:52:42 +01001392 // Update the dominator tree.
1393 dominated_blocks_.Delete(other);
1394 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1395 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1396 dominated_blocks_.Add(dominated);
1397 dominated->SetDominator(this);
1398 }
1399 other->dominated_blocks_.Reset();
1400 other->dominator_ = nullptr;
1401
1402 // Clear the list of predecessors of `other` in preparation of deleting it.
1403 other->predecessors_.Reset();
1404
1405 // Delete `other` from the graph. The function updates reverse post order.
1406 graph_->DeleteDeadBlock(other);
1407 other->SetGraph(nullptr);
1408}
1409
1410void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1411 DCHECK_NE(GetGraph(), other->GetGraph());
1412 DCHECK(GetDominatedBlocks().IsEmpty());
1413 DCHECK(GetSuccessors().IsEmpty());
1414 DCHECK(!EndsWithControlFlowInstruction());
1415 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1416 DCHECK(other->GetPredecessors().Get(0)->IsEntryBlock());
1417 DCHECK(other->GetPhis().IsEmpty());
1418 DCHECK(!other->IsInLoop());
1419
1420 // Move instructions from `other` to `this`.
1421 instructions_.Add(other->GetInstructions());
1422 other->instructions_.SetBlockOfInstructions(this);
1423
1424 // Update links to the successors of `other`.
1425 successors_.Reset();
1426 while (!other->successors_.IsEmpty()) {
1427 HBasicBlock* successor = other->successors_.Get(0);
1428 successor->ReplacePredecessor(other, this);
1429 }
1430
1431 // Update the dominator tree.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001432 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1433 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1434 dominated_blocks_.Add(dominated);
1435 dominated->SetDominator(this);
1436 }
1437 other->dominated_blocks_.Reset();
1438 other->dominator_ = nullptr;
1439 other->graph_ = nullptr;
1440}
1441
1442void HBasicBlock::ReplaceWith(HBasicBlock* other) {
1443 while (!GetPredecessors().IsEmpty()) {
1444 HBasicBlock* predecessor = GetPredecessors().Get(0);
1445 predecessor->ReplaceSuccessor(this, other);
1446 }
1447 while (!GetSuccessors().IsEmpty()) {
1448 HBasicBlock* successor = GetSuccessors().Get(0);
1449 successor->ReplacePredecessor(this, other);
1450 }
1451 for (size_t i = 0; i < dominated_blocks_.Size(); ++i) {
1452 other->AddDominatedBlock(dominated_blocks_.Get(i));
1453 }
1454 GetDominator()->ReplaceDominatedBlock(this, other);
1455 other->SetDominator(GetDominator());
1456 dominator_ = nullptr;
1457 graph_ = nullptr;
1458}
1459
1460// Create space in `blocks` for adding `number_of_new_blocks` entries
1461// starting at location `at`. Blocks after `at` are moved accordingly.
1462static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
1463 size_t number_of_new_blocks,
1464 size_t at) {
1465 size_t old_size = blocks->Size();
1466 size_t new_size = old_size + number_of_new_blocks;
1467 blocks->SetSize(new_size);
1468 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
1469 blocks->Put(j, blocks->Get(i));
1470 }
1471}
1472
David Brazdil2d7352b2015-04-20 14:52:42 +01001473void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1474 DCHECK_EQ(block->GetGraph(), this);
1475 DCHECK(block->GetSuccessors().IsEmpty());
1476 DCHECK(block->GetPredecessors().IsEmpty());
1477 DCHECK(block->GetDominatedBlocks().IsEmpty());
1478 DCHECK(block->GetDominator() == nullptr);
1479
1480 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1481 block->RemoveInstruction(it.Current());
1482 }
1483 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1484 block->RemovePhi(it.Current()->AsPhi());
1485 }
1486
David Brazdilc7af85d2015-05-26 12:05:55 +01001487 if (block->IsExitBlock()) {
1488 exit_block_ = nullptr;
1489 }
1490
David Brazdil2d7352b2015-04-20 14:52:42 +01001491 reverse_post_order_.Delete(block);
1492 blocks_.Put(block->GetBlockId(), nullptr);
1493}
1494
Calin Juravle2e768302015-07-28 14:41:11 +00001495HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001496 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001497 // Update the environments in this graph to have the invoke's environment
1498 // as parent.
1499 {
1500 HReversePostOrderIterator it(*this);
1501 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1502 for (; !it.Done(); it.Advance()) {
1503 HBasicBlock* block = it.Current();
1504 for (HInstructionIterator instr_it(block->GetInstructions());
1505 !instr_it.Done();
1506 instr_it.Advance()) {
1507 HInstruction* current = instr_it.Current();
1508 if (current->NeedsEnvironment()) {
1509 current->GetEnvironment()->SetAndCopyParentChain(
1510 outer_graph->GetArena(), invoke->GetEnvironment());
1511 }
1512 }
1513 }
1514 }
1515 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1516 if (HasBoundsChecks()) {
1517 outer_graph->SetHasBoundsChecks(true);
1518 }
1519
Calin Juravle2e768302015-07-28 14:41:11 +00001520 HInstruction* return_value = nullptr;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001521 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001522 // Simple case of an entry block, a body block, and an exit block.
1523 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001524 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001525 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
1526 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001527 DCHECK(!body->IsExitBlock());
1528 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001529
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001530 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1531 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001532
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001533 // Replace the invoke with the return value of the inlined graph.
1534 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001535 return_value = last->InputAt(0);
1536 invoke->ReplaceWith(return_value);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001537 } else {
1538 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001539 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001540
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001541 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001542 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001543 // Need to inline multiple blocks. We split `invoke`'s block
1544 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001545 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001546 // with the second half.
1547 ArenaAllocator* allocator = outer_graph->GetArena();
1548 HBasicBlock* at = invoke->GetBlock();
1549 HBasicBlock* to = at->SplitAfter(invoke);
1550
1551 HBasicBlock* first = entry_block_->GetSuccessors().Get(0);
1552 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001553 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001554 exit_block_->ReplaceWith(to);
1555
1556 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001557 // to not `HReturn` but `HGoto` instead.
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001558 bool returns_void = to->GetPredecessors().Get(0)->GetLastInstruction()->IsReturnVoid();
1559 if (to->GetPredecessors().Size() == 1) {
1560 HBasicBlock* predecessor = to->GetPredecessors().Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001561 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001562 if (!returns_void) {
1563 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001564 }
1565 predecessor->AddInstruction(new (allocator) HGoto());
1566 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001567 } else {
1568 if (!returns_void) {
1569 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001570 return_value = new (allocator) HPhi(
1571 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001572 to->AddPhi(return_value->AsPhi());
1573 }
1574 for (size_t i = 0, e = to->GetPredecessors().Size(); i < e; ++i) {
1575 HBasicBlock* predecessor = to->GetPredecessors().Get(i);
1576 HInstruction* last = predecessor->GetLastInstruction();
1577 if (!returns_void) {
1578 return_value->AsPhi()->AddInput(last->InputAt(0));
1579 }
1580 predecessor->AddInstruction(new (allocator) HGoto());
1581 predecessor->RemoveInstruction(last);
1582 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001583 }
1584
1585 if (return_value != nullptr) {
1586 invoke->ReplaceWith(return_value);
1587 }
1588
1589 // Update the meta information surrounding blocks:
1590 // (1) the graph they are now in,
1591 // (2) the reverse post order of that graph,
1592 // (3) the potential loop information they are now in.
1593
1594 // We don't add the entry block, the exit block, and the first block, which
1595 // has been merged with `at`.
1596 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1597
1598 // We add the `to` block.
1599 static constexpr int kNumberOfNewBlocksInCaller = 1;
1600 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1601 + kNumberOfNewBlocksInCaller;
1602
1603 // Find the location of `at` in the outer graph's reverse post order. The new
1604 // blocks will be added after it.
1605 size_t index_of_at = 0;
1606 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1607 index_of_at++;
1608 }
1609 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1610
1611 // Do a reverse post order of the blocks in the callee and do (1), (2),
1612 // and (3) to the blocks that apply.
1613 HLoopInformation* info = at->GetLoopInformation();
1614 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1615 HBasicBlock* current = it.Current();
1616 if (current != exit_block_ && current != entry_block_ && current != first) {
1617 DCHECK(!current->IsInLoop());
1618 DCHECK(current->GetGraph() == this);
1619 current->SetGraph(outer_graph);
1620 outer_graph->AddBlock(current);
1621 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1622 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001623 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001624 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1625 loop_it.Current()->Add(current);
1626 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001627 }
1628 }
1629 }
1630
1631 // Do (1), (2), and (3) to `to`.
1632 to->SetGraph(outer_graph);
1633 outer_graph->AddBlock(to);
1634 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1635 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001636 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001637 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1638 loop_it.Current()->Add(to);
1639 }
David Brazdil46e2a392015-03-16 17:31:52 +00001640 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001641 // Only `to` can become a back edge, as the inlined blocks
1642 // are predecessors of `to`.
1643 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001644 }
1645 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001646 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001647
David Brazdil05144f42015-04-16 15:18:00 +01001648 // Update the next instruction id of the outer graph, so that instructions
1649 // added later get bigger ids than those in the inner graph.
1650 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1651
1652 // Walk over the entry block and:
1653 // - Move constants from the entry block to the outer_graph's entry block,
1654 // - Replace HParameterValue instructions with their real value.
1655 // - Remove suspend checks, that hold an environment.
1656 // We must do this after the other blocks have been inlined, otherwise ids of
1657 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001658 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001659 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1660 HInstruction* current = it.Current();
1661 if (current->IsNullConstant()) {
1662 current->ReplaceWith(outer_graph->GetNullConstant());
1663 } else if (current->IsIntConstant()) {
1664 current->ReplaceWith(outer_graph->GetIntConstant(current->AsIntConstant()->GetValue()));
1665 } else if (current->IsLongConstant()) {
1666 current->ReplaceWith(outer_graph->GetLongConstant(current->AsLongConstant()->GetValue()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001667 } else if (current->IsFloatConstant()) {
1668 current->ReplaceWith(outer_graph->GetFloatConstant(current->AsFloatConstant()->GetValue()));
1669 } else if (current->IsDoubleConstant()) {
1670 current->ReplaceWith(outer_graph->GetDoubleConstant(current->AsDoubleConstant()->GetValue()));
David Brazdil05144f42015-04-16 15:18:00 +01001671 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001672 if (kIsDebugBuild
1673 && invoke->IsInvokeStaticOrDirect()
1674 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1675 // Ensure we do not use the last input of `invoke`, as it
1676 // contains a clinit check which is not an actual argument.
1677 size_t last_input_index = invoke->InputCount() - 1;
1678 DCHECK(parameter_index != last_input_index);
1679 }
David Brazdil05144f42015-04-16 15:18:00 +01001680 current->ReplaceWith(invoke->InputAt(parameter_index++));
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001681 } else if (current->IsCurrentMethod()) {
1682 current->ReplaceWith(outer_graph->GetCurrentMethod());
David Brazdil05144f42015-04-16 15:18:00 +01001683 } else {
1684 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1685 entry_block_->RemoveInstruction(current);
1686 }
1687 }
1688
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001689 // Finally remove the invoke from the caller.
1690 invoke->GetBlock()->RemoveInstruction(invoke);
Calin Juravle2e768302015-07-28 14:41:11 +00001691
1692 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001693}
1694
Mingyao Yang3584bce2015-05-19 16:01:59 -07001695/*
1696 * Loop will be transformed to:
1697 * old_pre_header
1698 * |
1699 * if_block
1700 * / \
1701 * dummy_block deopt_block
1702 * \ /
1703 * new_pre_header
1704 * |
1705 * header
1706 */
1707void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1708 DCHECK(header->IsLoopHeader());
1709 HBasicBlock* pre_header = header->GetDominator();
1710
1711 // Need this to avoid critical edge.
1712 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1713 // Need this to avoid critical edge.
1714 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1715 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1716 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1717 AddBlock(if_block);
1718 AddBlock(dummy_block);
1719 AddBlock(deopt_block);
1720 AddBlock(new_pre_header);
1721
1722 header->ReplacePredecessor(pre_header, new_pre_header);
1723 pre_header->successors_.Reset();
1724 pre_header->dominated_blocks_.Reset();
1725
1726 pre_header->AddSuccessor(if_block);
1727 if_block->AddSuccessor(dummy_block); // True successor
1728 if_block->AddSuccessor(deopt_block); // False successor
1729 dummy_block->AddSuccessor(new_pre_header);
1730 deopt_block->AddSuccessor(new_pre_header);
1731
1732 pre_header->dominated_blocks_.Add(if_block);
1733 if_block->SetDominator(pre_header);
1734 if_block->dominated_blocks_.Add(dummy_block);
1735 dummy_block->SetDominator(if_block);
1736 if_block->dominated_blocks_.Add(deopt_block);
1737 deopt_block->SetDominator(if_block);
1738 if_block->dominated_blocks_.Add(new_pre_header);
1739 new_pre_header->SetDominator(if_block);
1740 new_pre_header->dominated_blocks_.Add(header);
1741 header->SetDominator(new_pre_header);
1742
1743 size_t index_of_header = 0;
1744 while (reverse_post_order_.Get(index_of_header) != header) {
1745 index_of_header++;
1746 }
1747 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
1748 reverse_post_order_.Put(index_of_header++, if_block);
1749 reverse_post_order_.Put(index_of_header++, dummy_block);
1750 reverse_post_order_.Put(index_of_header++, deopt_block);
1751 reverse_post_order_.Put(index_of_header++, new_pre_header);
1752
1753 HLoopInformation* info = pre_header->GetLoopInformation();
1754 if (info != nullptr) {
1755 if_block->SetLoopInformation(info);
1756 dummy_block->SetLoopInformation(info);
1757 deopt_block->SetLoopInformation(info);
1758 new_pre_header->SetLoopInformation(info);
1759 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1760 !loop_it.Done();
1761 loop_it.Advance()) {
1762 loop_it.Current()->Add(if_block);
1763 loop_it.Current()->Add(dummy_block);
1764 loop_it.Current()->Add(deopt_block);
1765 loop_it.Current()->Add(new_pre_header);
1766 }
1767 }
1768}
1769
Calin Juravle2e768302015-07-28 14:41:11 +00001770void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
1771 if (kIsDebugBuild) {
1772 DCHECK_EQ(GetType(), Primitive::kPrimNot);
1773 ScopedObjectAccess soa(Thread::Current());
1774 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
1775 if (IsBoundType()) {
1776 // Having the test here spares us from making the method virtual just for
1777 // the sake of a DCHECK.
1778 ReferenceTypeInfo upper_bound_rti = AsBoundType()->GetUpperBound();
1779 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
1780 << " upper_bound_rti: " << upper_bound_rti
1781 << " rti: " << rti;
1782 DCHECK(!upper_bound_rti.GetTypeHandle()->IsFinal() || rti.IsExact());
1783 }
1784 }
1785 reference_type_info_ = rti;
1786}
1787
1788ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
1789
1790ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
1791 : type_handle_(type_handle), is_exact_(is_exact) {
1792 if (kIsDebugBuild) {
1793 ScopedObjectAccess soa(Thread::Current());
1794 DCHECK(IsValidHandle(type_handle));
1795 }
1796}
1797
Calin Juravleacf735c2015-02-12 15:25:22 +00001798std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1799 ScopedObjectAccess soa(Thread::Current());
1800 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00001801 << " is_valid=" << rhs.IsValid()
1802 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00001803 << " is_exact=" << rhs.IsExact()
1804 << " ]";
1805 return os;
1806}
1807
Mark Mendellc4701932015-04-10 13:18:51 -04001808bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
1809 // For now, assume that instructions in different blocks may use the
1810 // environment.
1811 // TODO: Use the control flow to decide if this is true.
1812 if (GetBlock() != other->GetBlock()) {
1813 return true;
1814 }
1815
1816 // We know that we are in the same block. Walk from 'this' to 'other',
1817 // checking to see if there is any instruction with an environment.
1818 HInstruction* current = this;
1819 for (; current != other && current != nullptr; current = current->GetNext()) {
1820 // This is a conservative check, as the instruction result may not be in
1821 // the referenced environment.
1822 if (current->HasEnvironment()) {
1823 return true;
1824 }
1825 }
1826
1827 // We should have been called with 'this' before 'other' in the block.
1828 // Just confirm this.
1829 DCHECK(current != nullptr);
1830 return false;
1831}
1832
1833void HInstruction::RemoveEnvironmentUsers() {
1834 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
1835 HUseListNode<HEnvironment*>* user_node = use_it.Current();
1836 HEnvironment* user = user_node->GetUser();
1837 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
1838 }
1839 env_uses_.Clear();
1840}
1841
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001842} // namespace art