blob: 68c197e60783fe5764cb1796bf58869b008c8eef [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 Geoffrayec7e4722014-06-06 11:24:33 +0100183 block->ReplaceSuccessor(successor, new_block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100184 new_block->AddSuccessor(successor);
185 if (successor->IsLoopHeader()) {
186 // If we split at a back edge boundary, make the new block the back edge.
187 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000188 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100189 info->RemoveBackEdge(block);
190 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100191 }
192 }
193}
194
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100195void HGraph::SimplifyLoop(HBasicBlock* header) {
196 HLoopInformation* info = header->GetLoopInformation();
197
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100198 // Make sure the loop has only one pre header. This simplifies SSA building by having
199 // to just look at the pre header to know which locals are initialized at entry of the
200 // loop.
201 size_t number_of_incomings = header->GetPredecessors().Size() - info->NumberOfBackEdges();
202 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100203 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100204 AddBlock(pre_header);
205 pre_header->AddInstruction(new (arena_) HGoto());
206
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100207 for (size_t pred = 0; pred < header->GetPredecessors().Size(); ++pred) {
208 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100209 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100210 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100211 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100212 }
213 }
214 pre_header->AddSuccessor(header);
215 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100216
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100217 // Make sure the first predecessor of a loop header is the incoming block.
218 if (info->IsBackEdge(*header->GetPredecessors().Get(0))) {
219 HBasicBlock* to_swap = header->GetPredecessors().Get(0);
220 for (size_t pred = 1, e = header->GetPredecessors().Size(); pred < e; ++pred) {
221 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
222 if (!info->IsBackEdge(*predecessor)) {
223 header->predecessors_.Put(pred, to_swap);
224 header->predecessors_.Put(0, predecessor);
225 break;
226 }
227 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100228 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100229
230 // Place the suspend check at the beginning of the header, so that live registers
231 // will be known when allocating registers. Note that code generation can still
232 // generate the suspend check at the back edge, but needs to be careful with
233 // loop phi spill slots (which are not written to at back edge).
234 HInstruction* first_instruction = header->GetFirstInstruction();
235 if (!first_instruction->IsSuspendCheck()) {
236 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
237 header->InsertInstructionBefore(check, first_instruction);
238 first_instruction = check;
239 }
240 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100241}
242
243void HGraph::SimplifyCFG() {
244 // Simplify the CFG for future analysis, and code generation:
245 // (1): Split critical edges.
246 // (2): Simplify loops by having only one back edge, and one preheader.
247 for (size_t i = 0; i < blocks_.Size(); ++i) {
248 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100249 if (block == nullptr) continue;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100250 if (block->GetSuccessors().Size() > 1) {
251 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
252 HBasicBlock* successor = block->GetSuccessors().Get(j);
253 if (successor->GetPredecessors().Size() > 1) {
254 SplitCriticalEdge(block, successor);
255 --j;
256 }
257 }
258 }
259 if (block->IsLoopHeader()) {
260 SimplifyLoop(block);
261 }
262 }
263}
264
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000265bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100266 // Order does not matter.
267 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
268 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100269 if (block->IsLoopHeader()) {
270 HLoopInformation* info = block->GetLoopInformation();
271 if (!info->Populate()) {
272 // Abort if the loop is non natural. We currently bailout in such cases.
273 return false;
274 }
275 }
276 }
277 return true;
278}
279
David Brazdil8d5b8b22015-03-24 10:51:52 +0000280void HGraph::InsertConstant(HConstant* constant) {
281 // New constants are inserted before the final control-flow instruction
282 // of the graph, or at its end if called from the graph builder.
283 if (entry_block_->EndsWithControlFlowInstruction()) {
284 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000285 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000286 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000287 }
288}
289
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000290HNullConstant* HGraph::GetNullConstant() {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100291 // For simplicity, don't bother reviving the cached null constant if it is
292 // not null and not in a block. Otherwise, we need to clear the instruction
293 // id and/or any invariants the graph is assuming when adding new instructions.
294 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000295 cached_null_constant_ = new (arena_) HNullConstant();
David Brazdil8d5b8b22015-03-24 10:51:52 +0000296 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000297 }
298 return cached_null_constant_;
299}
300
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100301HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100302 // For simplicity, don't bother reviving the cached current method if it is
303 // not null and not in a block. Otherwise, we need to clear the instruction
304 // id and/or any invariants the graph is assuming when adding new instructions.
305 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700306 cached_current_method_ = new (arena_) HCurrentMethod(
307 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100308 if (entry_block_->GetFirstInstruction() == nullptr) {
309 entry_block_->AddInstruction(cached_current_method_);
310 } else {
311 entry_block_->InsertInstructionBefore(
312 cached_current_method_, entry_block_->GetFirstInstruction());
313 }
314 }
315 return cached_current_method_;
316}
317
David Brazdil8d5b8b22015-03-24 10:51:52 +0000318HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value) {
319 switch (type) {
320 case Primitive::Type::kPrimBoolean:
321 DCHECK(IsUint<1>(value));
322 FALLTHROUGH_INTENDED;
323 case Primitive::Type::kPrimByte:
324 case Primitive::Type::kPrimChar:
325 case Primitive::Type::kPrimShort:
326 case Primitive::Type::kPrimInt:
327 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
328 return GetIntConstant(static_cast<int32_t>(value));
329
330 case Primitive::Type::kPrimLong:
331 return GetLongConstant(value);
332
333 default:
334 LOG(FATAL) << "Unsupported constant type";
335 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000336 }
David Brazdil46e2a392015-03-16 17:31:52 +0000337}
338
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000339void HGraph::CacheFloatConstant(HFloatConstant* constant) {
340 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
341 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
342 cached_float_constants_.Overwrite(value, constant);
343}
344
345void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
346 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
347 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
348 cached_double_constants_.Overwrite(value, constant);
349}
350
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000351void HLoopInformation::Add(HBasicBlock* block) {
352 blocks_.SetBit(block->GetBlockId());
353}
354
David Brazdil46e2a392015-03-16 17:31:52 +0000355void HLoopInformation::Remove(HBasicBlock* block) {
356 blocks_.ClearBit(block->GetBlockId());
357}
358
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100359void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
360 if (blocks_.IsBitSet(block->GetBlockId())) {
361 return;
362 }
363
364 blocks_.SetBit(block->GetBlockId());
365 block->SetInLoop(this);
366 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
367 PopulateRecursive(block->GetPredecessors().Get(i));
368 }
369}
370
371bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100372 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100373 for (size_t i = 0, e = GetBackEdges().Size(); i < e; ++i) {
374 HBasicBlock* back_edge = GetBackEdges().Get(i);
375 DCHECK(back_edge->GetDominator() != nullptr);
376 if (!header_->Dominates(back_edge)) {
377 // This loop is not natural. Do not bother going further.
378 return false;
379 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100380
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100381 // Populate this loop: starting with the back edge, recursively add predecessors
382 // that are not already part of that loop. Set the header as part of the loop
383 // to end the recursion.
384 // This is a recursive implementation of the algorithm described in
385 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
386 blocks_.SetBit(header_->GetBlockId());
387 PopulateRecursive(back_edge);
388 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100389 return true;
390}
391
David Brazdila4b8c212015-05-07 09:59:30 +0100392void HLoopInformation::Update() {
393 HGraph* graph = header_->GetGraph();
394 for (uint32_t id : blocks_.Indexes()) {
395 HBasicBlock* block = graph->GetBlocks().Get(id);
396 // Reset loop information of non-header blocks inside the loop, except
397 // members of inner nested loops because those should already have been
398 // updated by their own LoopInformation.
399 if (block->GetLoopInformation() == this && block != header_) {
400 block->SetLoopInformation(nullptr);
401 }
402 }
403 blocks_.ClearAllBits();
404
405 if (back_edges_.IsEmpty()) {
406 // The loop has been dismantled, delete its suspend check and remove info
407 // from the header.
408 DCHECK(HasSuspendCheck());
409 header_->RemoveInstruction(suspend_check_);
410 header_->SetLoopInformation(nullptr);
411 header_ = nullptr;
412 suspend_check_ = nullptr;
413 } else {
414 if (kIsDebugBuild) {
415 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
416 DCHECK(header_->Dominates(back_edges_.Get(i)));
417 }
418 }
419 // This loop still has reachable back edges. Repopulate the list of blocks.
420 bool populate_successful = Populate();
421 DCHECK(populate_successful);
422 }
423}
424
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100425HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100426 return header_->GetDominator();
427}
428
429bool HLoopInformation::Contains(const HBasicBlock& block) const {
430 return blocks_.IsBitSet(block.GetBlockId());
431}
432
433bool HLoopInformation::IsIn(const HLoopInformation& other) const {
434 return other.blocks_.IsBitSet(header_->GetBlockId());
435}
436
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100437size_t HLoopInformation::GetLifetimeEnd() const {
438 size_t last_position = 0;
439 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
440 last_position = std::max(back_edges_.Get(i)->GetLifetimeEnd(), last_position);
441 }
442 return last_position;
443}
444
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100445bool HBasicBlock::Dominates(HBasicBlock* other) const {
446 // Walk up the dominator tree from `other`, to find out if `this`
447 // is an ancestor.
448 HBasicBlock* current = other;
449 while (current != nullptr) {
450 if (current == this) {
451 return true;
452 }
453 current = current->GetDominator();
454 }
455 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100456}
457
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100458static void UpdateInputsUsers(HInstruction* instruction) {
459 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
460 instruction->InputAt(i)->AddUseAt(instruction, i);
461 }
462 // Environment should be created later.
463 DCHECK(!instruction->HasEnvironment());
464}
465
Roland Levillainccc07a92014-09-16 14:48:16 +0100466void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
467 HInstruction* replacement) {
468 DCHECK(initial->GetBlock() == this);
469 InsertInstructionBefore(replacement, initial);
470 initial->ReplaceWith(replacement);
471 RemoveInstruction(initial);
472}
473
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100474static void Add(HInstructionList* instruction_list,
475 HBasicBlock* block,
476 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000477 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000478 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100479 instruction->SetBlock(block);
480 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100481 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100482 instruction_list->AddInstruction(instruction);
483}
484
485void HBasicBlock::AddInstruction(HInstruction* instruction) {
486 Add(&instructions_, this, instruction);
487}
488
489void HBasicBlock::AddPhi(HPhi* phi) {
490 Add(&phis_, this, phi);
491}
492
David Brazdilc3d743f2015-04-22 13:40:50 +0100493void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
494 DCHECK(!cursor->IsPhi());
495 DCHECK(!instruction->IsPhi());
496 DCHECK_EQ(instruction->GetId(), -1);
497 DCHECK_NE(cursor->GetId(), -1);
498 DCHECK_EQ(cursor->GetBlock(), this);
499 DCHECK(!instruction->IsControlFlow());
500 instruction->SetBlock(this);
501 instruction->SetId(GetGraph()->GetNextInstructionId());
502 UpdateInputsUsers(instruction);
503 instructions_.InsertInstructionBefore(instruction, cursor);
504}
505
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100506void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
507 DCHECK(!cursor->IsPhi());
508 DCHECK(!instruction->IsPhi());
509 DCHECK_EQ(instruction->GetId(), -1);
510 DCHECK_NE(cursor->GetId(), -1);
511 DCHECK_EQ(cursor->GetBlock(), this);
512 DCHECK(!instruction->IsControlFlow());
513 DCHECK(!cursor->IsControlFlow());
514 instruction->SetBlock(this);
515 instruction->SetId(GetGraph()->GetNextInstructionId());
516 UpdateInputsUsers(instruction);
517 instructions_.InsertInstructionAfter(instruction, cursor);
518}
519
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100520void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
521 DCHECK_EQ(phi->GetId(), -1);
522 DCHECK_NE(cursor->GetId(), -1);
523 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100524 phi->SetBlock(this);
525 phi->SetId(GetGraph()->GetNextInstructionId());
526 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100527 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100528}
529
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100530static void Remove(HInstructionList* instruction_list,
531 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000532 HInstruction* instruction,
533 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100534 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100535 instruction->SetBlock(nullptr);
536 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000537 if (ensure_safety) {
538 DCHECK(instruction->GetUses().IsEmpty());
539 DCHECK(instruction->GetEnvUses().IsEmpty());
540 RemoveAsUser(instruction);
541 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100542}
543
David Brazdil1abb4192015-02-17 18:33:36 +0000544void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100545 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000546 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100547}
548
David Brazdil1abb4192015-02-17 18:33:36 +0000549void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
550 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100551}
552
David Brazdilc7508e92015-04-27 13:28:57 +0100553void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
554 if (instruction->IsPhi()) {
555 RemovePhi(instruction->AsPhi(), ensure_safety);
556 } else {
557 RemoveInstruction(instruction, ensure_safety);
558 }
559}
560
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100561void HEnvironment::CopyFrom(const GrowableArray<HInstruction*>& locals) {
562 for (size_t i = 0; i < locals.Size(); i++) {
563 HInstruction* instruction = locals.Get(i);
564 SetRawEnvAt(i, instruction);
565 if (instruction != nullptr) {
566 instruction->AddEnvUseAt(this, i);
567 }
568 }
569}
570
David Brazdiled596192015-01-23 10:39:45 +0000571void HEnvironment::CopyFrom(HEnvironment* env) {
572 for (size_t i = 0; i < env->Size(); i++) {
573 HInstruction* instruction = env->GetInstructionAt(i);
574 SetRawEnvAt(i, instruction);
575 if (instruction != nullptr) {
576 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100577 }
David Brazdiled596192015-01-23 10:39:45 +0000578 }
579}
580
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700581void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
582 HBasicBlock* loop_header) {
583 DCHECK(loop_header->IsLoopHeader());
584 for (size_t i = 0; i < env->Size(); i++) {
585 HInstruction* instruction = env->GetInstructionAt(i);
586 SetRawEnvAt(i, instruction);
587 if (instruction == nullptr) {
588 continue;
589 }
590 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
591 // At the end of the loop pre-header, the corresponding value for instruction
592 // is the first input of the phi.
593 HInstruction* initial = instruction->AsPhi()->InputAt(0);
594 DCHECK(initial->GetBlock()->Dominates(loop_header));
595 SetRawEnvAt(i, initial);
596 initial->AddEnvUseAt(this, i);
597 } else {
598 instruction->AddEnvUseAt(this, i);
599 }
600 }
601}
602
David Brazdil1abb4192015-02-17 18:33:36 +0000603void HEnvironment::RemoveAsUserOfInput(size_t index) const {
604 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
605 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100606}
607
Calin Juravle77520bc2015-01-12 18:45:46 +0000608HInstruction* HInstruction::GetNextDisregardingMoves() const {
609 HInstruction* next = GetNext();
610 while (next != nullptr && next->IsParallelMove()) {
611 next = next->GetNext();
612 }
613 return next;
614}
615
616HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
617 HInstruction* previous = GetPrevious();
618 while (previous != nullptr && previous->IsParallelMove()) {
619 previous = previous->GetPrevious();
620 }
621 return previous;
622}
623
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100624void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000625 if (first_instruction_ == nullptr) {
626 DCHECK(last_instruction_ == nullptr);
627 first_instruction_ = last_instruction_ = instruction;
628 } else {
629 last_instruction_->next_ = instruction;
630 instruction->previous_ = last_instruction_;
631 last_instruction_ = instruction;
632 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000633}
634
David Brazdilc3d743f2015-04-22 13:40:50 +0100635void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
636 DCHECK(Contains(cursor));
637 if (cursor == first_instruction_) {
638 cursor->previous_ = instruction;
639 instruction->next_ = cursor;
640 first_instruction_ = instruction;
641 } else {
642 instruction->previous_ = cursor->previous_;
643 instruction->next_ = cursor;
644 cursor->previous_ = instruction;
645 instruction->previous_->next_ = instruction;
646 }
647}
648
649void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
650 DCHECK(Contains(cursor));
651 if (cursor == last_instruction_) {
652 cursor->next_ = instruction;
653 instruction->previous_ = cursor;
654 last_instruction_ = instruction;
655 } else {
656 instruction->next_ = cursor->next_;
657 instruction->previous_ = cursor;
658 cursor->next_ = instruction;
659 instruction->next_->previous_ = instruction;
660 }
661}
662
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100663void HInstructionList::RemoveInstruction(HInstruction* instruction) {
664 if (instruction->previous_ != nullptr) {
665 instruction->previous_->next_ = instruction->next_;
666 }
667 if (instruction->next_ != nullptr) {
668 instruction->next_->previous_ = instruction->previous_;
669 }
670 if (instruction == first_instruction_) {
671 first_instruction_ = instruction->next_;
672 }
673 if (instruction == last_instruction_) {
674 last_instruction_ = instruction->previous_;
675 }
676}
677
Roland Levillain6b469232014-09-25 10:10:38 +0100678bool HInstructionList::Contains(HInstruction* instruction) const {
679 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
680 if (it.Current() == instruction) {
681 return true;
682 }
683 }
684 return false;
685}
686
Roland Levillainccc07a92014-09-16 14:48:16 +0100687bool HInstructionList::FoundBefore(const HInstruction* instruction1,
688 const HInstruction* instruction2) const {
689 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
690 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
691 if (it.Current() == instruction1) {
692 return true;
693 }
694 if (it.Current() == instruction2) {
695 return false;
696 }
697 }
698 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
699 return true;
700}
701
Roland Levillain6c82d402014-10-13 16:10:27 +0100702bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
703 if (other_instruction == this) {
704 // An instruction does not strictly dominate itself.
705 return false;
706 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100707 HBasicBlock* block = GetBlock();
708 HBasicBlock* other_block = other_instruction->GetBlock();
709 if (block != other_block) {
710 return GetBlock()->Dominates(other_instruction->GetBlock());
711 } else {
712 // If both instructions are in the same block, ensure this
713 // instruction comes before `other_instruction`.
714 if (IsPhi()) {
715 if (!other_instruction->IsPhi()) {
716 // Phis appear before non phi-instructions so this instruction
717 // dominates `other_instruction`.
718 return true;
719 } else {
720 // There is no order among phis.
721 LOG(FATAL) << "There is no dominance between phis of a same block.";
722 return false;
723 }
724 } else {
725 // `this` is not a phi.
726 if (other_instruction->IsPhi()) {
727 // Phis appear before non phi-instructions so this instruction
728 // does not dominate `other_instruction`.
729 return false;
730 } else {
731 // Check whether this instruction comes before
732 // `other_instruction` in the instruction list.
733 return block->GetInstructions().FoundBefore(this, other_instruction);
734 }
735 }
736 }
737}
738
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100739void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100740 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000741 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
742 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100743 HInstruction* user = current->GetUser();
744 size_t input_index = current->GetIndex();
745 user->SetRawInputAt(input_index, other);
746 other->AddUseAt(user, input_index);
747 }
748
David Brazdiled596192015-01-23 10:39:45 +0000749 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
750 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100751 HEnvironment* user = current->GetUser();
752 size_t input_index = current->GetIndex();
753 user->SetRawEnvAt(input_index, other);
754 other->AddEnvUseAt(user, input_index);
755 }
756
David Brazdiled596192015-01-23 10:39:45 +0000757 uses_.Clear();
758 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100759}
760
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100761void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000762 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100763 SetRawInputAt(index, replacement);
764 replacement->AddUseAt(this, index);
765}
766
Nicolas Geoffray39468442014-09-02 15:17:15 +0100767size_t HInstruction::EnvironmentSize() const {
768 return HasEnvironment() ? environment_->Size() : 0;
769}
770
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100771void HPhi::AddInput(HInstruction* input) {
772 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000773 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100774 input->AddUseAt(this, inputs_.Size() - 1);
775}
776
David Brazdil2d7352b2015-04-20 14:52:42 +0100777void HPhi::RemoveInputAt(size_t index) {
778 RemoveAsUserOfInput(index);
779 inputs_.DeleteAt(index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100780 for (size_t i = index, e = InputCount(); i < e; ++i) {
781 InputRecordAt(i).GetUseNode()->SetIndex(i);
782 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100783}
784
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100785#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000786void H##name::Accept(HGraphVisitor* visitor) { \
787 visitor->Visit##name(this); \
788}
789
790FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
791
792#undef DEFINE_ACCEPT
793
794void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100795 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
796 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000797 HBasicBlock* block = blocks.Get(i);
798 if (block != nullptr) {
799 VisitBasicBlock(block);
800 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000801 }
802}
803
Roland Levillain633021e2014-10-01 14:12:25 +0100804void HGraphVisitor::VisitReversePostOrder() {
805 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
806 VisitBasicBlock(it.Current());
807 }
808}
809
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000810void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100811 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100812 it.Current()->Accept(this);
813 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100814 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000815 it.Current()->Accept(this);
816 }
817}
818
Mark Mendelle82549b2015-05-06 10:55:34 -0400819HConstant* HTypeConversion::TryStaticEvaluation() const {
820 HGraph* graph = GetBlock()->GetGraph();
821 if (GetInput()->IsIntConstant()) {
822 int32_t value = GetInput()->AsIntConstant()->GetValue();
823 switch (GetResultType()) {
824 case Primitive::kPrimLong:
825 return graph->GetLongConstant(static_cast<int64_t>(value));
826 case Primitive::kPrimFloat:
827 return graph->GetFloatConstant(static_cast<float>(value));
828 case Primitive::kPrimDouble:
829 return graph->GetDoubleConstant(static_cast<double>(value));
830 default:
831 return nullptr;
832 }
833 } else if (GetInput()->IsLongConstant()) {
834 int64_t value = GetInput()->AsLongConstant()->GetValue();
835 switch (GetResultType()) {
836 case Primitive::kPrimInt:
837 return graph->GetIntConstant(static_cast<int32_t>(value));
838 case Primitive::kPrimFloat:
839 return graph->GetFloatConstant(static_cast<float>(value));
840 case Primitive::kPrimDouble:
841 return graph->GetDoubleConstant(static_cast<double>(value));
842 default:
843 return nullptr;
844 }
845 } else if (GetInput()->IsFloatConstant()) {
846 float value = GetInput()->AsFloatConstant()->GetValue();
847 switch (GetResultType()) {
848 case Primitive::kPrimInt:
849 if (std::isnan(value))
850 return graph->GetIntConstant(0);
851 if (value >= kPrimIntMax)
852 return graph->GetIntConstant(kPrimIntMax);
853 if (value <= kPrimIntMin)
854 return graph->GetIntConstant(kPrimIntMin);
855 return graph->GetIntConstant(static_cast<int32_t>(value));
856 case Primitive::kPrimLong:
857 if (std::isnan(value))
858 return graph->GetLongConstant(0);
859 if (value >= kPrimLongMax)
860 return graph->GetLongConstant(kPrimLongMax);
861 if (value <= kPrimLongMin)
862 return graph->GetLongConstant(kPrimLongMin);
863 return graph->GetLongConstant(static_cast<int64_t>(value));
864 case Primitive::kPrimDouble:
865 return graph->GetDoubleConstant(static_cast<double>(value));
866 default:
867 return nullptr;
868 }
869 } else if (GetInput()->IsDoubleConstant()) {
870 double value = GetInput()->AsDoubleConstant()->GetValue();
871 switch (GetResultType()) {
872 case Primitive::kPrimInt:
873 if (std::isnan(value))
874 return graph->GetIntConstant(0);
875 if (value >= kPrimIntMax)
876 return graph->GetIntConstant(kPrimIntMax);
877 if (value <= kPrimLongMin)
878 return graph->GetIntConstant(kPrimIntMin);
879 return graph->GetIntConstant(static_cast<int32_t>(value));
880 case Primitive::kPrimLong:
881 if (std::isnan(value))
882 return graph->GetLongConstant(0);
883 if (value >= kPrimLongMax)
884 return graph->GetLongConstant(kPrimLongMax);
885 if (value <= kPrimLongMin)
886 return graph->GetLongConstant(kPrimLongMin);
887 return graph->GetLongConstant(static_cast<int64_t>(value));
888 case Primitive::kPrimFloat:
889 return graph->GetFloatConstant(static_cast<float>(value));
890 default:
891 return nullptr;
892 }
893 }
894 return nullptr;
895}
896
Roland Levillain9240d6a2014-10-20 16:47:04 +0100897HConstant* HUnaryOperation::TryStaticEvaluation() const {
898 if (GetInput()->IsIntConstant()) {
899 int32_t value = Evaluate(GetInput()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000900 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain9240d6a2014-10-20 16:47:04 +0100901 } else if (GetInput()->IsLongConstant()) {
Roland Levillainb762d2e2014-10-22 10:11:06 +0100902 // TODO: Implement static evaluation of long unary operations.
903 //
904 // Do not exit with a fatal condition here. Instead, simply
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700905 // return `null' to notify the caller that this instruction
Roland Levillainb762d2e2014-10-22 10:11:06 +0100906 // cannot (yet) be statically evaluated.
Roland Levillain9240d6a2014-10-20 16:47:04 +0100907 return nullptr;
908 }
909 return nullptr;
910}
911
912HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain556c3d12014-09-18 15:25:07 +0100913 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
914 int32_t value = Evaluate(GetLeft()->AsIntConstant()->GetValue(),
915 GetRight()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000916 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain556c3d12014-09-18 15:25:07 +0100917 } else if (GetLeft()->IsLongConstant() && GetRight()->IsLongConstant()) {
918 int64_t value = Evaluate(GetLeft()->AsLongConstant()->GetValue(),
919 GetRight()->AsLongConstant()->GetValue());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000920 if (GetResultType() == Primitive::kPrimLong) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000921 return GetBlock()->GetGraph()->GetLongConstant(value);
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000922 } else {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000923 DCHECK_EQ(GetResultType(), Primitive::kPrimInt);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000924 return GetBlock()->GetGraph()->GetIntConstant(static_cast<int32_t>(value));
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000925 }
Roland Levillain556c3d12014-09-18 15:25:07 +0100926 }
927 return nullptr;
928}
Dave Allison20dfc792014-06-16 20:44:29 -0700929
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000930HConstant* HBinaryOperation::GetConstantRight() const {
931 if (GetRight()->IsConstant()) {
932 return GetRight()->AsConstant();
933 } else if (IsCommutative() && GetLeft()->IsConstant()) {
934 return GetLeft()->AsConstant();
935 } else {
936 return nullptr;
937 }
938}
939
940// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700941// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000942HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
943 HInstruction* most_constant_right = GetConstantRight();
944 if (most_constant_right == nullptr) {
945 return nullptr;
946 } else if (most_constant_right == GetLeft()) {
947 return GetRight();
948 } else {
949 return GetLeft();
950 }
951}
952
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700953bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
954 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100955}
956
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100957bool HInstruction::Equals(HInstruction* other) const {
958 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100959 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100960 if (!InstructionDataEquals(other)) return false;
961 if (GetType() != other->GetType()) return false;
962 if (InputCount() != other->InputCount()) return false;
963
964 for (size_t i = 0, e = InputCount(); i < e; ++i) {
965 if (InputAt(i) != other->InputAt(i)) return false;
966 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100967 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100968 return true;
969}
970
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700971std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
972#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
973 switch (rhs) {
974 FOR_EACH_INSTRUCTION(DECLARE_CASE)
975 default:
976 os << "Unknown instruction kind " << static_cast<int>(rhs);
977 break;
978 }
979#undef DECLARE_CASE
980 return os;
981}
982
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000983void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000984 next_->previous_ = previous_;
985 if (previous_ != nullptr) {
986 previous_->next_ = next_;
987 }
988 if (block_->instructions_.first_instruction_ == this) {
989 block_->instructions_.first_instruction_ = next_;
990 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000991 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000992
993 previous_ = cursor->previous_;
994 if (previous_ != nullptr) {
995 previous_->next_ = this;
996 }
997 next_ = cursor;
998 cursor->previous_ = this;
999 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001000
1001 if (block_->instructions_.first_instruction_ == cursor) {
1002 block_->instructions_.first_instruction_ = this;
1003 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001004}
1005
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001006HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1007 DCHECK(!cursor->IsControlFlow());
1008 DCHECK_NE(instructions_.last_instruction_, cursor);
1009 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001010
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001011 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1012 new_block->instructions_.first_instruction_ = cursor->GetNext();
1013 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1014 cursor->next_->previous_ = nullptr;
1015 cursor->next_ = nullptr;
1016 instructions_.last_instruction_ = cursor;
1017
1018 new_block->instructions_.SetBlockOfInstructions(new_block);
1019 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
1020 HBasicBlock* successor = GetSuccessors().Get(i);
1021 new_block->successors_.Add(successor);
1022 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
1023 }
1024 successors_.Reset();
1025
1026 for (size_t i = 0, e = GetDominatedBlocks().Size(); i < e; ++i) {
1027 HBasicBlock* dominated = GetDominatedBlocks().Get(i);
1028 dominated->dominator_ = new_block;
1029 new_block->dominated_blocks_.Add(dominated);
1030 }
1031 dominated_blocks_.Reset();
1032 return new_block;
1033}
1034
David Brazdil46e2a392015-03-16 17:31:52 +00001035bool HBasicBlock::IsSingleGoto() const {
1036 HLoopInformation* loop_info = GetLoopInformation();
1037 // TODO: Remove the null check b/19084197.
1038 return GetFirstInstruction() != nullptr
1039 && GetPhis().IsEmpty()
1040 && GetFirstInstruction() == GetLastInstruction()
1041 && GetLastInstruction()->IsGoto()
1042 // Back edges generate the suspend check.
1043 && (loop_info == nullptr || !loop_info->IsBackEdge(*this));
1044}
1045
David Brazdil8d5b8b22015-03-24 10:51:52 +00001046bool HBasicBlock::EndsWithControlFlowInstruction() const {
1047 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1048}
1049
David Brazdilb2bd1c52015-03-25 11:17:37 +00001050bool HBasicBlock::EndsWithIf() const {
1051 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1052}
1053
1054bool HBasicBlock::HasSinglePhi() const {
1055 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1056}
1057
David Brazdil2d7352b2015-04-20 14:52:42 +01001058size_t HInstructionList::CountSize() const {
1059 size_t size = 0;
1060 HInstruction* current = first_instruction_;
1061 for (; current != nullptr; current = current->GetNext()) {
1062 size++;
1063 }
1064 return size;
1065}
1066
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001067void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1068 for (HInstruction* current = first_instruction_;
1069 current != nullptr;
1070 current = current->GetNext()) {
1071 current->SetBlock(block);
1072 }
1073}
1074
1075void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1076 DCHECK(Contains(cursor));
1077 if (!instruction_list.IsEmpty()) {
1078 if (cursor == last_instruction_) {
1079 last_instruction_ = instruction_list.last_instruction_;
1080 } else {
1081 cursor->next_->previous_ = instruction_list.last_instruction_;
1082 }
1083 instruction_list.last_instruction_->next_ = cursor->next_;
1084 cursor->next_ = instruction_list.first_instruction_;
1085 instruction_list.first_instruction_->previous_ = cursor;
1086 }
1087}
1088
1089void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001090 if (IsEmpty()) {
1091 first_instruction_ = instruction_list.first_instruction_;
1092 last_instruction_ = instruction_list.last_instruction_;
1093 } else {
1094 AddAfter(last_instruction_, instruction_list);
1095 }
1096}
1097
David Brazdil2d7352b2015-04-20 14:52:42 +01001098void HBasicBlock::DisconnectAndDelete() {
1099 // Dominators must be removed after all the blocks they dominate. This way
1100 // a loop header is removed last, a requirement for correct loop information
1101 // iteration.
1102 DCHECK(dominated_blocks_.IsEmpty());
David Brazdil46e2a392015-03-16 17:31:52 +00001103
David Brazdil2d7352b2015-04-20 14:52:42 +01001104 // Remove the block from all loops it is included in.
1105 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1106 HLoopInformation* loop_info = it.Current();
1107 loop_info->Remove(this);
1108 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001109 // If this was the last back edge of the loop, we deliberately leave the
1110 // loop in an inconsistent state and will fail SSAChecker unless the
1111 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001112 loop_info->RemoveBackEdge(this);
1113 }
1114 }
1115
1116 // Disconnect the block from its predecessors and update their control-flow
1117 // instructions.
David Brazdil46e2a392015-03-16 17:31:52 +00001118 for (size_t i = 0, e = predecessors_.Size(); i < e; ++i) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001119 HBasicBlock* predecessor = predecessors_.Get(i);
1120 HInstruction* last_instruction = predecessor->GetLastInstruction();
1121 predecessor->RemoveInstruction(last_instruction);
1122 predecessor->RemoveSuccessor(this);
1123 if (predecessor->GetSuccessors().Size() == 1u) {
1124 DCHECK(last_instruction->IsIf());
1125 predecessor->AddInstruction(new (graph_->GetArena()) HGoto());
1126 } else {
1127 // The predecessor has no remaining successors and therefore must be dead.
1128 // We deliberately leave it without a control-flow instruction so that the
1129 // SSAChecker fails unless it is not removed during the pass too.
1130 DCHECK_EQ(predecessor->GetSuccessors().Size(), 0u);
1131 }
David Brazdil46e2a392015-03-16 17:31:52 +00001132 }
David Brazdil46e2a392015-03-16 17:31:52 +00001133 predecessors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +01001134
1135 // Disconnect the block from its successors and update their dominators
1136 // and phis.
1137 for (size_t i = 0, e = successors_.Size(); i < e; ++i) {
1138 HBasicBlock* successor = successors_.Get(i);
1139 // Delete this block from the list of predecessors.
1140 size_t this_index = successor->GetPredecessorIndexOf(this);
1141 successor->predecessors_.DeleteAt(this_index);
1142
1143 // Check that `successor` has other predecessors, otherwise `this` is the
1144 // dominator of `successor` which violates the order DCHECKed at the top.
1145 DCHECK(!successor->predecessors_.IsEmpty());
1146
1147 // Recompute the successor's dominator.
1148 HBasicBlock* old_dominator = successor->GetDominator();
1149 HBasicBlock* new_dominator = successor->predecessors_.Get(0);
1150 for (size_t j = 1, f = successor->predecessors_.Size(); j < f; ++j) {
1151 new_dominator = graph_->FindCommonDominator(
1152 new_dominator, successor->predecessors_.Get(j));
1153 }
1154 if (old_dominator != new_dominator) {
1155 successor->SetDominator(new_dominator);
1156 old_dominator->RemoveDominatedBlock(successor);
1157 new_dominator->AddDominatedBlock(successor);
1158 }
1159
1160 // Remove this block's entries in the successor's phis.
1161 if (successor->predecessors_.Size() == 1u) {
1162 // The successor has just one predecessor left. Replace phis with the only
1163 // remaining input.
1164 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1165 HPhi* phi = phi_it.Current()->AsPhi();
1166 phi->ReplaceWith(phi->InputAt(1 - this_index));
1167 successor->RemovePhi(phi);
1168 }
1169 } else {
1170 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1171 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1172 }
1173 }
1174 }
David Brazdil46e2a392015-03-16 17:31:52 +00001175 successors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +01001176
1177 // Disconnect from the dominator.
1178 dominator_->RemoveDominatedBlock(this);
1179 SetDominator(nullptr);
1180
1181 // Delete from the graph. The function safely deletes remaining instructions
1182 // and updates the reverse post order.
1183 graph_->DeleteDeadBlock(this);
1184 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001185}
1186
1187void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001188 DCHECK_EQ(GetGraph(), other->GetGraph());
1189 DCHECK(GetDominatedBlocks().Contains(other));
1190 DCHECK_EQ(GetSuccessors().Size(), 1u);
1191 DCHECK_EQ(GetSuccessors().Get(0), other);
1192 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1193 DCHECK_EQ(other->GetPredecessors().Get(0), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001194 DCHECK(other->GetPhis().IsEmpty());
1195
David Brazdil2d7352b2015-04-20 14:52:42 +01001196 // Move instructions from `other` to `this`.
1197 DCHECK(EndsWithControlFlowInstruction());
1198 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001199 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001200 other->instructions_.SetBlockOfInstructions(this);
1201 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001202
David Brazdil2d7352b2015-04-20 14:52:42 +01001203 // Remove `other` from the loops it is included in.
1204 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1205 HLoopInformation* loop_info = it.Current();
1206 loop_info->Remove(other);
1207 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001208 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001209 }
1210 }
1211
1212 // Update links to the successors of `other`.
1213 successors_.Reset();
1214 while (!other->successors_.IsEmpty()) {
1215 HBasicBlock* successor = other->successors_.Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001216 successor->ReplacePredecessor(other, this);
1217 }
1218
David Brazdil2d7352b2015-04-20 14:52:42 +01001219 // Update the dominator tree.
1220 dominated_blocks_.Delete(other);
1221 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1222 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1223 dominated_blocks_.Add(dominated);
1224 dominated->SetDominator(this);
1225 }
1226 other->dominated_blocks_.Reset();
1227 other->dominator_ = nullptr;
1228
1229 // Clear the list of predecessors of `other` in preparation of deleting it.
1230 other->predecessors_.Reset();
1231
1232 // Delete `other` from the graph. The function updates reverse post order.
1233 graph_->DeleteDeadBlock(other);
1234 other->SetGraph(nullptr);
1235}
1236
1237void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1238 DCHECK_NE(GetGraph(), other->GetGraph());
1239 DCHECK(GetDominatedBlocks().IsEmpty());
1240 DCHECK(GetSuccessors().IsEmpty());
1241 DCHECK(!EndsWithControlFlowInstruction());
1242 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1243 DCHECK(other->GetPredecessors().Get(0)->IsEntryBlock());
1244 DCHECK(other->GetPhis().IsEmpty());
1245 DCHECK(!other->IsInLoop());
1246
1247 // Move instructions from `other` to `this`.
1248 instructions_.Add(other->GetInstructions());
1249 other->instructions_.SetBlockOfInstructions(this);
1250
1251 // Update links to the successors of `other`.
1252 successors_.Reset();
1253 while (!other->successors_.IsEmpty()) {
1254 HBasicBlock* successor = other->successors_.Get(0);
1255 successor->ReplacePredecessor(other, this);
1256 }
1257
1258 // Update the dominator tree.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001259 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1260 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1261 dominated_blocks_.Add(dominated);
1262 dominated->SetDominator(this);
1263 }
1264 other->dominated_blocks_.Reset();
1265 other->dominator_ = nullptr;
1266 other->graph_ = nullptr;
1267}
1268
1269void HBasicBlock::ReplaceWith(HBasicBlock* other) {
1270 while (!GetPredecessors().IsEmpty()) {
1271 HBasicBlock* predecessor = GetPredecessors().Get(0);
1272 predecessor->ReplaceSuccessor(this, other);
1273 }
1274 while (!GetSuccessors().IsEmpty()) {
1275 HBasicBlock* successor = GetSuccessors().Get(0);
1276 successor->ReplacePredecessor(this, other);
1277 }
1278 for (size_t i = 0; i < dominated_blocks_.Size(); ++i) {
1279 other->AddDominatedBlock(dominated_blocks_.Get(i));
1280 }
1281 GetDominator()->ReplaceDominatedBlock(this, other);
1282 other->SetDominator(GetDominator());
1283 dominator_ = nullptr;
1284 graph_ = nullptr;
1285}
1286
1287// Create space in `blocks` for adding `number_of_new_blocks` entries
1288// starting at location `at`. Blocks after `at` are moved accordingly.
1289static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
1290 size_t number_of_new_blocks,
1291 size_t at) {
1292 size_t old_size = blocks->Size();
1293 size_t new_size = old_size + number_of_new_blocks;
1294 blocks->SetSize(new_size);
1295 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
1296 blocks->Put(j, blocks->Get(i));
1297 }
1298}
1299
David Brazdil2d7352b2015-04-20 14:52:42 +01001300void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1301 DCHECK_EQ(block->GetGraph(), this);
1302 DCHECK(block->GetSuccessors().IsEmpty());
1303 DCHECK(block->GetPredecessors().IsEmpty());
1304 DCHECK(block->GetDominatedBlocks().IsEmpty());
1305 DCHECK(block->GetDominator() == nullptr);
1306
1307 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1308 block->RemoveInstruction(it.Current());
1309 }
1310 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1311 block->RemovePhi(it.Current()->AsPhi());
1312 }
1313
David Brazdilc7af85d2015-05-26 12:05:55 +01001314 if (block->IsExitBlock()) {
1315 exit_block_ = nullptr;
1316 }
1317
David Brazdil2d7352b2015-04-20 14:52:42 +01001318 reverse_post_order_.Delete(block);
1319 blocks_.Put(block->GetBlockId(), nullptr);
1320}
1321
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001322void HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001323 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001324 // Update the environments in this graph to have the invoke's environment
1325 // as parent.
1326 {
1327 HReversePostOrderIterator it(*this);
1328 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1329 for (; !it.Done(); it.Advance()) {
1330 HBasicBlock* block = it.Current();
1331 for (HInstructionIterator instr_it(block->GetInstructions());
1332 !instr_it.Done();
1333 instr_it.Advance()) {
1334 HInstruction* current = instr_it.Current();
1335 if (current->NeedsEnvironment()) {
1336 current->GetEnvironment()->SetAndCopyParentChain(
1337 outer_graph->GetArena(), invoke->GetEnvironment());
1338 }
1339 }
1340 }
1341 }
1342 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1343 if (HasBoundsChecks()) {
1344 outer_graph->SetHasBoundsChecks(true);
1345 }
1346
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001347 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001348 // Simple case of an entry block, a body block, and an exit block.
1349 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001350 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001351 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
1352 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001353 DCHECK(!body->IsExitBlock());
1354 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001355
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001356 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1357 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001358
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001359 // Replace the invoke with the return value of the inlined graph.
1360 if (last->IsReturn()) {
1361 invoke->ReplaceWith(last->InputAt(0));
1362 } else {
1363 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001364 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001365
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001366 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001367 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001368 // Need to inline multiple blocks. We split `invoke`'s block
1369 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001370 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001371 // with the second half.
1372 ArenaAllocator* allocator = outer_graph->GetArena();
1373 HBasicBlock* at = invoke->GetBlock();
1374 HBasicBlock* to = at->SplitAfter(invoke);
1375
1376 HBasicBlock* first = entry_block_->GetSuccessors().Get(0);
1377 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001378 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001379 exit_block_->ReplaceWith(to);
1380
1381 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001382 // to not `HReturn` but `HGoto` instead.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001383 HInstruction* return_value = nullptr;
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001384 bool returns_void = to->GetPredecessors().Get(0)->GetLastInstruction()->IsReturnVoid();
1385 if (to->GetPredecessors().Size() == 1) {
1386 HBasicBlock* predecessor = to->GetPredecessors().Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001387 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001388 if (!returns_void) {
1389 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001390 }
1391 predecessor->AddInstruction(new (allocator) HGoto());
1392 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001393 } else {
1394 if (!returns_void) {
1395 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001396 return_value = new (allocator) HPhi(
1397 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001398 to->AddPhi(return_value->AsPhi());
1399 }
1400 for (size_t i = 0, e = to->GetPredecessors().Size(); i < e; ++i) {
1401 HBasicBlock* predecessor = to->GetPredecessors().Get(i);
1402 HInstruction* last = predecessor->GetLastInstruction();
1403 if (!returns_void) {
1404 return_value->AsPhi()->AddInput(last->InputAt(0));
1405 }
1406 predecessor->AddInstruction(new (allocator) HGoto());
1407 predecessor->RemoveInstruction(last);
1408 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001409 }
1410
1411 if (return_value != nullptr) {
1412 invoke->ReplaceWith(return_value);
1413 }
1414
1415 // Update the meta information surrounding blocks:
1416 // (1) the graph they are now in,
1417 // (2) the reverse post order of that graph,
1418 // (3) the potential loop information they are now in.
1419
1420 // We don't add the entry block, the exit block, and the first block, which
1421 // has been merged with `at`.
1422 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1423
1424 // We add the `to` block.
1425 static constexpr int kNumberOfNewBlocksInCaller = 1;
1426 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1427 + kNumberOfNewBlocksInCaller;
1428
1429 // Find the location of `at` in the outer graph's reverse post order. The new
1430 // blocks will be added after it.
1431 size_t index_of_at = 0;
1432 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1433 index_of_at++;
1434 }
1435 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1436
1437 // Do a reverse post order of the blocks in the callee and do (1), (2),
1438 // and (3) to the blocks that apply.
1439 HLoopInformation* info = at->GetLoopInformation();
1440 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1441 HBasicBlock* current = it.Current();
1442 if (current != exit_block_ && current != entry_block_ && current != first) {
1443 DCHECK(!current->IsInLoop());
1444 DCHECK(current->GetGraph() == this);
1445 current->SetGraph(outer_graph);
1446 outer_graph->AddBlock(current);
1447 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1448 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001449 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001450 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1451 loop_it.Current()->Add(current);
1452 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001453 }
1454 }
1455 }
1456
1457 // Do (1), (2), and (3) to `to`.
1458 to->SetGraph(outer_graph);
1459 outer_graph->AddBlock(to);
1460 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1461 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001462 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001463 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1464 loop_it.Current()->Add(to);
1465 }
David Brazdil46e2a392015-03-16 17:31:52 +00001466 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001467 // Only `to` can become a back edge, as the inlined blocks
1468 // are predecessors of `to`.
1469 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001470 }
1471 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001472 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001473
David Brazdil05144f42015-04-16 15:18:00 +01001474 // Update the next instruction id of the outer graph, so that instructions
1475 // added later get bigger ids than those in the inner graph.
1476 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1477
1478 // Walk over the entry block and:
1479 // - Move constants from the entry block to the outer_graph's entry block,
1480 // - Replace HParameterValue instructions with their real value.
1481 // - Remove suspend checks, that hold an environment.
1482 // We must do this after the other blocks have been inlined, otherwise ids of
1483 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001484 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001485 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1486 HInstruction* current = it.Current();
1487 if (current->IsNullConstant()) {
1488 current->ReplaceWith(outer_graph->GetNullConstant());
1489 } else if (current->IsIntConstant()) {
1490 current->ReplaceWith(outer_graph->GetIntConstant(current->AsIntConstant()->GetValue()));
1491 } else if (current->IsLongConstant()) {
1492 current->ReplaceWith(outer_graph->GetLongConstant(current->AsLongConstant()->GetValue()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001493 } else if (current->IsFloatConstant()) {
1494 current->ReplaceWith(outer_graph->GetFloatConstant(current->AsFloatConstant()->GetValue()));
1495 } else if (current->IsDoubleConstant()) {
1496 current->ReplaceWith(outer_graph->GetDoubleConstant(current->AsDoubleConstant()->GetValue()));
David Brazdil05144f42015-04-16 15:18:00 +01001497 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001498 if (kIsDebugBuild
1499 && invoke->IsInvokeStaticOrDirect()
1500 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1501 // Ensure we do not use the last input of `invoke`, as it
1502 // contains a clinit check which is not an actual argument.
1503 size_t last_input_index = invoke->InputCount() - 1;
1504 DCHECK(parameter_index != last_input_index);
1505 }
David Brazdil05144f42015-04-16 15:18:00 +01001506 current->ReplaceWith(invoke->InputAt(parameter_index++));
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001507 } else if (current->IsCurrentMethod()) {
1508 current->ReplaceWith(outer_graph->GetCurrentMethod());
David Brazdil05144f42015-04-16 15:18:00 +01001509 } else {
1510 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1511 entry_block_->RemoveInstruction(current);
1512 }
1513 }
1514
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001515 // Finally remove the invoke from the caller.
1516 invoke->GetBlock()->RemoveInstruction(invoke);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001517}
1518
Mingyao Yang3584bce2015-05-19 16:01:59 -07001519/*
1520 * Loop will be transformed to:
1521 * old_pre_header
1522 * |
1523 * if_block
1524 * / \
1525 * dummy_block deopt_block
1526 * \ /
1527 * new_pre_header
1528 * |
1529 * header
1530 */
1531void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1532 DCHECK(header->IsLoopHeader());
1533 HBasicBlock* pre_header = header->GetDominator();
1534
1535 // Need this to avoid critical edge.
1536 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1537 // Need this to avoid critical edge.
1538 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1539 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1540 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1541 AddBlock(if_block);
1542 AddBlock(dummy_block);
1543 AddBlock(deopt_block);
1544 AddBlock(new_pre_header);
1545
1546 header->ReplacePredecessor(pre_header, new_pre_header);
1547 pre_header->successors_.Reset();
1548 pre_header->dominated_blocks_.Reset();
1549
1550 pre_header->AddSuccessor(if_block);
1551 if_block->AddSuccessor(dummy_block); // True successor
1552 if_block->AddSuccessor(deopt_block); // False successor
1553 dummy_block->AddSuccessor(new_pre_header);
1554 deopt_block->AddSuccessor(new_pre_header);
1555
1556 pre_header->dominated_blocks_.Add(if_block);
1557 if_block->SetDominator(pre_header);
1558 if_block->dominated_blocks_.Add(dummy_block);
1559 dummy_block->SetDominator(if_block);
1560 if_block->dominated_blocks_.Add(deopt_block);
1561 deopt_block->SetDominator(if_block);
1562 if_block->dominated_blocks_.Add(new_pre_header);
1563 new_pre_header->SetDominator(if_block);
1564 new_pre_header->dominated_blocks_.Add(header);
1565 header->SetDominator(new_pre_header);
1566
1567 size_t index_of_header = 0;
1568 while (reverse_post_order_.Get(index_of_header) != header) {
1569 index_of_header++;
1570 }
1571 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
1572 reverse_post_order_.Put(index_of_header++, if_block);
1573 reverse_post_order_.Put(index_of_header++, dummy_block);
1574 reverse_post_order_.Put(index_of_header++, deopt_block);
1575 reverse_post_order_.Put(index_of_header++, new_pre_header);
1576
1577 HLoopInformation* info = pre_header->GetLoopInformation();
1578 if (info != nullptr) {
1579 if_block->SetLoopInformation(info);
1580 dummy_block->SetLoopInformation(info);
1581 deopt_block->SetLoopInformation(info);
1582 new_pre_header->SetLoopInformation(info);
1583 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1584 !loop_it.Done();
1585 loop_it.Advance()) {
1586 loop_it.Current()->Add(if_block);
1587 loop_it.Current()->Add(dummy_block);
1588 loop_it.Current()->Add(deopt_block);
1589 loop_it.Current()->Add(new_pre_header);
1590 }
1591 }
1592}
1593
Calin Juravleacf735c2015-02-12 15:25:22 +00001594std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1595 ScopedObjectAccess soa(Thread::Current());
1596 os << "["
1597 << " is_top=" << rhs.IsTop()
1598 << " type=" << (rhs.IsTop() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
1599 << " is_exact=" << rhs.IsExact()
1600 << " ]";
1601 return os;
1602}
1603
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001604} // namespace art