blob: 01eb2d7f864b1d2e9076332b197583d11dbcc489 [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() {
101 ArenaBitVector visited(arena_, blocks_.Size(), false);
102
103 // (1) Find the back edges in the graph doing a DFS traversal.
104 FindBackEdges(&visited);
105
Roland Levillainfc600dc2014-12-02 17:16:31 +0000106 // (2) Remove instructions and phis from blocks not visited during
107 // the initial DFS as users from other instructions, so that
108 // users can be safely removed before uses later.
109 RemoveInstructionsAsUsersFromDeadBlocks(visited);
110
111 // (3) Remove blocks not visited during the initial DFS.
112 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000113 // predecessors list of live blocks.
114 RemoveDeadBlocks(visited);
115
Roland Levillainfc600dc2014-12-02 17:16:31 +0000116 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100117 // dominators and the reverse post order.
118 SimplifyCFG();
119
Roland Levillainfc600dc2014-12-02 17:16:31 +0000120 // (5) Compute the immediate dominator of each block. We visit
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000121 // the successors of a block only when all its forward branches
122 // have been processed.
123 GrowableArray<size_t> visits(arena_, blocks_.Size());
124 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100125 reverse_post_order_.Add(entry_block_);
126 for (size_t i = 0; i < entry_block_->GetSuccessors().Size(); i++) {
127 VisitBlockForDominatorTree(entry_block_->GetSuccessors().Get(i), entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000128 }
129}
130
131HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
132 ArenaBitVector visited(arena_, blocks_.Size(), false);
133 // Walk the dominator tree of the first block and mark the visited blocks.
134 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000135 visited.SetBit(first->GetBlockId());
136 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000137 }
138 // Walk the dominator tree of the second block until a marked block is found.
139 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000140 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000141 return second;
142 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000143 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000144 }
145 LOG(ERROR) << "Could not find common dominator";
146 return nullptr;
147}
148
149void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
150 HBasicBlock* predecessor,
151 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000152 if (block->GetDominator() == nullptr) {
153 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000154 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000155 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000156 }
157
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000158 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000159 // Once all the forward edges have been visited, we know the immediate
160 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000161 if (visits->Get(block->GetBlockId()) ==
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100162 block->GetPredecessors().Size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100163 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100164 reverse_post_order_.Add(block);
165 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
166 VisitBlockForDominatorTree(block->GetSuccessors().Get(i), block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000167 }
168 }
169}
170
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000171void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100172 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100173 SsaBuilder ssa_builder(this);
174 ssa_builder.BuildSsa();
175}
176
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100177void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
178 // Insert a new node between `block` and `successor` to split the
179 // critical edge.
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100180 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100181 AddBlock(new_block);
182 new_block->AddInstruction(new (arena_) HGoto());
Nicolas Geoffray8b20f882015-06-19 16:17:05 +0100183 // Use `InsertBetween` to ensure the predecessor index and successor index of
184 // `block` and `successor` are preserved.
185 new_block->InsertBetween(block, successor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100186 if (successor->IsLoopHeader()) {
187 // If we split at a back edge boundary, make the new block the back edge.
188 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000189 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100190 info->RemoveBackEdge(block);
191 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100192 }
193 }
194}
195
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100196void HGraph::SimplifyLoop(HBasicBlock* header) {
197 HLoopInformation* info = header->GetLoopInformation();
198
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100199 // Make sure the loop has only one pre header. This simplifies SSA building by having
200 // to just look at the pre header to know which locals are initialized at entry of the
201 // loop.
202 size_t number_of_incomings = header->GetPredecessors().Size() - info->NumberOfBackEdges();
203 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100204 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100205 AddBlock(pre_header);
206 pre_header->AddInstruction(new (arena_) HGoto());
207
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100208 for (size_t pred = 0; pred < header->GetPredecessors().Size(); ++pred) {
209 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100210 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100211 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100212 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100213 }
214 }
215 pre_header->AddSuccessor(header);
216 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100217
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100218 // Make sure the first predecessor of a loop header is the incoming block.
219 if (info->IsBackEdge(*header->GetPredecessors().Get(0))) {
220 HBasicBlock* to_swap = header->GetPredecessors().Get(0);
221 for (size_t pred = 1, e = header->GetPredecessors().Size(); pred < e; ++pred) {
222 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
223 if (!info->IsBackEdge(*predecessor)) {
224 header->predecessors_.Put(pred, to_swap);
225 header->predecessors_.Put(0, predecessor);
226 break;
227 }
228 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100229 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100230
231 // Place the suspend check at the beginning of the header, so that live registers
232 // will be known when allocating registers. Note that code generation can still
233 // generate the suspend check at the back edge, but needs to be careful with
234 // loop phi spill slots (which are not written to at back edge).
235 HInstruction* first_instruction = header->GetFirstInstruction();
236 if (!first_instruction->IsSuspendCheck()) {
237 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
238 header->InsertInstructionBefore(check, first_instruction);
239 first_instruction = check;
240 }
241 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100242}
243
244void HGraph::SimplifyCFG() {
245 // Simplify the CFG for future analysis, and code generation:
246 // (1): Split critical edges.
247 // (2): Simplify loops by having only one back edge, and one preheader.
248 for (size_t i = 0; i < blocks_.Size(); ++i) {
249 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100250 if (block == nullptr) continue;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100251 if (block->GetSuccessors().Size() > 1) {
252 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
253 HBasicBlock* successor = block->GetSuccessors().Get(j);
254 if (successor->GetPredecessors().Size() > 1) {
255 SplitCriticalEdge(block, successor);
256 --j;
257 }
258 }
259 }
260 if (block->IsLoopHeader()) {
261 SimplifyLoop(block);
262 }
263 }
264}
265
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000266bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100267 // Order does not matter.
268 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
269 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100270 if (block->IsLoopHeader()) {
271 HLoopInformation* info = block->GetLoopInformation();
272 if (!info->Populate()) {
273 // Abort if the loop is non natural. We currently bailout in such cases.
274 return false;
275 }
276 }
277 }
278 return true;
279}
280
David Brazdil8d5b8b22015-03-24 10:51:52 +0000281void HGraph::InsertConstant(HConstant* constant) {
282 // New constants are inserted before the final control-flow instruction
283 // of the graph, or at its end if called from the graph builder.
284 if (entry_block_->EndsWithControlFlowInstruction()) {
285 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000286 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000287 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000288 }
289}
290
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000291HNullConstant* HGraph::GetNullConstant() {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100292 // For simplicity, don't bother reviving the cached null constant if it is
293 // not null and not in a block. Otherwise, we need to clear the instruction
294 // id and/or any invariants the graph is assuming when adding new instructions.
295 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000296 cached_null_constant_ = new (arena_) HNullConstant();
David Brazdil8d5b8b22015-03-24 10:51:52 +0000297 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000298 }
299 return cached_null_constant_;
300}
301
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100302HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100303 // For simplicity, don't bother reviving the cached current method if it is
304 // not null and not in a block. Otherwise, we need to clear the instruction
305 // id and/or any invariants the graph is assuming when adding new instructions.
306 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700307 cached_current_method_ = new (arena_) HCurrentMethod(
308 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100309 if (entry_block_->GetFirstInstruction() == nullptr) {
310 entry_block_->AddInstruction(cached_current_method_);
311 } else {
312 entry_block_->InsertInstructionBefore(
313 cached_current_method_, entry_block_->GetFirstInstruction());
314 }
315 }
316 return cached_current_method_;
317}
318
David Brazdil8d5b8b22015-03-24 10:51:52 +0000319HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value) {
320 switch (type) {
321 case Primitive::Type::kPrimBoolean:
322 DCHECK(IsUint<1>(value));
323 FALLTHROUGH_INTENDED;
324 case Primitive::Type::kPrimByte:
325 case Primitive::Type::kPrimChar:
326 case Primitive::Type::kPrimShort:
327 case Primitive::Type::kPrimInt:
328 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
329 return GetIntConstant(static_cast<int32_t>(value));
330
331 case Primitive::Type::kPrimLong:
332 return GetLongConstant(value);
333
334 default:
335 LOG(FATAL) << "Unsupported constant type";
336 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000337 }
David Brazdil46e2a392015-03-16 17:31:52 +0000338}
339
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000340void HGraph::CacheFloatConstant(HFloatConstant* constant) {
341 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
342 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
343 cached_float_constants_.Overwrite(value, constant);
344}
345
346void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
347 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
348 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
349 cached_double_constants_.Overwrite(value, constant);
350}
351
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000352void HLoopInformation::Add(HBasicBlock* block) {
353 blocks_.SetBit(block->GetBlockId());
354}
355
David Brazdil46e2a392015-03-16 17:31:52 +0000356void HLoopInformation::Remove(HBasicBlock* block) {
357 blocks_.ClearBit(block->GetBlockId());
358}
359
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100360void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
361 if (blocks_.IsBitSet(block->GetBlockId())) {
362 return;
363 }
364
365 blocks_.SetBit(block->GetBlockId());
366 block->SetInLoop(this);
367 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
368 PopulateRecursive(block->GetPredecessors().Get(i));
369 }
370}
371
372bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100373 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100374 for (size_t i = 0, e = GetBackEdges().Size(); i < e; ++i) {
375 HBasicBlock* back_edge = GetBackEdges().Get(i);
376 DCHECK(back_edge->GetDominator() != nullptr);
377 if (!header_->Dominates(back_edge)) {
378 // This loop is not natural. Do not bother going further.
379 return false;
380 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100381
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100382 // Populate this loop: starting with the back edge, recursively add predecessors
383 // that are not already part of that loop. Set the header as part of the loop
384 // to end the recursion.
385 // This is a recursive implementation of the algorithm described in
386 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
387 blocks_.SetBit(header_->GetBlockId());
388 PopulateRecursive(back_edge);
389 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100390 return true;
391}
392
David Brazdila4b8c212015-05-07 09:59:30 +0100393void HLoopInformation::Update() {
394 HGraph* graph = header_->GetGraph();
395 for (uint32_t id : blocks_.Indexes()) {
396 HBasicBlock* block = graph->GetBlocks().Get(id);
397 // Reset loop information of non-header blocks inside the loop, except
398 // members of inner nested loops because those should already have been
399 // updated by their own LoopInformation.
400 if (block->GetLoopInformation() == this && block != header_) {
401 block->SetLoopInformation(nullptr);
402 }
403 }
404 blocks_.ClearAllBits();
405
406 if (back_edges_.IsEmpty()) {
407 // The loop has been dismantled, delete its suspend check and remove info
408 // from the header.
409 DCHECK(HasSuspendCheck());
410 header_->RemoveInstruction(suspend_check_);
411 header_->SetLoopInformation(nullptr);
412 header_ = nullptr;
413 suspend_check_ = nullptr;
414 } else {
415 if (kIsDebugBuild) {
416 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
417 DCHECK(header_->Dominates(back_edges_.Get(i)));
418 }
419 }
420 // This loop still has reachable back edges. Repopulate the list of blocks.
421 bool populate_successful = Populate();
422 DCHECK(populate_successful);
423 }
424}
425
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100426HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100427 return header_->GetDominator();
428}
429
430bool HLoopInformation::Contains(const HBasicBlock& block) const {
431 return blocks_.IsBitSet(block.GetBlockId());
432}
433
434bool HLoopInformation::IsIn(const HLoopInformation& other) const {
435 return other.blocks_.IsBitSet(header_->GetBlockId());
436}
437
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100438size_t HLoopInformation::GetLifetimeEnd() const {
439 size_t last_position = 0;
440 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
441 last_position = std::max(back_edges_.Get(i)->GetLifetimeEnd(), last_position);
442 }
443 return last_position;
444}
445
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100446bool HBasicBlock::Dominates(HBasicBlock* other) const {
447 // Walk up the dominator tree from `other`, to find out if `this`
448 // is an ancestor.
449 HBasicBlock* current = other;
450 while (current != nullptr) {
451 if (current == this) {
452 return true;
453 }
454 current = current->GetDominator();
455 }
456 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100457}
458
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100459static void UpdateInputsUsers(HInstruction* instruction) {
460 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
461 instruction->InputAt(i)->AddUseAt(instruction, i);
462 }
463 // Environment should be created later.
464 DCHECK(!instruction->HasEnvironment());
465}
466
Roland Levillainccc07a92014-09-16 14:48:16 +0100467void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
468 HInstruction* replacement) {
469 DCHECK(initial->GetBlock() == this);
470 InsertInstructionBefore(replacement, initial);
471 initial->ReplaceWith(replacement);
472 RemoveInstruction(initial);
473}
474
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100475static void Add(HInstructionList* instruction_list,
476 HBasicBlock* block,
477 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000478 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000479 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100480 instruction->SetBlock(block);
481 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100482 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100483 instruction_list->AddInstruction(instruction);
484}
485
486void HBasicBlock::AddInstruction(HInstruction* instruction) {
487 Add(&instructions_, this, instruction);
488}
489
490void HBasicBlock::AddPhi(HPhi* phi) {
491 Add(&phis_, this, phi);
492}
493
David Brazdilc3d743f2015-04-22 13:40:50 +0100494void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
495 DCHECK(!cursor->IsPhi());
496 DCHECK(!instruction->IsPhi());
497 DCHECK_EQ(instruction->GetId(), -1);
498 DCHECK_NE(cursor->GetId(), -1);
499 DCHECK_EQ(cursor->GetBlock(), this);
500 DCHECK(!instruction->IsControlFlow());
501 instruction->SetBlock(this);
502 instruction->SetId(GetGraph()->GetNextInstructionId());
503 UpdateInputsUsers(instruction);
504 instructions_.InsertInstructionBefore(instruction, cursor);
505}
506
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100507void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
508 DCHECK(!cursor->IsPhi());
509 DCHECK(!instruction->IsPhi());
510 DCHECK_EQ(instruction->GetId(), -1);
511 DCHECK_NE(cursor->GetId(), -1);
512 DCHECK_EQ(cursor->GetBlock(), this);
513 DCHECK(!instruction->IsControlFlow());
514 DCHECK(!cursor->IsControlFlow());
515 instruction->SetBlock(this);
516 instruction->SetId(GetGraph()->GetNextInstructionId());
517 UpdateInputsUsers(instruction);
518 instructions_.InsertInstructionAfter(instruction, cursor);
519}
520
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100521void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
522 DCHECK_EQ(phi->GetId(), -1);
523 DCHECK_NE(cursor->GetId(), -1);
524 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100525 phi->SetBlock(this);
526 phi->SetId(GetGraph()->GetNextInstructionId());
527 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100528 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100529}
530
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100531static void Remove(HInstructionList* instruction_list,
532 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000533 HInstruction* instruction,
534 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100535 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100536 instruction->SetBlock(nullptr);
537 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000538 if (ensure_safety) {
539 DCHECK(instruction->GetUses().IsEmpty());
540 DCHECK(instruction->GetEnvUses().IsEmpty());
541 RemoveAsUser(instruction);
542 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100543}
544
David Brazdil1abb4192015-02-17 18:33:36 +0000545void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100546 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000547 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100548}
549
David Brazdil1abb4192015-02-17 18:33:36 +0000550void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
551 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100552}
553
David Brazdilc7508e92015-04-27 13:28:57 +0100554void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
555 if (instruction->IsPhi()) {
556 RemovePhi(instruction->AsPhi(), ensure_safety);
557 } else {
558 RemoveInstruction(instruction, ensure_safety);
559 }
560}
561
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100562void HEnvironment::CopyFrom(const GrowableArray<HInstruction*>& locals) {
563 for (size_t i = 0; i < locals.Size(); i++) {
564 HInstruction* instruction = locals.Get(i);
565 SetRawEnvAt(i, instruction);
566 if (instruction != nullptr) {
567 instruction->AddEnvUseAt(this, i);
568 }
569 }
570}
571
David Brazdiled596192015-01-23 10:39:45 +0000572void HEnvironment::CopyFrom(HEnvironment* env) {
573 for (size_t i = 0; i < env->Size(); i++) {
574 HInstruction* instruction = env->GetInstructionAt(i);
575 SetRawEnvAt(i, instruction);
576 if (instruction != nullptr) {
577 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100578 }
David Brazdiled596192015-01-23 10:39:45 +0000579 }
580}
581
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700582void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
583 HBasicBlock* loop_header) {
584 DCHECK(loop_header->IsLoopHeader());
585 for (size_t i = 0; i < env->Size(); i++) {
586 HInstruction* instruction = env->GetInstructionAt(i);
587 SetRawEnvAt(i, instruction);
588 if (instruction == nullptr) {
589 continue;
590 }
591 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
592 // At the end of the loop pre-header, the corresponding value for instruction
593 // is the first input of the phi.
594 HInstruction* initial = instruction->AsPhi()->InputAt(0);
595 DCHECK(initial->GetBlock()->Dominates(loop_header));
596 SetRawEnvAt(i, initial);
597 initial->AddEnvUseAt(this, i);
598 } else {
599 instruction->AddEnvUseAt(this, i);
600 }
601 }
602}
603
David Brazdil1abb4192015-02-17 18:33:36 +0000604void HEnvironment::RemoveAsUserOfInput(size_t index) const {
605 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
606 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100607}
608
Calin Juravle77520bc2015-01-12 18:45:46 +0000609HInstruction* HInstruction::GetNextDisregardingMoves() const {
610 HInstruction* next = GetNext();
611 while (next != nullptr && next->IsParallelMove()) {
612 next = next->GetNext();
613 }
614 return next;
615}
616
617HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
618 HInstruction* previous = GetPrevious();
619 while (previous != nullptr && previous->IsParallelMove()) {
620 previous = previous->GetPrevious();
621 }
622 return previous;
623}
624
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100625void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000626 if (first_instruction_ == nullptr) {
627 DCHECK(last_instruction_ == nullptr);
628 first_instruction_ = last_instruction_ = instruction;
629 } else {
630 last_instruction_->next_ = instruction;
631 instruction->previous_ = last_instruction_;
632 last_instruction_ = instruction;
633 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000634}
635
David Brazdilc3d743f2015-04-22 13:40:50 +0100636void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
637 DCHECK(Contains(cursor));
638 if (cursor == first_instruction_) {
639 cursor->previous_ = instruction;
640 instruction->next_ = cursor;
641 first_instruction_ = instruction;
642 } else {
643 instruction->previous_ = cursor->previous_;
644 instruction->next_ = cursor;
645 cursor->previous_ = instruction;
646 instruction->previous_->next_ = instruction;
647 }
648}
649
650void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
651 DCHECK(Contains(cursor));
652 if (cursor == last_instruction_) {
653 cursor->next_ = instruction;
654 instruction->previous_ = cursor;
655 last_instruction_ = instruction;
656 } else {
657 instruction->next_ = cursor->next_;
658 instruction->previous_ = cursor;
659 cursor->next_ = instruction;
660 instruction->next_->previous_ = instruction;
661 }
662}
663
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100664void HInstructionList::RemoveInstruction(HInstruction* instruction) {
665 if (instruction->previous_ != nullptr) {
666 instruction->previous_->next_ = instruction->next_;
667 }
668 if (instruction->next_ != nullptr) {
669 instruction->next_->previous_ = instruction->previous_;
670 }
671 if (instruction == first_instruction_) {
672 first_instruction_ = instruction->next_;
673 }
674 if (instruction == last_instruction_) {
675 last_instruction_ = instruction->previous_;
676 }
677}
678
Roland Levillain6b469232014-09-25 10:10:38 +0100679bool HInstructionList::Contains(HInstruction* instruction) const {
680 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
681 if (it.Current() == instruction) {
682 return true;
683 }
684 }
685 return false;
686}
687
Roland Levillainccc07a92014-09-16 14:48:16 +0100688bool HInstructionList::FoundBefore(const HInstruction* instruction1,
689 const HInstruction* instruction2) const {
690 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
691 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
692 if (it.Current() == instruction1) {
693 return true;
694 }
695 if (it.Current() == instruction2) {
696 return false;
697 }
698 }
699 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
700 return true;
701}
702
Roland Levillain6c82d402014-10-13 16:10:27 +0100703bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
704 if (other_instruction == this) {
705 // An instruction does not strictly dominate itself.
706 return false;
707 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100708 HBasicBlock* block = GetBlock();
709 HBasicBlock* other_block = other_instruction->GetBlock();
710 if (block != other_block) {
711 return GetBlock()->Dominates(other_instruction->GetBlock());
712 } else {
713 // If both instructions are in the same block, ensure this
714 // instruction comes before `other_instruction`.
715 if (IsPhi()) {
716 if (!other_instruction->IsPhi()) {
717 // Phis appear before non phi-instructions so this instruction
718 // dominates `other_instruction`.
719 return true;
720 } else {
721 // There is no order among phis.
722 LOG(FATAL) << "There is no dominance between phis of a same block.";
723 return false;
724 }
725 } else {
726 // `this` is not a phi.
727 if (other_instruction->IsPhi()) {
728 // Phis appear before non phi-instructions so this instruction
729 // does not dominate `other_instruction`.
730 return false;
731 } else {
732 // Check whether this instruction comes before
733 // `other_instruction` in the instruction list.
734 return block->GetInstructions().FoundBefore(this, other_instruction);
735 }
736 }
737 }
738}
739
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100740void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100741 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000742 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
743 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100744 HInstruction* user = current->GetUser();
745 size_t input_index = current->GetIndex();
746 user->SetRawInputAt(input_index, other);
747 other->AddUseAt(user, input_index);
748 }
749
David Brazdiled596192015-01-23 10:39:45 +0000750 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
751 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100752 HEnvironment* user = current->GetUser();
753 size_t input_index = current->GetIndex();
754 user->SetRawEnvAt(input_index, other);
755 other->AddEnvUseAt(user, input_index);
756 }
757
David Brazdiled596192015-01-23 10:39:45 +0000758 uses_.Clear();
759 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100760}
761
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100762void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000763 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100764 SetRawInputAt(index, replacement);
765 replacement->AddUseAt(this, index);
766}
767
Nicolas Geoffray39468442014-09-02 15:17:15 +0100768size_t HInstruction::EnvironmentSize() const {
769 return HasEnvironment() ? environment_->Size() : 0;
770}
771
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100772void HPhi::AddInput(HInstruction* input) {
773 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000774 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100775 input->AddUseAt(this, inputs_.Size() - 1);
776}
777
David Brazdil2d7352b2015-04-20 14:52:42 +0100778void HPhi::RemoveInputAt(size_t index) {
779 RemoveAsUserOfInput(index);
780 inputs_.DeleteAt(index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100781 for (size_t i = index, e = InputCount(); i < e; ++i) {
782 InputRecordAt(i).GetUseNode()->SetIndex(i);
783 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100784}
785
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100786#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000787void H##name::Accept(HGraphVisitor* visitor) { \
788 visitor->Visit##name(this); \
789}
790
791FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
792
793#undef DEFINE_ACCEPT
794
795void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100796 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
797 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000798 HBasicBlock* block = blocks.Get(i);
799 if (block != nullptr) {
800 VisitBasicBlock(block);
801 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000802 }
803}
804
Roland Levillain633021e2014-10-01 14:12:25 +0100805void HGraphVisitor::VisitReversePostOrder() {
806 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
807 VisitBasicBlock(it.Current());
808 }
809}
810
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000811void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100812 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100813 it.Current()->Accept(this);
814 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100815 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000816 it.Current()->Accept(this);
817 }
818}
819
Mark Mendelle82549b2015-05-06 10:55:34 -0400820HConstant* HTypeConversion::TryStaticEvaluation() const {
821 HGraph* graph = GetBlock()->GetGraph();
822 if (GetInput()->IsIntConstant()) {
823 int32_t value = GetInput()->AsIntConstant()->GetValue();
824 switch (GetResultType()) {
825 case Primitive::kPrimLong:
826 return graph->GetLongConstant(static_cast<int64_t>(value));
827 case Primitive::kPrimFloat:
828 return graph->GetFloatConstant(static_cast<float>(value));
829 case Primitive::kPrimDouble:
830 return graph->GetDoubleConstant(static_cast<double>(value));
831 default:
832 return nullptr;
833 }
834 } else if (GetInput()->IsLongConstant()) {
835 int64_t value = GetInput()->AsLongConstant()->GetValue();
836 switch (GetResultType()) {
837 case Primitive::kPrimInt:
838 return graph->GetIntConstant(static_cast<int32_t>(value));
839 case Primitive::kPrimFloat:
840 return graph->GetFloatConstant(static_cast<float>(value));
841 case Primitive::kPrimDouble:
842 return graph->GetDoubleConstant(static_cast<double>(value));
843 default:
844 return nullptr;
845 }
846 } else if (GetInput()->IsFloatConstant()) {
847 float value = GetInput()->AsFloatConstant()->GetValue();
848 switch (GetResultType()) {
849 case Primitive::kPrimInt:
850 if (std::isnan(value))
851 return graph->GetIntConstant(0);
852 if (value >= kPrimIntMax)
853 return graph->GetIntConstant(kPrimIntMax);
854 if (value <= kPrimIntMin)
855 return graph->GetIntConstant(kPrimIntMin);
856 return graph->GetIntConstant(static_cast<int32_t>(value));
857 case Primitive::kPrimLong:
858 if (std::isnan(value))
859 return graph->GetLongConstant(0);
860 if (value >= kPrimLongMax)
861 return graph->GetLongConstant(kPrimLongMax);
862 if (value <= kPrimLongMin)
863 return graph->GetLongConstant(kPrimLongMin);
864 return graph->GetLongConstant(static_cast<int64_t>(value));
865 case Primitive::kPrimDouble:
866 return graph->GetDoubleConstant(static_cast<double>(value));
867 default:
868 return nullptr;
869 }
870 } else if (GetInput()->IsDoubleConstant()) {
871 double value = GetInput()->AsDoubleConstant()->GetValue();
872 switch (GetResultType()) {
873 case Primitive::kPrimInt:
874 if (std::isnan(value))
875 return graph->GetIntConstant(0);
876 if (value >= kPrimIntMax)
877 return graph->GetIntConstant(kPrimIntMax);
878 if (value <= kPrimLongMin)
879 return graph->GetIntConstant(kPrimIntMin);
880 return graph->GetIntConstant(static_cast<int32_t>(value));
881 case Primitive::kPrimLong:
882 if (std::isnan(value))
883 return graph->GetLongConstant(0);
884 if (value >= kPrimLongMax)
885 return graph->GetLongConstant(kPrimLongMax);
886 if (value <= kPrimLongMin)
887 return graph->GetLongConstant(kPrimLongMin);
888 return graph->GetLongConstant(static_cast<int64_t>(value));
889 case Primitive::kPrimFloat:
890 return graph->GetFloatConstant(static_cast<float>(value));
891 default:
892 return nullptr;
893 }
894 }
895 return nullptr;
896}
897
Roland Levillain9240d6a2014-10-20 16:47:04 +0100898HConstant* HUnaryOperation::TryStaticEvaluation() const {
899 if (GetInput()->IsIntConstant()) {
900 int32_t value = Evaluate(GetInput()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000901 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain9240d6a2014-10-20 16:47:04 +0100902 } else if (GetInput()->IsLongConstant()) {
Roland Levillainb762d2e2014-10-22 10:11:06 +0100903 // TODO: Implement static evaluation of long unary operations.
904 //
905 // Do not exit with a fatal condition here. Instead, simply
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700906 // return `null' to notify the caller that this instruction
Roland Levillainb762d2e2014-10-22 10:11:06 +0100907 // cannot (yet) be statically evaluated.
Roland Levillain9240d6a2014-10-20 16:47:04 +0100908 return nullptr;
909 }
910 return nullptr;
911}
912
913HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain556c3d12014-09-18 15:25:07 +0100914 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
915 int32_t value = Evaluate(GetLeft()->AsIntConstant()->GetValue(),
916 GetRight()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000917 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain556c3d12014-09-18 15:25:07 +0100918 } else if (GetLeft()->IsLongConstant() && GetRight()->IsLongConstant()) {
919 int64_t value = Evaluate(GetLeft()->AsLongConstant()->GetValue(),
920 GetRight()->AsLongConstant()->GetValue());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000921 if (GetResultType() == Primitive::kPrimLong) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000922 return GetBlock()->GetGraph()->GetLongConstant(value);
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000923 } else {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000924 DCHECK_EQ(GetResultType(), Primitive::kPrimInt);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000925 return GetBlock()->GetGraph()->GetIntConstant(static_cast<int32_t>(value));
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000926 }
Roland Levillain556c3d12014-09-18 15:25:07 +0100927 }
928 return nullptr;
929}
Dave Allison20dfc792014-06-16 20:44:29 -0700930
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000931HConstant* HBinaryOperation::GetConstantRight() const {
932 if (GetRight()->IsConstant()) {
933 return GetRight()->AsConstant();
934 } else if (IsCommutative() && GetLeft()->IsConstant()) {
935 return GetLeft()->AsConstant();
936 } else {
937 return nullptr;
938 }
939}
940
941// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700942// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000943HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
944 HInstruction* most_constant_right = GetConstantRight();
945 if (most_constant_right == nullptr) {
946 return nullptr;
947 } else if (most_constant_right == GetLeft()) {
948 return GetRight();
949 } else {
950 return GetLeft();
951 }
952}
953
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700954bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
955 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100956}
957
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100958bool HInstruction::Equals(HInstruction* other) const {
959 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100960 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100961 if (!InstructionDataEquals(other)) return false;
962 if (GetType() != other->GetType()) return false;
963 if (InputCount() != other->InputCount()) return false;
964
965 for (size_t i = 0, e = InputCount(); i < e; ++i) {
966 if (InputAt(i) != other->InputAt(i)) return false;
967 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100968 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100969 return true;
970}
971
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700972std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
973#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
974 switch (rhs) {
975 FOR_EACH_INSTRUCTION(DECLARE_CASE)
976 default:
977 os << "Unknown instruction kind " << static_cast<int>(rhs);
978 break;
979 }
980#undef DECLARE_CASE
981 return os;
982}
983
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000984void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000985 next_->previous_ = previous_;
986 if (previous_ != nullptr) {
987 previous_->next_ = next_;
988 }
989 if (block_->instructions_.first_instruction_ == this) {
990 block_->instructions_.first_instruction_ = next_;
991 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000992 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000993
994 previous_ = cursor->previous_;
995 if (previous_ != nullptr) {
996 previous_->next_ = this;
997 }
998 next_ = cursor;
999 cursor->previous_ = this;
1000 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001001
1002 if (block_->instructions_.first_instruction_ == cursor) {
1003 block_->instructions_.first_instruction_ = this;
1004 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001005}
1006
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001007HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1008 DCHECK(!cursor->IsControlFlow());
1009 DCHECK_NE(instructions_.last_instruction_, cursor);
1010 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001011
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001012 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1013 new_block->instructions_.first_instruction_ = cursor->GetNext();
1014 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1015 cursor->next_->previous_ = nullptr;
1016 cursor->next_ = nullptr;
1017 instructions_.last_instruction_ = cursor;
1018
1019 new_block->instructions_.SetBlockOfInstructions(new_block);
1020 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
1021 HBasicBlock* successor = GetSuccessors().Get(i);
1022 new_block->successors_.Add(successor);
1023 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
1024 }
1025 successors_.Reset();
1026
1027 for (size_t i = 0, e = GetDominatedBlocks().Size(); i < e; ++i) {
1028 HBasicBlock* dominated = GetDominatedBlocks().Get(i);
1029 dominated->dominator_ = new_block;
1030 new_block->dominated_blocks_.Add(dominated);
1031 }
1032 dominated_blocks_.Reset();
1033 return new_block;
1034}
1035
David Brazdil46e2a392015-03-16 17:31:52 +00001036bool HBasicBlock::IsSingleGoto() const {
1037 HLoopInformation* loop_info = GetLoopInformation();
1038 // TODO: Remove the null check b/19084197.
1039 return GetFirstInstruction() != nullptr
1040 && GetPhis().IsEmpty()
1041 && GetFirstInstruction() == GetLastInstruction()
1042 && GetLastInstruction()->IsGoto()
1043 // Back edges generate the suspend check.
1044 && (loop_info == nullptr || !loop_info->IsBackEdge(*this));
1045}
1046
David Brazdil8d5b8b22015-03-24 10:51:52 +00001047bool HBasicBlock::EndsWithControlFlowInstruction() const {
1048 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1049}
1050
David Brazdilb2bd1c52015-03-25 11:17:37 +00001051bool HBasicBlock::EndsWithIf() const {
1052 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1053}
1054
1055bool HBasicBlock::HasSinglePhi() const {
1056 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1057}
1058
David Brazdil2d7352b2015-04-20 14:52:42 +01001059size_t HInstructionList::CountSize() const {
1060 size_t size = 0;
1061 HInstruction* current = first_instruction_;
1062 for (; current != nullptr; current = current->GetNext()) {
1063 size++;
1064 }
1065 return size;
1066}
1067
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001068void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1069 for (HInstruction* current = first_instruction_;
1070 current != nullptr;
1071 current = current->GetNext()) {
1072 current->SetBlock(block);
1073 }
1074}
1075
1076void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1077 DCHECK(Contains(cursor));
1078 if (!instruction_list.IsEmpty()) {
1079 if (cursor == last_instruction_) {
1080 last_instruction_ = instruction_list.last_instruction_;
1081 } else {
1082 cursor->next_->previous_ = instruction_list.last_instruction_;
1083 }
1084 instruction_list.last_instruction_->next_ = cursor->next_;
1085 cursor->next_ = instruction_list.first_instruction_;
1086 instruction_list.first_instruction_->previous_ = cursor;
1087 }
1088}
1089
1090void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001091 if (IsEmpty()) {
1092 first_instruction_ = instruction_list.first_instruction_;
1093 last_instruction_ = instruction_list.last_instruction_;
1094 } else {
1095 AddAfter(last_instruction_, instruction_list);
1096 }
1097}
1098
David Brazdil2d7352b2015-04-20 14:52:42 +01001099void HBasicBlock::DisconnectAndDelete() {
1100 // Dominators must be removed after all the blocks they dominate. This way
1101 // a loop header is removed last, a requirement for correct loop information
1102 // iteration.
1103 DCHECK(dominated_blocks_.IsEmpty());
David Brazdil46e2a392015-03-16 17:31:52 +00001104
David Brazdil2d7352b2015-04-20 14:52:42 +01001105 // Remove the block from all loops it is included in.
1106 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1107 HLoopInformation* loop_info = it.Current();
1108 loop_info->Remove(this);
1109 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001110 // If this was the last back edge of the loop, we deliberately leave the
1111 // loop in an inconsistent state and will fail SSAChecker unless the
1112 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001113 loop_info->RemoveBackEdge(this);
1114 }
1115 }
1116
1117 // Disconnect the block from its predecessors and update their control-flow
1118 // instructions.
David Brazdil46e2a392015-03-16 17:31:52 +00001119 for (size_t i = 0, e = predecessors_.Size(); i < e; ++i) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001120 HBasicBlock* predecessor = predecessors_.Get(i);
1121 HInstruction* last_instruction = predecessor->GetLastInstruction();
1122 predecessor->RemoveInstruction(last_instruction);
1123 predecessor->RemoveSuccessor(this);
1124 if (predecessor->GetSuccessors().Size() == 1u) {
1125 DCHECK(last_instruction->IsIf());
1126 predecessor->AddInstruction(new (graph_->GetArena()) HGoto());
1127 } else {
1128 // The predecessor has no remaining successors and therefore must be dead.
1129 // We deliberately leave it without a control-flow instruction so that the
1130 // SSAChecker fails unless it is not removed during the pass too.
1131 DCHECK_EQ(predecessor->GetSuccessors().Size(), 0u);
1132 }
David Brazdil46e2a392015-03-16 17:31:52 +00001133 }
David Brazdil46e2a392015-03-16 17:31:52 +00001134 predecessors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +01001135
1136 // Disconnect the block from its successors and update their dominators
1137 // and phis.
1138 for (size_t i = 0, e = successors_.Size(); i < e; ++i) {
1139 HBasicBlock* successor = successors_.Get(i);
1140 // Delete this block from the list of predecessors.
1141 size_t this_index = successor->GetPredecessorIndexOf(this);
1142 successor->predecessors_.DeleteAt(this_index);
1143
1144 // Check that `successor` has other predecessors, otherwise `this` is the
1145 // dominator of `successor` which violates the order DCHECKed at the top.
1146 DCHECK(!successor->predecessors_.IsEmpty());
1147
1148 // Recompute the successor's dominator.
1149 HBasicBlock* old_dominator = successor->GetDominator();
1150 HBasicBlock* new_dominator = successor->predecessors_.Get(0);
1151 for (size_t j = 1, f = successor->predecessors_.Size(); j < f; ++j) {
1152 new_dominator = graph_->FindCommonDominator(
1153 new_dominator, successor->predecessors_.Get(j));
1154 }
1155 if (old_dominator != new_dominator) {
1156 successor->SetDominator(new_dominator);
1157 old_dominator->RemoveDominatedBlock(successor);
1158 new_dominator->AddDominatedBlock(successor);
1159 }
1160
1161 // Remove this block's entries in the successor's phis.
1162 if (successor->predecessors_.Size() == 1u) {
1163 // The successor has just one predecessor left. Replace phis with the only
1164 // remaining input.
1165 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1166 HPhi* phi = phi_it.Current()->AsPhi();
1167 phi->ReplaceWith(phi->InputAt(1 - this_index));
1168 successor->RemovePhi(phi);
1169 }
1170 } else {
1171 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1172 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1173 }
1174 }
1175 }
David Brazdil46e2a392015-03-16 17:31:52 +00001176 successors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +01001177
1178 // Disconnect from the dominator.
1179 dominator_->RemoveDominatedBlock(this);
1180 SetDominator(nullptr);
1181
1182 // Delete from the graph. The function safely deletes remaining instructions
1183 // and updates the reverse post order.
1184 graph_->DeleteDeadBlock(this);
1185 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001186}
1187
1188void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001189 DCHECK_EQ(GetGraph(), other->GetGraph());
1190 DCHECK(GetDominatedBlocks().Contains(other));
1191 DCHECK_EQ(GetSuccessors().Size(), 1u);
1192 DCHECK_EQ(GetSuccessors().Get(0), other);
1193 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1194 DCHECK_EQ(other->GetPredecessors().Get(0), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001195 DCHECK(other->GetPhis().IsEmpty());
1196
David Brazdil2d7352b2015-04-20 14:52:42 +01001197 // Move instructions from `other` to `this`.
1198 DCHECK(EndsWithControlFlowInstruction());
1199 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001200 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001201 other->instructions_.SetBlockOfInstructions(this);
1202 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001203
David Brazdil2d7352b2015-04-20 14:52:42 +01001204 // Remove `other` from the loops it is included in.
1205 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1206 HLoopInformation* loop_info = it.Current();
1207 loop_info->Remove(other);
1208 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001209 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001210 }
1211 }
1212
1213 // Update links to the successors of `other`.
1214 successors_.Reset();
1215 while (!other->successors_.IsEmpty()) {
1216 HBasicBlock* successor = other->successors_.Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001217 successor->ReplacePredecessor(other, this);
1218 }
1219
David Brazdil2d7352b2015-04-20 14:52:42 +01001220 // Update the dominator tree.
1221 dominated_blocks_.Delete(other);
1222 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1223 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1224 dominated_blocks_.Add(dominated);
1225 dominated->SetDominator(this);
1226 }
1227 other->dominated_blocks_.Reset();
1228 other->dominator_ = nullptr;
1229
1230 // Clear the list of predecessors of `other` in preparation of deleting it.
1231 other->predecessors_.Reset();
1232
1233 // Delete `other` from the graph. The function updates reverse post order.
1234 graph_->DeleteDeadBlock(other);
1235 other->SetGraph(nullptr);
1236}
1237
1238void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1239 DCHECK_NE(GetGraph(), other->GetGraph());
1240 DCHECK(GetDominatedBlocks().IsEmpty());
1241 DCHECK(GetSuccessors().IsEmpty());
1242 DCHECK(!EndsWithControlFlowInstruction());
1243 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1244 DCHECK(other->GetPredecessors().Get(0)->IsEntryBlock());
1245 DCHECK(other->GetPhis().IsEmpty());
1246 DCHECK(!other->IsInLoop());
1247
1248 // Move instructions from `other` to `this`.
1249 instructions_.Add(other->GetInstructions());
1250 other->instructions_.SetBlockOfInstructions(this);
1251
1252 // Update links to the successors of `other`.
1253 successors_.Reset();
1254 while (!other->successors_.IsEmpty()) {
1255 HBasicBlock* successor = other->successors_.Get(0);
1256 successor->ReplacePredecessor(other, this);
1257 }
1258
1259 // Update the dominator tree.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001260 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1261 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1262 dominated_blocks_.Add(dominated);
1263 dominated->SetDominator(this);
1264 }
1265 other->dominated_blocks_.Reset();
1266 other->dominator_ = nullptr;
1267 other->graph_ = nullptr;
1268}
1269
1270void HBasicBlock::ReplaceWith(HBasicBlock* other) {
1271 while (!GetPredecessors().IsEmpty()) {
1272 HBasicBlock* predecessor = GetPredecessors().Get(0);
1273 predecessor->ReplaceSuccessor(this, other);
1274 }
1275 while (!GetSuccessors().IsEmpty()) {
1276 HBasicBlock* successor = GetSuccessors().Get(0);
1277 successor->ReplacePredecessor(this, other);
1278 }
1279 for (size_t i = 0; i < dominated_blocks_.Size(); ++i) {
1280 other->AddDominatedBlock(dominated_blocks_.Get(i));
1281 }
1282 GetDominator()->ReplaceDominatedBlock(this, other);
1283 other->SetDominator(GetDominator());
1284 dominator_ = nullptr;
1285 graph_ = nullptr;
1286}
1287
1288// Create space in `blocks` for adding `number_of_new_blocks` entries
1289// starting at location `at`. Blocks after `at` are moved accordingly.
1290static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
1291 size_t number_of_new_blocks,
1292 size_t at) {
1293 size_t old_size = blocks->Size();
1294 size_t new_size = old_size + number_of_new_blocks;
1295 blocks->SetSize(new_size);
1296 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
1297 blocks->Put(j, blocks->Get(i));
1298 }
1299}
1300
David Brazdil2d7352b2015-04-20 14:52:42 +01001301void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1302 DCHECK_EQ(block->GetGraph(), this);
1303 DCHECK(block->GetSuccessors().IsEmpty());
1304 DCHECK(block->GetPredecessors().IsEmpty());
1305 DCHECK(block->GetDominatedBlocks().IsEmpty());
1306 DCHECK(block->GetDominator() == nullptr);
1307
1308 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1309 block->RemoveInstruction(it.Current());
1310 }
1311 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1312 block->RemovePhi(it.Current()->AsPhi());
1313 }
1314
David Brazdilc7af85d2015-05-26 12:05:55 +01001315 if (block->IsExitBlock()) {
1316 exit_block_ = nullptr;
1317 }
1318
David Brazdil2d7352b2015-04-20 14:52:42 +01001319 reverse_post_order_.Delete(block);
1320 blocks_.Put(block->GetBlockId(), nullptr);
1321}
1322
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001323void HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001324 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001325 // Update the environments in this graph to have the invoke's environment
1326 // as parent.
1327 {
1328 HReversePostOrderIterator it(*this);
1329 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1330 for (; !it.Done(); it.Advance()) {
1331 HBasicBlock* block = it.Current();
1332 for (HInstructionIterator instr_it(block->GetInstructions());
1333 !instr_it.Done();
1334 instr_it.Advance()) {
1335 HInstruction* current = instr_it.Current();
1336 if (current->NeedsEnvironment()) {
1337 current->GetEnvironment()->SetAndCopyParentChain(
1338 outer_graph->GetArena(), invoke->GetEnvironment());
1339 }
1340 }
1341 }
1342 }
1343 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1344 if (HasBoundsChecks()) {
1345 outer_graph->SetHasBoundsChecks(true);
1346 }
1347
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001348 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001349 // Simple case of an entry block, a body block, and an exit block.
1350 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001351 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001352 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
1353 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001354 DCHECK(!body->IsExitBlock());
1355 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001356
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001357 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1358 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001359
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001360 // Replace the invoke with the return value of the inlined graph.
1361 if (last->IsReturn()) {
1362 invoke->ReplaceWith(last->InputAt(0));
1363 } else {
1364 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001365 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001366
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001367 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001368 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001369 // Need to inline multiple blocks. We split `invoke`'s block
1370 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001371 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001372 // with the second half.
1373 ArenaAllocator* allocator = outer_graph->GetArena();
1374 HBasicBlock* at = invoke->GetBlock();
1375 HBasicBlock* to = at->SplitAfter(invoke);
1376
1377 HBasicBlock* first = entry_block_->GetSuccessors().Get(0);
1378 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001379 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001380 exit_block_->ReplaceWith(to);
1381
1382 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001383 // to not `HReturn` but `HGoto` instead.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001384 HInstruction* return_value = nullptr;
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001385 bool returns_void = to->GetPredecessors().Get(0)->GetLastInstruction()->IsReturnVoid();
1386 if (to->GetPredecessors().Size() == 1) {
1387 HBasicBlock* predecessor = to->GetPredecessors().Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001388 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001389 if (!returns_void) {
1390 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001391 }
1392 predecessor->AddInstruction(new (allocator) HGoto());
1393 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001394 } else {
1395 if (!returns_void) {
1396 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001397 return_value = new (allocator) HPhi(
1398 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001399 to->AddPhi(return_value->AsPhi());
1400 }
1401 for (size_t i = 0, e = to->GetPredecessors().Size(); i < e; ++i) {
1402 HBasicBlock* predecessor = to->GetPredecessors().Get(i);
1403 HInstruction* last = predecessor->GetLastInstruction();
1404 if (!returns_void) {
1405 return_value->AsPhi()->AddInput(last->InputAt(0));
1406 }
1407 predecessor->AddInstruction(new (allocator) HGoto());
1408 predecessor->RemoveInstruction(last);
1409 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001410 }
1411
1412 if (return_value != nullptr) {
1413 invoke->ReplaceWith(return_value);
1414 }
1415
1416 // Update the meta information surrounding blocks:
1417 // (1) the graph they are now in,
1418 // (2) the reverse post order of that graph,
1419 // (3) the potential loop information they are now in.
1420
1421 // We don't add the entry block, the exit block, and the first block, which
1422 // has been merged with `at`.
1423 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1424
1425 // We add the `to` block.
1426 static constexpr int kNumberOfNewBlocksInCaller = 1;
1427 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1428 + kNumberOfNewBlocksInCaller;
1429
1430 // Find the location of `at` in the outer graph's reverse post order. The new
1431 // blocks will be added after it.
1432 size_t index_of_at = 0;
1433 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1434 index_of_at++;
1435 }
1436 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1437
1438 // Do a reverse post order of the blocks in the callee and do (1), (2),
1439 // and (3) to the blocks that apply.
1440 HLoopInformation* info = at->GetLoopInformation();
1441 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1442 HBasicBlock* current = it.Current();
1443 if (current != exit_block_ && current != entry_block_ && current != first) {
1444 DCHECK(!current->IsInLoop());
1445 DCHECK(current->GetGraph() == this);
1446 current->SetGraph(outer_graph);
1447 outer_graph->AddBlock(current);
1448 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1449 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001450 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001451 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1452 loop_it.Current()->Add(current);
1453 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001454 }
1455 }
1456 }
1457
1458 // Do (1), (2), and (3) to `to`.
1459 to->SetGraph(outer_graph);
1460 outer_graph->AddBlock(to);
1461 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1462 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001463 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001464 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1465 loop_it.Current()->Add(to);
1466 }
David Brazdil46e2a392015-03-16 17:31:52 +00001467 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001468 // Only `to` can become a back edge, as the inlined blocks
1469 // are predecessors of `to`.
1470 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001471 }
1472 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001473 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001474
David Brazdil05144f42015-04-16 15:18:00 +01001475 // Update the next instruction id of the outer graph, so that instructions
1476 // added later get bigger ids than those in the inner graph.
1477 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1478
1479 // Walk over the entry block and:
1480 // - Move constants from the entry block to the outer_graph's entry block,
1481 // - Replace HParameterValue instructions with their real value.
1482 // - Remove suspend checks, that hold an environment.
1483 // We must do this after the other blocks have been inlined, otherwise ids of
1484 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001485 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001486 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1487 HInstruction* current = it.Current();
1488 if (current->IsNullConstant()) {
1489 current->ReplaceWith(outer_graph->GetNullConstant());
1490 } else if (current->IsIntConstant()) {
1491 current->ReplaceWith(outer_graph->GetIntConstant(current->AsIntConstant()->GetValue()));
1492 } else if (current->IsLongConstant()) {
1493 current->ReplaceWith(outer_graph->GetLongConstant(current->AsLongConstant()->GetValue()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001494 } else if (current->IsFloatConstant()) {
1495 current->ReplaceWith(outer_graph->GetFloatConstant(current->AsFloatConstant()->GetValue()));
1496 } else if (current->IsDoubleConstant()) {
1497 current->ReplaceWith(outer_graph->GetDoubleConstant(current->AsDoubleConstant()->GetValue()));
David Brazdil05144f42015-04-16 15:18:00 +01001498 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001499 if (kIsDebugBuild
1500 && invoke->IsInvokeStaticOrDirect()
1501 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1502 // Ensure we do not use the last input of `invoke`, as it
1503 // contains a clinit check which is not an actual argument.
1504 size_t last_input_index = invoke->InputCount() - 1;
1505 DCHECK(parameter_index != last_input_index);
1506 }
David Brazdil05144f42015-04-16 15:18:00 +01001507 current->ReplaceWith(invoke->InputAt(parameter_index++));
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001508 } else if (current->IsCurrentMethod()) {
1509 current->ReplaceWith(outer_graph->GetCurrentMethod());
David Brazdil05144f42015-04-16 15:18:00 +01001510 } else {
1511 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1512 entry_block_->RemoveInstruction(current);
1513 }
1514 }
1515
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001516 // Finally remove the invoke from the caller.
1517 invoke->GetBlock()->RemoveInstruction(invoke);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001518}
1519
Mingyao Yang3584bce2015-05-19 16:01:59 -07001520/*
1521 * Loop will be transformed to:
1522 * old_pre_header
1523 * |
1524 * if_block
1525 * / \
1526 * dummy_block deopt_block
1527 * \ /
1528 * new_pre_header
1529 * |
1530 * header
1531 */
1532void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1533 DCHECK(header->IsLoopHeader());
1534 HBasicBlock* pre_header = header->GetDominator();
1535
1536 // Need this to avoid critical edge.
1537 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1538 // Need this to avoid critical edge.
1539 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1540 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1541 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1542 AddBlock(if_block);
1543 AddBlock(dummy_block);
1544 AddBlock(deopt_block);
1545 AddBlock(new_pre_header);
1546
1547 header->ReplacePredecessor(pre_header, new_pre_header);
1548 pre_header->successors_.Reset();
1549 pre_header->dominated_blocks_.Reset();
1550
1551 pre_header->AddSuccessor(if_block);
1552 if_block->AddSuccessor(dummy_block); // True successor
1553 if_block->AddSuccessor(deopt_block); // False successor
1554 dummy_block->AddSuccessor(new_pre_header);
1555 deopt_block->AddSuccessor(new_pre_header);
1556
1557 pre_header->dominated_blocks_.Add(if_block);
1558 if_block->SetDominator(pre_header);
1559 if_block->dominated_blocks_.Add(dummy_block);
1560 dummy_block->SetDominator(if_block);
1561 if_block->dominated_blocks_.Add(deopt_block);
1562 deopt_block->SetDominator(if_block);
1563 if_block->dominated_blocks_.Add(new_pre_header);
1564 new_pre_header->SetDominator(if_block);
1565 new_pre_header->dominated_blocks_.Add(header);
1566 header->SetDominator(new_pre_header);
1567
1568 size_t index_of_header = 0;
1569 while (reverse_post_order_.Get(index_of_header) != header) {
1570 index_of_header++;
1571 }
1572 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
1573 reverse_post_order_.Put(index_of_header++, if_block);
1574 reverse_post_order_.Put(index_of_header++, dummy_block);
1575 reverse_post_order_.Put(index_of_header++, deopt_block);
1576 reverse_post_order_.Put(index_of_header++, new_pre_header);
1577
1578 HLoopInformation* info = pre_header->GetLoopInformation();
1579 if (info != nullptr) {
1580 if_block->SetLoopInformation(info);
1581 dummy_block->SetLoopInformation(info);
1582 deopt_block->SetLoopInformation(info);
1583 new_pre_header->SetLoopInformation(info);
1584 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1585 !loop_it.Done();
1586 loop_it.Advance()) {
1587 loop_it.Current()->Add(if_block);
1588 loop_it.Current()->Add(dummy_block);
1589 loop_it.Current()->Add(deopt_block);
1590 loop_it.Current()->Add(new_pre_header);
1591 }
1592 }
1593}
1594
Calin Juravleacf735c2015-02-12 15:25:22 +00001595std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1596 ScopedObjectAccess soa(Thread::Current());
1597 os << "["
1598 << " is_top=" << rhs.IsTop()
1599 << " type=" << (rhs.IsTop() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
1600 << " is_exact=" << rhs.IsExact()
1601 << " ]";
1602 return os;
1603}
1604
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001605} // namespace art