blob: 588ab70001a5e05d1dba70e0642f817b16169d89 [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
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100120 // (5) Compute the dominance information and the reverse post order.
121 ComputeDominanceInformation();
122}
123
124void HGraph::ClearDominanceInformation() {
125 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
126 it.Current()->ClearDominanceInformation();
127 }
128 reverse_post_order_.Reset();
129}
130
131void HBasicBlock::ClearDominanceInformation() {
132 dominated_blocks_.Reset();
133 dominator_ = nullptr;
134}
135
136void HGraph::ComputeDominanceInformation() {
137 DCHECK(reverse_post_order_.IsEmpty());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000138 GrowableArray<size_t> visits(arena_, blocks_.Size());
139 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100140 reverse_post_order_.Add(entry_block_);
141 for (size_t i = 0; i < entry_block_->GetSuccessors().Size(); i++) {
142 VisitBlockForDominatorTree(entry_block_->GetSuccessors().Get(i), entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000143 }
144}
145
146HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
147 ArenaBitVector visited(arena_, blocks_.Size(), false);
148 // Walk the dominator tree of the first block and mark the visited blocks.
149 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000150 visited.SetBit(first->GetBlockId());
151 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000152 }
153 // Walk the dominator tree of the second block until a marked block is found.
154 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000155 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000156 return second;
157 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000158 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000159 }
160 LOG(ERROR) << "Could not find common dominator";
161 return nullptr;
162}
163
164void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
165 HBasicBlock* predecessor,
166 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000167 if (block->GetDominator() == nullptr) {
168 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000169 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000170 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000171 }
172
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000173 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000174 // Once all the forward edges have been visited, we know the immediate
175 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000176 if (visits->Get(block->GetBlockId()) ==
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100177 block->GetPredecessors().Size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100178 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100179 reverse_post_order_.Add(block);
180 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
181 VisitBlockForDominatorTree(block->GetSuccessors().Get(i), block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000182 }
183 }
184}
185
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000186void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100187 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100188 SsaBuilder ssa_builder(this);
189 ssa_builder.BuildSsa();
190}
191
David Brazdilfc6a86a2015-06-26 10:33:45 +0000192HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000193 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
194 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000195 // Use `InsertBetween` to ensure the predecessor index and successor index of
196 // `block` and `successor` are preserved.
197 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000198 return new_block;
199}
200
201void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
202 // Insert a new node between `block` and `successor` to split the
203 // critical edge.
204 HBasicBlock* new_block = SplitEdge(block, successor);
205 new_block->AddInstruction(new (arena_) HGoto());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100206 if (successor->IsLoopHeader()) {
207 // If we split at a back edge boundary, make the new block the back edge.
208 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000209 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100210 info->RemoveBackEdge(block);
211 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100212 }
213 }
214}
215
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100216void HGraph::SimplifyLoop(HBasicBlock* header) {
217 HLoopInformation* info = header->GetLoopInformation();
218
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100219 // Make sure the loop has only one pre header. This simplifies SSA building by having
220 // to just look at the pre header to know which locals are initialized at entry of the
221 // loop.
222 size_t number_of_incomings = header->GetPredecessors().Size() - info->NumberOfBackEdges();
223 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100224 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100225 AddBlock(pre_header);
226 pre_header->AddInstruction(new (arena_) HGoto());
227
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100228 for (size_t pred = 0; pred < header->GetPredecessors().Size(); ++pred) {
229 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100230 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100231 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100232 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100233 }
234 }
235 pre_header->AddSuccessor(header);
236 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100237
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100238 // Make sure the first predecessor of a loop header is the incoming block.
239 if (info->IsBackEdge(*header->GetPredecessors().Get(0))) {
240 HBasicBlock* to_swap = header->GetPredecessors().Get(0);
241 for (size_t pred = 1, e = header->GetPredecessors().Size(); pred < e; ++pred) {
242 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
243 if (!info->IsBackEdge(*predecessor)) {
244 header->predecessors_.Put(pred, to_swap);
245 header->predecessors_.Put(0, predecessor);
246 break;
247 }
248 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100249 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100250
251 // Place the suspend check at the beginning of the header, so that live registers
252 // will be known when allocating registers. Note that code generation can still
253 // generate the suspend check at the back edge, but needs to be careful with
254 // loop phi spill slots (which are not written to at back edge).
255 HInstruction* first_instruction = header->GetFirstInstruction();
256 if (!first_instruction->IsSuspendCheck()) {
257 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
258 header->InsertInstructionBefore(check, first_instruction);
259 first_instruction = check;
260 }
261 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100262}
263
264void HGraph::SimplifyCFG() {
265 // Simplify the CFG for future analysis, and code generation:
266 // (1): Split critical edges.
267 // (2): Simplify loops by having only one back edge, and one preheader.
268 for (size_t i = 0; i < blocks_.Size(); ++i) {
269 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100270 if (block == nullptr) continue;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100271 if (block->GetSuccessors().Size() > 1) {
272 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
273 HBasicBlock* successor = block->GetSuccessors().Get(j);
274 if (successor->GetPredecessors().Size() > 1) {
275 SplitCriticalEdge(block, successor);
276 --j;
277 }
278 }
279 }
280 if (block->IsLoopHeader()) {
281 SimplifyLoop(block);
282 }
283 }
284}
285
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000286bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100287 // Order does not matter.
288 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
289 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100290 if (block->IsLoopHeader()) {
291 HLoopInformation* info = block->GetLoopInformation();
292 if (!info->Populate()) {
293 // Abort if the loop is non natural. We currently bailout in such cases.
294 return false;
295 }
296 }
297 }
298 return true;
299}
300
David Brazdil8d5b8b22015-03-24 10:51:52 +0000301void HGraph::InsertConstant(HConstant* constant) {
302 // New constants are inserted before the final control-flow instruction
303 // of the graph, or at its end if called from the graph builder.
304 if (entry_block_->EndsWithControlFlowInstruction()) {
305 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000306 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000307 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000308 }
309}
310
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000311HNullConstant* HGraph::GetNullConstant() {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100312 // For simplicity, don't bother reviving the cached null constant if it is
313 // not null and not in a block. Otherwise, we need to clear the instruction
314 // id and/or any invariants the graph is assuming when adding new instructions.
315 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000316 cached_null_constant_ = new (arena_) HNullConstant();
David Brazdil8d5b8b22015-03-24 10:51:52 +0000317 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000318 }
319 return cached_null_constant_;
320}
321
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100322HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100323 // For simplicity, don't bother reviving the cached current method if it is
324 // not null and not in a block. Otherwise, we need to clear the instruction
325 // id and/or any invariants the graph is assuming when adding new instructions.
326 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700327 cached_current_method_ = new (arena_) HCurrentMethod(
328 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100329 if (entry_block_->GetFirstInstruction() == nullptr) {
330 entry_block_->AddInstruction(cached_current_method_);
331 } else {
332 entry_block_->InsertInstructionBefore(
333 cached_current_method_, entry_block_->GetFirstInstruction());
334 }
335 }
336 return cached_current_method_;
337}
338
David Brazdil8d5b8b22015-03-24 10:51:52 +0000339HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value) {
340 switch (type) {
341 case Primitive::Type::kPrimBoolean:
342 DCHECK(IsUint<1>(value));
343 FALLTHROUGH_INTENDED;
344 case Primitive::Type::kPrimByte:
345 case Primitive::Type::kPrimChar:
346 case Primitive::Type::kPrimShort:
347 case Primitive::Type::kPrimInt:
348 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
349 return GetIntConstant(static_cast<int32_t>(value));
350
351 case Primitive::Type::kPrimLong:
352 return GetLongConstant(value);
353
354 default:
355 LOG(FATAL) << "Unsupported constant type";
356 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000357 }
David Brazdil46e2a392015-03-16 17:31:52 +0000358}
359
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000360void HGraph::CacheFloatConstant(HFloatConstant* constant) {
361 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
362 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
363 cached_float_constants_.Overwrite(value, constant);
364}
365
366void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
367 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
368 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
369 cached_double_constants_.Overwrite(value, constant);
370}
371
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000372void HLoopInformation::Add(HBasicBlock* block) {
373 blocks_.SetBit(block->GetBlockId());
374}
375
David Brazdil46e2a392015-03-16 17:31:52 +0000376void HLoopInformation::Remove(HBasicBlock* block) {
377 blocks_.ClearBit(block->GetBlockId());
378}
379
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100380void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
381 if (blocks_.IsBitSet(block->GetBlockId())) {
382 return;
383 }
384
385 blocks_.SetBit(block->GetBlockId());
386 block->SetInLoop(this);
387 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
388 PopulateRecursive(block->GetPredecessors().Get(i));
389 }
390}
391
392bool HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100393 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100394 for (size_t i = 0, e = GetBackEdges().Size(); i < e; ++i) {
395 HBasicBlock* back_edge = GetBackEdges().Get(i);
396 DCHECK(back_edge->GetDominator() != nullptr);
397 if (!header_->Dominates(back_edge)) {
398 // This loop is not natural. Do not bother going further.
399 return false;
400 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100401
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100402 // Populate this loop: starting with the back edge, recursively add predecessors
403 // that are not already part of that loop. Set the header as part of the loop
404 // to end the recursion.
405 // This is a recursive implementation of the algorithm described in
406 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
407 blocks_.SetBit(header_->GetBlockId());
408 PopulateRecursive(back_edge);
409 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100410 return true;
411}
412
David Brazdila4b8c212015-05-07 09:59:30 +0100413void HLoopInformation::Update() {
414 HGraph* graph = header_->GetGraph();
415 for (uint32_t id : blocks_.Indexes()) {
416 HBasicBlock* block = graph->GetBlocks().Get(id);
417 // Reset loop information of non-header blocks inside the loop, except
418 // members of inner nested loops because those should already have been
419 // updated by their own LoopInformation.
420 if (block->GetLoopInformation() == this && block != header_) {
421 block->SetLoopInformation(nullptr);
422 }
423 }
424 blocks_.ClearAllBits();
425
426 if (back_edges_.IsEmpty()) {
427 // The loop has been dismantled, delete its suspend check and remove info
428 // from the header.
429 DCHECK(HasSuspendCheck());
430 header_->RemoveInstruction(suspend_check_);
431 header_->SetLoopInformation(nullptr);
432 header_ = nullptr;
433 suspend_check_ = nullptr;
434 } else {
435 if (kIsDebugBuild) {
436 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
437 DCHECK(header_->Dominates(back_edges_.Get(i)));
438 }
439 }
440 // This loop still has reachable back edges. Repopulate the list of blocks.
441 bool populate_successful = Populate();
442 DCHECK(populate_successful);
443 }
444}
445
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100446HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100447 return header_->GetDominator();
448}
449
450bool HLoopInformation::Contains(const HBasicBlock& block) const {
451 return blocks_.IsBitSet(block.GetBlockId());
452}
453
454bool HLoopInformation::IsIn(const HLoopInformation& other) const {
455 return other.blocks_.IsBitSet(header_->GetBlockId());
456}
457
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100458size_t HLoopInformation::GetLifetimeEnd() const {
459 size_t last_position = 0;
460 for (size_t i = 0, e = back_edges_.Size(); i < e; ++i) {
461 last_position = std::max(back_edges_.Get(i)->GetLifetimeEnd(), last_position);
462 }
463 return last_position;
464}
465
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100466bool HBasicBlock::Dominates(HBasicBlock* other) const {
467 // Walk up the dominator tree from `other`, to find out if `this`
468 // is an ancestor.
469 HBasicBlock* current = other;
470 while (current != nullptr) {
471 if (current == this) {
472 return true;
473 }
474 current = current->GetDominator();
475 }
476 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100477}
478
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100479static void UpdateInputsUsers(HInstruction* instruction) {
480 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
481 instruction->InputAt(i)->AddUseAt(instruction, i);
482 }
483 // Environment should be created later.
484 DCHECK(!instruction->HasEnvironment());
485}
486
Roland Levillainccc07a92014-09-16 14:48:16 +0100487void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
488 HInstruction* replacement) {
489 DCHECK(initial->GetBlock() == this);
490 InsertInstructionBefore(replacement, initial);
491 initial->ReplaceWith(replacement);
492 RemoveInstruction(initial);
493}
494
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100495static void Add(HInstructionList* instruction_list,
496 HBasicBlock* block,
497 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000498 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000499 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100500 instruction->SetBlock(block);
501 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100502 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100503 instruction_list->AddInstruction(instruction);
504}
505
506void HBasicBlock::AddInstruction(HInstruction* instruction) {
507 Add(&instructions_, this, instruction);
508}
509
510void HBasicBlock::AddPhi(HPhi* phi) {
511 Add(&phis_, this, phi);
512}
513
David Brazdilc3d743f2015-04-22 13:40:50 +0100514void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
515 DCHECK(!cursor->IsPhi());
516 DCHECK(!instruction->IsPhi());
517 DCHECK_EQ(instruction->GetId(), -1);
518 DCHECK_NE(cursor->GetId(), -1);
519 DCHECK_EQ(cursor->GetBlock(), this);
520 DCHECK(!instruction->IsControlFlow());
521 instruction->SetBlock(this);
522 instruction->SetId(GetGraph()->GetNextInstructionId());
523 UpdateInputsUsers(instruction);
524 instructions_.InsertInstructionBefore(instruction, cursor);
525}
526
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100527void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
528 DCHECK(!cursor->IsPhi());
529 DCHECK(!instruction->IsPhi());
530 DCHECK_EQ(instruction->GetId(), -1);
531 DCHECK_NE(cursor->GetId(), -1);
532 DCHECK_EQ(cursor->GetBlock(), this);
533 DCHECK(!instruction->IsControlFlow());
534 DCHECK(!cursor->IsControlFlow());
535 instruction->SetBlock(this);
536 instruction->SetId(GetGraph()->GetNextInstructionId());
537 UpdateInputsUsers(instruction);
538 instructions_.InsertInstructionAfter(instruction, cursor);
539}
540
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100541void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
542 DCHECK_EQ(phi->GetId(), -1);
543 DCHECK_NE(cursor->GetId(), -1);
544 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100545 phi->SetBlock(this);
546 phi->SetId(GetGraph()->GetNextInstructionId());
547 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100548 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100549}
550
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100551static void Remove(HInstructionList* instruction_list,
552 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000553 HInstruction* instruction,
554 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100555 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100556 instruction->SetBlock(nullptr);
557 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000558 if (ensure_safety) {
559 DCHECK(instruction->GetUses().IsEmpty());
560 DCHECK(instruction->GetEnvUses().IsEmpty());
561 RemoveAsUser(instruction);
562 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100563}
564
David Brazdil1abb4192015-02-17 18:33:36 +0000565void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100566 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000567 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100568}
569
David Brazdil1abb4192015-02-17 18:33:36 +0000570void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
571 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100572}
573
David Brazdilc7508e92015-04-27 13:28:57 +0100574void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
575 if (instruction->IsPhi()) {
576 RemovePhi(instruction->AsPhi(), ensure_safety);
577 } else {
578 RemoveInstruction(instruction, ensure_safety);
579 }
580}
581
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100582void HEnvironment::CopyFrom(const GrowableArray<HInstruction*>& locals) {
583 for (size_t i = 0; i < locals.Size(); i++) {
584 HInstruction* instruction = locals.Get(i);
585 SetRawEnvAt(i, instruction);
586 if (instruction != nullptr) {
587 instruction->AddEnvUseAt(this, i);
588 }
589 }
590}
591
David Brazdiled596192015-01-23 10:39:45 +0000592void HEnvironment::CopyFrom(HEnvironment* env) {
593 for (size_t i = 0; i < env->Size(); i++) {
594 HInstruction* instruction = env->GetInstructionAt(i);
595 SetRawEnvAt(i, instruction);
596 if (instruction != nullptr) {
597 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100598 }
David Brazdiled596192015-01-23 10:39:45 +0000599 }
600}
601
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700602void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
603 HBasicBlock* loop_header) {
604 DCHECK(loop_header->IsLoopHeader());
605 for (size_t i = 0; i < env->Size(); i++) {
606 HInstruction* instruction = env->GetInstructionAt(i);
607 SetRawEnvAt(i, instruction);
608 if (instruction == nullptr) {
609 continue;
610 }
611 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
612 // At the end of the loop pre-header, the corresponding value for instruction
613 // is the first input of the phi.
614 HInstruction* initial = instruction->AsPhi()->InputAt(0);
615 DCHECK(initial->GetBlock()->Dominates(loop_header));
616 SetRawEnvAt(i, initial);
617 initial->AddEnvUseAt(this, i);
618 } else {
619 instruction->AddEnvUseAt(this, i);
620 }
621 }
622}
623
David Brazdil1abb4192015-02-17 18:33:36 +0000624void HEnvironment::RemoveAsUserOfInput(size_t index) const {
625 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
626 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100627}
628
Calin Juravle77520bc2015-01-12 18:45:46 +0000629HInstruction* HInstruction::GetNextDisregardingMoves() const {
630 HInstruction* next = GetNext();
631 while (next != nullptr && next->IsParallelMove()) {
632 next = next->GetNext();
633 }
634 return next;
635}
636
637HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
638 HInstruction* previous = GetPrevious();
639 while (previous != nullptr && previous->IsParallelMove()) {
640 previous = previous->GetPrevious();
641 }
642 return previous;
643}
644
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100645void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000646 if (first_instruction_ == nullptr) {
647 DCHECK(last_instruction_ == nullptr);
648 first_instruction_ = last_instruction_ = instruction;
649 } else {
650 last_instruction_->next_ = instruction;
651 instruction->previous_ = last_instruction_;
652 last_instruction_ = instruction;
653 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000654}
655
David Brazdilc3d743f2015-04-22 13:40:50 +0100656void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
657 DCHECK(Contains(cursor));
658 if (cursor == first_instruction_) {
659 cursor->previous_ = instruction;
660 instruction->next_ = cursor;
661 first_instruction_ = instruction;
662 } else {
663 instruction->previous_ = cursor->previous_;
664 instruction->next_ = cursor;
665 cursor->previous_ = instruction;
666 instruction->previous_->next_ = instruction;
667 }
668}
669
670void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
671 DCHECK(Contains(cursor));
672 if (cursor == last_instruction_) {
673 cursor->next_ = instruction;
674 instruction->previous_ = cursor;
675 last_instruction_ = instruction;
676 } else {
677 instruction->next_ = cursor->next_;
678 instruction->previous_ = cursor;
679 cursor->next_ = instruction;
680 instruction->next_->previous_ = instruction;
681 }
682}
683
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100684void HInstructionList::RemoveInstruction(HInstruction* instruction) {
685 if (instruction->previous_ != nullptr) {
686 instruction->previous_->next_ = instruction->next_;
687 }
688 if (instruction->next_ != nullptr) {
689 instruction->next_->previous_ = instruction->previous_;
690 }
691 if (instruction == first_instruction_) {
692 first_instruction_ = instruction->next_;
693 }
694 if (instruction == last_instruction_) {
695 last_instruction_ = instruction->previous_;
696 }
697}
698
Roland Levillain6b469232014-09-25 10:10:38 +0100699bool HInstructionList::Contains(HInstruction* instruction) const {
700 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
701 if (it.Current() == instruction) {
702 return true;
703 }
704 }
705 return false;
706}
707
Roland Levillainccc07a92014-09-16 14:48:16 +0100708bool HInstructionList::FoundBefore(const HInstruction* instruction1,
709 const HInstruction* instruction2) const {
710 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
711 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
712 if (it.Current() == instruction1) {
713 return true;
714 }
715 if (it.Current() == instruction2) {
716 return false;
717 }
718 }
719 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
720 return true;
721}
722
Roland Levillain6c82d402014-10-13 16:10:27 +0100723bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
724 if (other_instruction == this) {
725 // An instruction does not strictly dominate itself.
726 return false;
727 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100728 HBasicBlock* block = GetBlock();
729 HBasicBlock* other_block = other_instruction->GetBlock();
730 if (block != other_block) {
731 return GetBlock()->Dominates(other_instruction->GetBlock());
732 } else {
733 // If both instructions are in the same block, ensure this
734 // instruction comes before `other_instruction`.
735 if (IsPhi()) {
736 if (!other_instruction->IsPhi()) {
737 // Phis appear before non phi-instructions so this instruction
738 // dominates `other_instruction`.
739 return true;
740 } else {
741 // There is no order among phis.
742 LOG(FATAL) << "There is no dominance between phis of a same block.";
743 return false;
744 }
745 } else {
746 // `this` is not a phi.
747 if (other_instruction->IsPhi()) {
748 // Phis appear before non phi-instructions so this instruction
749 // does not dominate `other_instruction`.
750 return false;
751 } else {
752 // Check whether this instruction comes before
753 // `other_instruction` in the instruction list.
754 return block->GetInstructions().FoundBefore(this, other_instruction);
755 }
756 }
757 }
758}
759
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100760void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100761 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000762 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
763 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100764 HInstruction* user = current->GetUser();
765 size_t input_index = current->GetIndex();
766 user->SetRawInputAt(input_index, other);
767 other->AddUseAt(user, input_index);
768 }
769
David Brazdiled596192015-01-23 10:39:45 +0000770 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
771 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100772 HEnvironment* user = current->GetUser();
773 size_t input_index = current->GetIndex();
774 user->SetRawEnvAt(input_index, other);
775 other->AddEnvUseAt(user, input_index);
776 }
777
David Brazdiled596192015-01-23 10:39:45 +0000778 uses_.Clear();
779 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100780}
781
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100782void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000783 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100784 SetRawInputAt(index, replacement);
785 replacement->AddUseAt(this, index);
786}
787
Nicolas Geoffray39468442014-09-02 15:17:15 +0100788size_t HInstruction::EnvironmentSize() const {
789 return HasEnvironment() ? environment_->Size() : 0;
790}
791
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100792void HPhi::AddInput(HInstruction* input) {
793 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000794 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100795 input->AddUseAt(this, inputs_.Size() - 1);
796}
797
David Brazdil2d7352b2015-04-20 14:52:42 +0100798void HPhi::RemoveInputAt(size_t index) {
799 RemoveAsUserOfInput(index);
800 inputs_.DeleteAt(index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +0100801 for (size_t i = index, e = InputCount(); i < e; ++i) {
802 InputRecordAt(i).GetUseNode()->SetIndex(i);
803 }
David Brazdil2d7352b2015-04-20 14:52:42 +0100804}
805
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100806#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000807void H##name::Accept(HGraphVisitor* visitor) { \
808 visitor->Visit##name(this); \
809}
810
811FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
812
813#undef DEFINE_ACCEPT
814
815void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100816 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
817 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000818 HBasicBlock* block = blocks.Get(i);
819 if (block != nullptr) {
820 VisitBasicBlock(block);
821 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000822 }
823}
824
Roland Levillain633021e2014-10-01 14:12:25 +0100825void HGraphVisitor::VisitReversePostOrder() {
826 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
827 VisitBasicBlock(it.Current());
828 }
829}
830
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000831void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100832 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100833 it.Current()->Accept(this);
834 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100835 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000836 it.Current()->Accept(this);
837 }
838}
839
Mark Mendelle82549b2015-05-06 10:55:34 -0400840HConstant* HTypeConversion::TryStaticEvaluation() const {
841 HGraph* graph = GetBlock()->GetGraph();
842 if (GetInput()->IsIntConstant()) {
843 int32_t value = GetInput()->AsIntConstant()->GetValue();
844 switch (GetResultType()) {
845 case Primitive::kPrimLong:
846 return graph->GetLongConstant(static_cast<int64_t>(value));
847 case Primitive::kPrimFloat:
848 return graph->GetFloatConstant(static_cast<float>(value));
849 case Primitive::kPrimDouble:
850 return graph->GetDoubleConstant(static_cast<double>(value));
851 default:
852 return nullptr;
853 }
854 } else if (GetInput()->IsLongConstant()) {
855 int64_t value = GetInput()->AsLongConstant()->GetValue();
856 switch (GetResultType()) {
857 case Primitive::kPrimInt:
858 return graph->GetIntConstant(static_cast<int32_t>(value));
859 case Primitive::kPrimFloat:
860 return graph->GetFloatConstant(static_cast<float>(value));
861 case Primitive::kPrimDouble:
862 return graph->GetDoubleConstant(static_cast<double>(value));
863 default:
864 return nullptr;
865 }
866 } else if (GetInput()->IsFloatConstant()) {
867 float value = GetInput()->AsFloatConstant()->GetValue();
868 switch (GetResultType()) {
869 case Primitive::kPrimInt:
870 if (std::isnan(value))
871 return graph->GetIntConstant(0);
872 if (value >= kPrimIntMax)
873 return graph->GetIntConstant(kPrimIntMax);
874 if (value <= kPrimIntMin)
875 return graph->GetIntConstant(kPrimIntMin);
876 return graph->GetIntConstant(static_cast<int32_t>(value));
877 case Primitive::kPrimLong:
878 if (std::isnan(value))
879 return graph->GetLongConstant(0);
880 if (value >= kPrimLongMax)
881 return graph->GetLongConstant(kPrimLongMax);
882 if (value <= kPrimLongMin)
883 return graph->GetLongConstant(kPrimLongMin);
884 return graph->GetLongConstant(static_cast<int64_t>(value));
885 case Primitive::kPrimDouble:
886 return graph->GetDoubleConstant(static_cast<double>(value));
887 default:
888 return nullptr;
889 }
890 } else if (GetInput()->IsDoubleConstant()) {
891 double value = GetInput()->AsDoubleConstant()->GetValue();
892 switch (GetResultType()) {
893 case Primitive::kPrimInt:
894 if (std::isnan(value))
895 return graph->GetIntConstant(0);
896 if (value >= kPrimIntMax)
897 return graph->GetIntConstant(kPrimIntMax);
898 if (value <= kPrimLongMin)
899 return graph->GetIntConstant(kPrimIntMin);
900 return graph->GetIntConstant(static_cast<int32_t>(value));
901 case Primitive::kPrimLong:
902 if (std::isnan(value))
903 return graph->GetLongConstant(0);
904 if (value >= kPrimLongMax)
905 return graph->GetLongConstant(kPrimLongMax);
906 if (value <= kPrimLongMin)
907 return graph->GetLongConstant(kPrimLongMin);
908 return graph->GetLongConstant(static_cast<int64_t>(value));
909 case Primitive::kPrimFloat:
910 return graph->GetFloatConstant(static_cast<float>(value));
911 default:
912 return nullptr;
913 }
914 }
915 return nullptr;
916}
917
Roland Levillain9240d6a2014-10-20 16:47:04 +0100918HConstant* HUnaryOperation::TryStaticEvaluation() const {
919 if (GetInput()->IsIntConstant()) {
920 int32_t value = Evaluate(GetInput()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000921 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain9240d6a2014-10-20 16:47:04 +0100922 } else if (GetInput()->IsLongConstant()) {
Roland Levillainb762d2e2014-10-22 10:11:06 +0100923 // TODO: Implement static evaluation of long unary operations.
924 //
925 // Do not exit with a fatal condition here. Instead, simply
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700926 // return `null' to notify the caller that this instruction
Roland Levillainb762d2e2014-10-22 10:11:06 +0100927 // cannot (yet) be statically evaluated.
Roland Levillain9240d6a2014-10-20 16:47:04 +0100928 return nullptr;
929 }
930 return nullptr;
931}
932
933HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain556c3d12014-09-18 15:25:07 +0100934 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
935 int32_t value = Evaluate(GetLeft()->AsIntConstant()->GetValue(),
936 GetRight()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000937 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain556c3d12014-09-18 15:25:07 +0100938 } else if (GetLeft()->IsLongConstant() && GetRight()->IsLongConstant()) {
939 int64_t value = Evaluate(GetLeft()->AsLongConstant()->GetValue(),
940 GetRight()->AsLongConstant()->GetValue());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000941 if (GetResultType() == Primitive::kPrimLong) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000942 return GetBlock()->GetGraph()->GetLongConstant(value);
Mark Mendellc4701932015-04-10 13:18:51 -0400943 } else if (GetResultType() == Primitive::kPrimBoolean) {
944 // This can be the result of an HCondition evaluation.
945 return GetBlock()->GetGraph()->GetIntConstant(static_cast<int32_t>(value));
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000946 } else {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000947 DCHECK_EQ(GetResultType(), Primitive::kPrimInt);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000948 return GetBlock()->GetGraph()->GetIntConstant(static_cast<int32_t>(value));
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000949 }
Roland Levillain556c3d12014-09-18 15:25:07 +0100950 }
951 return nullptr;
952}
Dave Allison20dfc792014-06-16 20:44:29 -0700953
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000954HConstant* HBinaryOperation::GetConstantRight() const {
955 if (GetRight()->IsConstant()) {
956 return GetRight()->AsConstant();
957 } else if (IsCommutative() && GetLeft()->IsConstant()) {
958 return GetLeft()->AsConstant();
959 } else {
960 return nullptr;
961 }
962}
963
964// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700965// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000966HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
967 HInstruction* most_constant_right = GetConstantRight();
968 if (most_constant_right == nullptr) {
969 return nullptr;
970 } else if (most_constant_right == GetLeft()) {
971 return GetRight();
972 } else {
973 return GetLeft();
974 }
975}
976
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700977bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
978 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100979}
980
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100981bool HInstruction::Equals(HInstruction* other) const {
982 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100983 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100984 if (!InstructionDataEquals(other)) return false;
985 if (GetType() != other->GetType()) return false;
986 if (InputCount() != other->InputCount()) return false;
987
988 for (size_t i = 0, e = InputCount(); i < e; ++i) {
989 if (InputAt(i) != other->InputAt(i)) return false;
990 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100991 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100992 return true;
993}
994
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700995std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
996#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
997 switch (rhs) {
998 FOR_EACH_INSTRUCTION(DECLARE_CASE)
999 default:
1000 os << "Unknown instruction kind " << static_cast<int>(rhs);
1001 break;
1002 }
1003#undef DECLARE_CASE
1004 return os;
1005}
1006
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001007void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001008 next_->previous_ = previous_;
1009 if (previous_ != nullptr) {
1010 previous_->next_ = next_;
1011 }
1012 if (block_->instructions_.first_instruction_ == this) {
1013 block_->instructions_.first_instruction_ = next_;
1014 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001015 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001016
1017 previous_ = cursor->previous_;
1018 if (previous_ != nullptr) {
1019 previous_->next_ = this;
1020 }
1021 next_ = cursor;
1022 cursor->previous_ = this;
1023 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001024
1025 if (block_->instructions_.first_instruction_ == cursor) {
1026 block_->instructions_.first_instruction_ = this;
1027 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001028}
1029
David Brazdilfc6a86a2015-06-26 10:33:45 +00001030HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
1031 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented";
1032 DCHECK_EQ(cursor->GetBlock(), this);
1033
1034 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1035 new_block->instructions_.first_instruction_ = cursor;
1036 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1037 instructions_.last_instruction_ = cursor->previous_;
1038 if (cursor->previous_ == nullptr) {
1039 instructions_.first_instruction_ = nullptr;
1040 } else {
1041 cursor->previous_->next_ = nullptr;
1042 cursor->previous_ = nullptr;
1043 }
1044
1045 new_block->instructions_.SetBlockOfInstructions(new_block);
1046 AddInstruction(new (GetGraph()->GetArena()) HGoto());
1047
1048 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
1049 HBasicBlock* successor = GetSuccessors().Get(i);
1050 new_block->successors_.Add(successor);
1051 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
1052 }
1053 successors_.Reset();
1054 AddSuccessor(new_block);
1055
David Brazdil56e1acc2015-06-30 15:41:36 +01001056 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001057 return new_block;
1058}
1059
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001060HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1061 DCHECK(!cursor->IsControlFlow());
1062 DCHECK_NE(instructions_.last_instruction_, cursor);
1063 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001064
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001065 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1066 new_block->instructions_.first_instruction_ = cursor->GetNext();
1067 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1068 cursor->next_->previous_ = nullptr;
1069 cursor->next_ = nullptr;
1070 instructions_.last_instruction_ = cursor;
1071
1072 new_block->instructions_.SetBlockOfInstructions(new_block);
1073 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
1074 HBasicBlock* successor = GetSuccessors().Get(i);
1075 new_block->successors_.Add(successor);
1076 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
1077 }
1078 successors_.Reset();
1079
1080 for (size_t i = 0, e = GetDominatedBlocks().Size(); i < e; ++i) {
1081 HBasicBlock* dominated = GetDominatedBlocks().Get(i);
1082 dominated->dominator_ = new_block;
1083 new_block->dominated_blocks_.Add(dominated);
1084 }
1085 dominated_blocks_.Reset();
1086 return new_block;
1087}
1088
David Brazdilfc6a86a2015-06-26 10:33:45 +00001089bool HBasicBlock::IsExceptionalSuccessor(size_t idx) const {
1090 return !GetInstructions().IsEmpty()
1091 && GetLastInstruction()->IsTryBoundary()
1092 && GetLastInstruction()->AsTryBoundary()->IsExceptionalSuccessor(idx);
1093}
1094
1095static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1096 return block.GetPhis().IsEmpty()
1097 && !block.GetInstructions().IsEmpty()
1098 && block.GetFirstInstruction() == block.GetLastInstruction();
1099}
1100
David Brazdil46e2a392015-03-16 17:31:52 +00001101bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001102 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1103}
1104
1105bool HBasicBlock::IsSingleTryBoundary() const {
1106 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001107}
1108
David Brazdil8d5b8b22015-03-24 10:51:52 +00001109bool HBasicBlock::EndsWithControlFlowInstruction() const {
1110 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1111}
1112
David Brazdilb2bd1c52015-03-25 11:17:37 +00001113bool HBasicBlock::EndsWithIf() const {
1114 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1115}
1116
1117bool HBasicBlock::HasSinglePhi() const {
1118 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1119}
1120
David Brazdil2d7352b2015-04-20 14:52:42 +01001121size_t HInstructionList::CountSize() const {
1122 size_t size = 0;
1123 HInstruction* current = first_instruction_;
1124 for (; current != nullptr; current = current->GetNext()) {
1125 size++;
1126 }
1127 return size;
1128}
1129
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001130void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1131 for (HInstruction* current = first_instruction_;
1132 current != nullptr;
1133 current = current->GetNext()) {
1134 current->SetBlock(block);
1135 }
1136}
1137
1138void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1139 DCHECK(Contains(cursor));
1140 if (!instruction_list.IsEmpty()) {
1141 if (cursor == last_instruction_) {
1142 last_instruction_ = instruction_list.last_instruction_;
1143 } else {
1144 cursor->next_->previous_ = instruction_list.last_instruction_;
1145 }
1146 instruction_list.last_instruction_->next_ = cursor->next_;
1147 cursor->next_ = instruction_list.first_instruction_;
1148 instruction_list.first_instruction_->previous_ = cursor;
1149 }
1150}
1151
1152void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001153 if (IsEmpty()) {
1154 first_instruction_ = instruction_list.first_instruction_;
1155 last_instruction_ = instruction_list.last_instruction_;
1156 } else {
1157 AddAfter(last_instruction_, instruction_list);
1158 }
1159}
1160
David Brazdil2d7352b2015-04-20 14:52:42 +01001161void HBasicBlock::DisconnectAndDelete() {
1162 // Dominators must be removed after all the blocks they dominate. This way
1163 // a loop header is removed last, a requirement for correct loop information
1164 // iteration.
1165 DCHECK(dominated_blocks_.IsEmpty());
David Brazdil46e2a392015-03-16 17:31:52 +00001166
David Brazdil2d7352b2015-04-20 14:52:42 +01001167 // Remove the block from all loops it is included in.
1168 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1169 HLoopInformation* loop_info = it.Current();
1170 loop_info->Remove(this);
1171 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001172 // If this was the last back edge of the loop, we deliberately leave the
1173 // loop in an inconsistent state and will fail SSAChecker unless the
1174 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001175 loop_info->RemoveBackEdge(this);
1176 }
1177 }
1178
1179 // Disconnect the block from its predecessors and update their control-flow
1180 // instructions.
David Brazdil46e2a392015-03-16 17:31:52 +00001181 for (size_t i = 0, e = predecessors_.Size(); i < e; ++i) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001182 HBasicBlock* predecessor = predecessors_.Get(i);
1183 HInstruction* last_instruction = predecessor->GetLastInstruction();
1184 predecessor->RemoveInstruction(last_instruction);
1185 predecessor->RemoveSuccessor(this);
1186 if (predecessor->GetSuccessors().Size() == 1u) {
1187 DCHECK(last_instruction->IsIf());
1188 predecessor->AddInstruction(new (graph_->GetArena()) HGoto());
1189 } else {
1190 // The predecessor has no remaining successors and therefore must be dead.
1191 // We deliberately leave it without a control-flow instruction so that the
1192 // SSAChecker fails unless it is not removed during the pass too.
1193 DCHECK_EQ(predecessor->GetSuccessors().Size(), 0u);
1194 }
David Brazdil46e2a392015-03-16 17:31:52 +00001195 }
David Brazdil46e2a392015-03-16 17:31:52 +00001196 predecessors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +01001197
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +01001198 // Disconnect the block from its successors and update their phis.
David Brazdil2d7352b2015-04-20 14:52:42 +01001199 for (size_t i = 0, e = successors_.Size(); i < e; ++i) {
1200 HBasicBlock* successor = successors_.Get(i);
1201 // Delete this block from the list of predecessors.
1202 size_t this_index = successor->GetPredecessorIndexOf(this);
1203 successor->predecessors_.DeleteAt(this_index);
1204
1205 // Check that `successor` has other predecessors, otherwise `this` is the
1206 // dominator of `successor` which violates the order DCHECKed at the top.
1207 DCHECK(!successor->predecessors_.IsEmpty());
1208
David Brazdil2d7352b2015-04-20 14:52:42 +01001209 // Remove this block's entries in the successor's phis.
1210 if (successor->predecessors_.Size() == 1u) {
1211 // The successor has just one predecessor left. Replace phis with the only
1212 // remaining input.
1213 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1214 HPhi* phi = phi_it.Current()->AsPhi();
1215 phi->ReplaceWith(phi->InputAt(1 - this_index));
1216 successor->RemovePhi(phi);
1217 }
1218 } else {
1219 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1220 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1221 }
1222 }
1223 }
David Brazdil46e2a392015-03-16 17:31:52 +00001224 successors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +01001225
1226 // Disconnect from the dominator.
1227 dominator_->RemoveDominatedBlock(this);
1228 SetDominator(nullptr);
1229
1230 // Delete from the graph. The function safely deletes remaining instructions
1231 // and updates the reverse post order.
1232 graph_->DeleteDeadBlock(this);
1233 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001234}
1235
1236void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001237 DCHECK_EQ(GetGraph(), other->GetGraph());
1238 DCHECK(GetDominatedBlocks().Contains(other));
1239 DCHECK_EQ(GetSuccessors().Size(), 1u);
1240 DCHECK_EQ(GetSuccessors().Get(0), other);
1241 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1242 DCHECK_EQ(other->GetPredecessors().Get(0), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001243 DCHECK(other->GetPhis().IsEmpty());
1244
David Brazdil2d7352b2015-04-20 14:52:42 +01001245 // Move instructions from `other` to `this`.
1246 DCHECK(EndsWithControlFlowInstruction());
1247 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001248 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001249 other->instructions_.SetBlockOfInstructions(this);
1250 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001251
David Brazdil2d7352b2015-04-20 14:52:42 +01001252 // Remove `other` from the loops it is included in.
1253 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1254 HLoopInformation* loop_info = it.Current();
1255 loop_info->Remove(other);
1256 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001257 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001258 }
1259 }
1260
1261 // Update links to the successors of `other`.
1262 successors_.Reset();
1263 while (!other->successors_.IsEmpty()) {
1264 HBasicBlock* successor = other->successors_.Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001265 successor->ReplacePredecessor(other, this);
1266 }
1267
David Brazdil2d7352b2015-04-20 14:52:42 +01001268 // Update the dominator tree.
1269 dominated_blocks_.Delete(other);
1270 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1271 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1272 dominated_blocks_.Add(dominated);
1273 dominated->SetDominator(this);
1274 }
1275 other->dominated_blocks_.Reset();
1276 other->dominator_ = nullptr;
1277
1278 // Clear the list of predecessors of `other` in preparation of deleting it.
1279 other->predecessors_.Reset();
1280
1281 // Delete `other` from the graph. The function updates reverse post order.
1282 graph_->DeleteDeadBlock(other);
1283 other->SetGraph(nullptr);
1284}
1285
1286void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1287 DCHECK_NE(GetGraph(), other->GetGraph());
1288 DCHECK(GetDominatedBlocks().IsEmpty());
1289 DCHECK(GetSuccessors().IsEmpty());
1290 DCHECK(!EndsWithControlFlowInstruction());
1291 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1292 DCHECK(other->GetPredecessors().Get(0)->IsEntryBlock());
1293 DCHECK(other->GetPhis().IsEmpty());
1294 DCHECK(!other->IsInLoop());
1295
1296 // Move instructions from `other` to `this`.
1297 instructions_.Add(other->GetInstructions());
1298 other->instructions_.SetBlockOfInstructions(this);
1299
1300 // Update links to the successors of `other`.
1301 successors_.Reset();
1302 while (!other->successors_.IsEmpty()) {
1303 HBasicBlock* successor = other->successors_.Get(0);
1304 successor->ReplacePredecessor(other, this);
1305 }
1306
1307 // Update the dominator tree.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001308 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1309 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1310 dominated_blocks_.Add(dominated);
1311 dominated->SetDominator(this);
1312 }
1313 other->dominated_blocks_.Reset();
1314 other->dominator_ = nullptr;
1315 other->graph_ = nullptr;
1316}
1317
1318void HBasicBlock::ReplaceWith(HBasicBlock* other) {
1319 while (!GetPredecessors().IsEmpty()) {
1320 HBasicBlock* predecessor = GetPredecessors().Get(0);
1321 predecessor->ReplaceSuccessor(this, other);
1322 }
1323 while (!GetSuccessors().IsEmpty()) {
1324 HBasicBlock* successor = GetSuccessors().Get(0);
1325 successor->ReplacePredecessor(this, other);
1326 }
1327 for (size_t i = 0; i < dominated_blocks_.Size(); ++i) {
1328 other->AddDominatedBlock(dominated_blocks_.Get(i));
1329 }
1330 GetDominator()->ReplaceDominatedBlock(this, other);
1331 other->SetDominator(GetDominator());
1332 dominator_ = nullptr;
1333 graph_ = nullptr;
1334}
1335
1336// Create space in `blocks` for adding `number_of_new_blocks` entries
1337// starting at location `at`. Blocks after `at` are moved accordingly.
1338static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
1339 size_t number_of_new_blocks,
1340 size_t at) {
1341 size_t old_size = blocks->Size();
1342 size_t new_size = old_size + number_of_new_blocks;
1343 blocks->SetSize(new_size);
1344 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
1345 blocks->Put(j, blocks->Get(i));
1346 }
1347}
1348
David Brazdil2d7352b2015-04-20 14:52:42 +01001349void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1350 DCHECK_EQ(block->GetGraph(), this);
1351 DCHECK(block->GetSuccessors().IsEmpty());
1352 DCHECK(block->GetPredecessors().IsEmpty());
1353 DCHECK(block->GetDominatedBlocks().IsEmpty());
1354 DCHECK(block->GetDominator() == nullptr);
1355
1356 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1357 block->RemoveInstruction(it.Current());
1358 }
1359 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1360 block->RemovePhi(it.Current()->AsPhi());
1361 }
1362
David Brazdilc7af85d2015-05-26 12:05:55 +01001363 if (block->IsExitBlock()) {
1364 exit_block_ = nullptr;
1365 }
1366
David Brazdil2d7352b2015-04-20 14:52:42 +01001367 reverse_post_order_.Delete(block);
1368 blocks_.Put(block->GetBlockId(), nullptr);
1369}
1370
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001371void HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001372 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001373 // Update the environments in this graph to have the invoke's environment
1374 // as parent.
1375 {
1376 HReversePostOrderIterator it(*this);
1377 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1378 for (; !it.Done(); it.Advance()) {
1379 HBasicBlock* block = it.Current();
1380 for (HInstructionIterator instr_it(block->GetInstructions());
1381 !instr_it.Done();
1382 instr_it.Advance()) {
1383 HInstruction* current = instr_it.Current();
1384 if (current->NeedsEnvironment()) {
1385 current->GetEnvironment()->SetAndCopyParentChain(
1386 outer_graph->GetArena(), invoke->GetEnvironment());
1387 }
1388 }
1389 }
1390 }
1391 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1392 if (HasBoundsChecks()) {
1393 outer_graph->SetHasBoundsChecks(true);
1394 }
1395
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001396 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001397 // Simple case of an entry block, a body block, and an exit block.
1398 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001399 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001400 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
1401 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001402 DCHECK(!body->IsExitBlock());
1403 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001404
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001405 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1406 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001407
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001408 // Replace the invoke with the return value of the inlined graph.
1409 if (last->IsReturn()) {
1410 invoke->ReplaceWith(last->InputAt(0));
1411 } else {
1412 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001413 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001414
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001415 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001416 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001417 // Need to inline multiple blocks. We split `invoke`'s block
1418 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001419 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001420 // with the second half.
1421 ArenaAllocator* allocator = outer_graph->GetArena();
1422 HBasicBlock* at = invoke->GetBlock();
1423 HBasicBlock* to = at->SplitAfter(invoke);
1424
1425 HBasicBlock* first = entry_block_->GetSuccessors().Get(0);
1426 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001427 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001428 exit_block_->ReplaceWith(to);
1429
1430 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001431 // to not `HReturn` but `HGoto` instead.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001432 HInstruction* return_value = nullptr;
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001433 bool returns_void = to->GetPredecessors().Get(0)->GetLastInstruction()->IsReturnVoid();
1434 if (to->GetPredecessors().Size() == 1) {
1435 HBasicBlock* predecessor = to->GetPredecessors().Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001436 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001437 if (!returns_void) {
1438 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001439 }
1440 predecessor->AddInstruction(new (allocator) HGoto());
1441 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001442 } else {
1443 if (!returns_void) {
1444 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001445 return_value = new (allocator) HPhi(
1446 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001447 to->AddPhi(return_value->AsPhi());
1448 }
1449 for (size_t i = 0, e = to->GetPredecessors().Size(); i < e; ++i) {
1450 HBasicBlock* predecessor = to->GetPredecessors().Get(i);
1451 HInstruction* last = predecessor->GetLastInstruction();
1452 if (!returns_void) {
1453 return_value->AsPhi()->AddInput(last->InputAt(0));
1454 }
1455 predecessor->AddInstruction(new (allocator) HGoto());
1456 predecessor->RemoveInstruction(last);
1457 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001458 }
1459
1460 if (return_value != nullptr) {
1461 invoke->ReplaceWith(return_value);
1462 }
1463
1464 // Update the meta information surrounding blocks:
1465 // (1) the graph they are now in,
1466 // (2) the reverse post order of that graph,
1467 // (3) the potential loop information they are now in.
1468
1469 // We don't add the entry block, the exit block, and the first block, which
1470 // has been merged with `at`.
1471 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1472
1473 // We add the `to` block.
1474 static constexpr int kNumberOfNewBlocksInCaller = 1;
1475 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1476 + kNumberOfNewBlocksInCaller;
1477
1478 // Find the location of `at` in the outer graph's reverse post order. The new
1479 // blocks will be added after it.
1480 size_t index_of_at = 0;
1481 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1482 index_of_at++;
1483 }
1484 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1485
1486 // Do a reverse post order of the blocks in the callee and do (1), (2),
1487 // and (3) to the blocks that apply.
1488 HLoopInformation* info = at->GetLoopInformation();
1489 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1490 HBasicBlock* current = it.Current();
1491 if (current != exit_block_ && current != entry_block_ && current != first) {
1492 DCHECK(!current->IsInLoop());
1493 DCHECK(current->GetGraph() == this);
1494 current->SetGraph(outer_graph);
1495 outer_graph->AddBlock(current);
1496 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1497 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001498 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001499 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1500 loop_it.Current()->Add(current);
1501 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001502 }
1503 }
1504 }
1505
1506 // Do (1), (2), and (3) to `to`.
1507 to->SetGraph(outer_graph);
1508 outer_graph->AddBlock(to);
1509 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1510 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001511 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001512 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1513 loop_it.Current()->Add(to);
1514 }
David Brazdil46e2a392015-03-16 17:31:52 +00001515 if (info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001516 // Only `to` can become a back edge, as the inlined blocks
1517 // are predecessors of `to`.
1518 info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001519 }
1520 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001521 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001522
David Brazdil05144f42015-04-16 15:18:00 +01001523 // Update the next instruction id of the outer graph, so that instructions
1524 // added later get bigger ids than those in the inner graph.
1525 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1526
1527 // Walk over the entry block and:
1528 // - Move constants from the entry block to the outer_graph's entry block,
1529 // - Replace HParameterValue instructions with their real value.
1530 // - Remove suspend checks, that hold an environment.
1531 // We must do this after the other blocks have been inlined, otherwise ids of
1532 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001533 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001534 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1535 HInstruction* current = it.Current();
1536 if (current->IsNullConstant()) {
1537 current->ReplaceWith(outer_graph->GetNullConstant());
1538 } else if (current->IsIntConstant()) {
1539 current->ReplaceWith(outer_graph->GetIntConstant(current->AsIntConstant()->GetValue()));
1540 } else if (current->IsLongConstant()) {
1541 current->ReplaceWith(outer_graph->GetLongConstant(current->AsLongConstant()->GetValue()));
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00001542 } else if (current->IsFloatConstant()) {
1543 current->ReplaceWith(outer_graph->GetFloatConstant(current->AsFloatConstant()->GetValue()));
1544 } else if (current->IsDoubleConstant()) {
1545 current->ReplaceWith(outer_graph->GetDoubleConstant(current->AsDoubleConstant()->GetValue()));
David Brazdil05144f42015-04-16 15:18:00 +01001546 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001547 if (kIsDebugBuild
1548 && invoke->IsInvokeStaticOrDirect()
1549 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1550 // Ensure we do not use the last input of `invoke`, as it
1551 // contains a clinit check which is not an actual argument.
1552 size_t last_input_index = invoke->InputCount() - 1;
1553 DCHECK(parameter_index != last_input_index);
1554 }
David Brazdil05144f42015-04-16 15:18:00 +01001555 current->ReplaceWith(invoke->InputAt(parameter_index++));
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01001556 } else if (current->IsCurrentMethod()) {
1557 current->ReplaceWith(outer_graph->GetCurrentMethod());
David Brazdil05144f42015-04-16 15:18:00 +01001558 } else {
1559 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1560 entry_block_->RemoveInstruction(current);
1561 }
1562 }
1563
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001564 // Finally remove the invoke from the caller.
1565 invoke->GetBlock()->RemoveInstruction(invoke);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001566}
1567
Mingyao Yang3584bce2015-05-19 16:01:59 -07001568/*
1569 * Loop will be transformed to:
1570 * old_pre_header
1571 * |
1572 * if_block
1573 * / \
1574 * dummy_block deopt_block
1575 * \ /
1576 * new_pre_header
1577 * |
1578 * header
1579 */
1580void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
1581 DCHECK(header->IsLoopHeader());
1582 HBasicBlock* pre_header = header->GetDominator();
1583
1584 // Need this to avoid critical edge.
1585 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1586 // Need this to avoid critical edge.
1587 HBasicBlock* dummy_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1588 HBasicBlock* deopt_block = new (arena_) HBasicBlock(this, header->GetDexPc());
1589 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
1590 AddBlock(if_block);
1591 AddBlock(dummy_block);
1592 AddBlock(deopt_block);
1593 AddBlock(new_pre_header);
1594
1595 header->ReplacePredecessor(pre_header, new_pre_header);
1596 pre_header->successors_.Reset();
1597 pre_header->dominated_blocks_.Reset();
1598
1599 pre_header->AddSuccessor(if_block);
1600 if_block->AddSuccessor(dummy_block); // True successor
1601 if_block->AddSuccessor(deopt_block); // False successor
1602 dummy_block->AddSuccessor(new_pre_header);
1603 deopt_block->AddSuccessor(new_pre_header);
1604
1605 pre_header->dominated_blocks_.Add(if_block);
1606 if_block->SetDominator(pre_header);
1607 if_block->dominated_blocks_.Add(dummy_block);
1608 dummy_block->SetDominator(if_block);
1609 if_block->dominated_blocks_.Add(deopt_block);
1610 deopt_block->SetDominator(if_block);
1611 if_block->dominated_blocks_.Add(new_pre_header);
1612 new_pre_header->SetDominator(if_block);
1613 new_pre_header->dominated_blocks_.Add(header);
1614 header->SetDominator(new_pre_header);
1615
1616 size_t index_of_header = 0;
1617 while (reverse_post_order_.Get(index_of_header) != header) {
1618 index_of_header++;
1619 }
1620 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
1621 reverse_post_order_.Put(index_of_header++, if_block);
1622 reverse_post_order_.Put(index_of_header++, dummy_block);
1623 reverse_post_order_.Put(index_of_header++, deopt_block);
1624 reverse_post_order_.Put(index_of_header++, new_pre_header);
1625
1626 HLoopInformation* info = pre_header->GetLoopInformation();
1627 if (info != nullptr) {
1628 if_block->SetLoopInformation(info);
1629 dummy_block->SetLoopInformation(info);
1630 deopt_block->SetLoopInformation(info);
1631 new_pre_header->SetLoopInformation(info);
1632 for (HLoopInformationOutwardIterator loop_it(*pre_header);
1633 !loop_it.Done();
1634 loop_it.Advance()) {
1635 loop_it.Current()->Add(if_block);
1636 loop_it.Current()->Add(dummy_block);
1637 loop_it.Current()->Add(deopt_block);
1638 loop_it.Current()->Add(new_pre_header);
1639 }
1640 }
1641}
1642
Calin Juravleacf735c2015-02-12 15:25:22 +00001643std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1644 ScopedObjectAccess soa(Thread::Current());
1645 os << "["
1646 << " is_top=" << rhs.IsTop()
1647 << " type=" << (rhs.IsTop() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
1648 << " is_exact=" << rhs.IsExact()
1649 << " ]";
1650 return os;
1651}
1652
Mark Mendellc4701932015-04-10 13:18:51 -04001653bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
1654 // For now, assume that instructions in different blocks may use the
1655 // environment.
1656 // TODO: Use the control flow to decide if this is true.
1657 if (GetBlock() != other->GetBlock()) {
1658 return true;
1659 }
1660
1661 // We know that we are in the same block. Walk from 'this' to 'other',
1662 // checking to see if there is any instruction with an environment.
1663 HInstruction* current = this;
1664 for (; current != other && current != nullptr; current = current->GetNext()) {
1665 // This is a conservative check, as the instruction result may not be in
1666 // the referenced environment.
1667 if (current->HasEnvironment()) {
1668 return true;
1669 }
1670 }
1671
1672 // We should have been called with 'this' before 'other' in the block.
1673 // Just confirm this.
1674 DCHECK(current != nullptr);
1675 return false;
1676}
1677
1678void HInstruction::RemoveEnvironmentUsers() {
1679 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
1680 HUseListNode<HEnvironment*>* user_node = use_it.Current();
1681 HEnvironment* user = user_node->GetUser();
1682 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
1683 }
1684 env_uses_.Clear();
1685}
1686
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001687} // namespace art