blob: c158ddf4eec3f81dfdc9e73a76211835f0ac2896 [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
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010019#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000020#include "utils/growable_array.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000021#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000022
23namespace art {
24
25void HGraph::AddBlock(HBasicBlock* block) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000026 block->SetBlockId(blocks_.Size());
Nicolas Geoffray818f2102014-02-18 16:43:35 +000027 blocks_.Add(block);
28}
29
Nicolas Geoffray804d0932014-05-02 08:46:00 +010030void HGraph::FindBackEdges(ArenaBitVector* visited) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000031 ArenaBitVector visiting(arena_, blocks_.Size(), false);
Nicolas Geoffrayd4dd2552014-02-28 10:23:58 +000032 VisitBlockForBackEdges(entry_block_, visited, &visiting);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000033}
34
Roland Levillainfc600dc2014-12-02 17:16:31 +000035static void RemoveAsUser(HInstruction* instruction) {
36 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000037 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000038 }
39
40 HEnvironment* environment = instruction->GetEnvironment();
41 if (environment != nullptr) {
42 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000043 if (environment->GetInstructionAt(i) != nullptr) {
44 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000045 }
46 }
47 }
48}
49
50void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
51 for (size_t i = 0; i < blocks_.Size(); ++i) {
52 if (!visited.IsBitSet(i)) {
53 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010054 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +000055 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
56 RemoveAsUser(it.Current());
57 }
58 }
59 }
60}
61
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010062void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010063 for (size_t i = 0; i < blocks_.Size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000064 if (!visited.IsBitSet(i)) {
David Brazdil1abb4192015-02-17 18:33:36 +000065 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010066 // We only need to update the successor, which might be live.
David Brazdil1abb4192015-02-17 18:33:36 +000067 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
68 block->GetSuccessors().Get(j)->RemovePredecessor(block);
69 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +010070 // Remove the block from the list of blocks, so that further analyses
71 // never see it.
72 blocks_.Put(i, nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000073 }
74 }
75}
76
77void HGraph::VisitBlockForBackEdges(HBasicBlock* block,
78 ArenaBitVector* visited,
Nicolas Geoffray804d0932014-05-02 08:46:00 +010079 ArenaBitVector* visiting) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +000080 int id = block->GetBlockId();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000081 if (visited->IsBitSet(id)) return;
82
83 visited->SetBit(id);
84 visiting->SetBit(id);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +010085 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
86 HBasicBlock* successor = block->GetSuccessors().Get(i);
Nicolas Geoffray787c3072014-03-17 10:20:19 +000087 if (visiting->IsBitSet(successor->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000088 successor->AddBackEdge(block);
89 } else {
90 VisitBlockForBackEdges(successor, visited, visiting);
91 }
92 }
93 visiting->ClearBit(id);
94}
95
96void HGraph::BuildDominatorTree() {
97 ArenaBitVector visited(arena_, blocks_.Size(), false);
98
99 // (1) Find the back edges in the graph doing a DFS traversal.
100 FindBackEdges(&visited);
101
Roland Levillainfc600dc2014-12-02 17:16:31 +0000102 // (2) Remove instructions and phis from blocks not visited during
103 // the initial DFS as users from other instructions, so that
104 // users can be safely removed before uses later.
105 RemoveInstructionsAsUsersFromDeadBlocks(visited);
106
107 // (3) Remove blocks not visited during the initial DFS.
108 // Step (4) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000109 // predecessors list of live blocks.
110 RemoveDeadBlocks(visited);
111
Roland Levillainfc600dc2014-12-02 17:16:31 +0000112 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100113 // dominators and the reverse post order.
114 SimplifyCFG();
115
Roland Levillainfc600dc2014-12-02 17:16:31 +0000116 // (5) Compute the immediate dominator of each block. We visit
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000117 // the successors of a block only when all its forward branches
118 // have been processed.
119 GrowableArray<size_t> visits(arena_, blocks_.Size());
120 visits.SetSize(blocks_.Size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100121 reverse_post_order_.Add(entry_block_);
122 for (size_t i = 0; i < entry_block_->GetSuccessors().Size(); i++) {
123 VisitBlockForDominatorTree(entry_block_->GetSuccessors().Get(i), entry_block_, &visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000124 }
125}
126
127HBasicBlock* HGraph::FindCommonDominator(HBasicBlock* first, HBasicBlock* second) const {
128 ArenaBitVector visited(arena_, blocks_.Size(), false);
129 // Walk the dominator tree of the first block and mark the visited blocks.
130 while (first != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000131 visited.SetBit(first->GetBlockId());
132 first = first->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000133 }
134 // Walk the dominator tree of the second block until a marked block is found.
135 while (second != nullptr) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000136 if (visited.IsBitSet(second->GetBlockId())) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000137 return second;
138 }
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000139 second = second->GetDominator();
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000140 }
141 LOG(ERROR) << "Could not find common dominator";
142 return nullptr;
143}
144
145void HGraph::VisitBlockForDominatorTree(HBasicBlock* block,
146 HBasicBlock* predecessor,
147 GrowableArray<size_t>* visits) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000148 if (block->GetDominator() == nullptr) {
149 block->SetDominator(predecessor);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000150 } else {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000151 block->SetDominator(FindCommonDominator(block->GetDominator(), predecessor));
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000152 }
153
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000154 visits->Increment(block->GetBlockId());
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000155 // Once all the forward edges have been visited, we know the immediate
156 // dominator of the block. We can then start visiting its successors.
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000157 if (visits->Get(block->GetBlockId()) ==
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100158 block->GetPredecessors().Size() - block->NumberOfBackEdges()) {
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100159 block->GetDominator()->AddDominatedBlock(block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100160 reverse_post_order_.Add(block);
161 for (size_t i = 0; i < block->GetSuccessors().Size(); i++) {
162 VisitBlockForDominatorTree(block->GetSuccessors().Get(i), block, visits);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000163 }
164 }
165}
166
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000167void HGraph::TransformToSsa() {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100168 DCHECK(!reverse_post_order_.IsEmpty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100169 SsaBuilder ssa_builder(this);
170 ssa_builder.BuildSsa();
171}
172
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100173void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
174 // Insert a new node between `block` and `successor` to split the
175 // critical edge.
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100176 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100177 AddBlock(new_block);
178 new_block->AddInstruction(new (arena_) HGoto());
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100179 block->ReplaceSuccessor(successor, new_block);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100180 new_block->AddSuccessor(successor);
181 if (successor->IsLoopHeader()) {
182 // If we split at a back edge boundary, make the new block the back edge.
183 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000184 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100185 info->RemoveBackEdge(block);
186 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100187 }
188 }
189}
190
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100191void HGraph::SimplifyLoop(HBasicBlock* header) {
192 HLoopInformation* info = header->GetLoopInformation();
193
194 // If there are more than one back edge, make them branch to the same block that
195 // will become the only back edge. This simplifies finding natural loops in the
196 // graph.
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100197 // Also, if the loop is a do/while (that is the back edge is an if), change the
198 // back edge to be a goto. This simplifies code generation of suspend cheks.
199 if (info->NumberOfBackEdges() > 1 || info->GetBackEdges().Get(0)->GetLastInstruction()->IsIf()) {
200 HBasicBlock* new_back_edge = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100201 AddBlock(new_back_edge);
202 new_back_edge->AddInstruction(new (arena_) HGoto());
203 for (size_t pred = 0, e = info->GetBackEdges().Size(); pred < e; ++pred) {
204 HBasicBlock* back_edge = info->GetBackEdges().Get(pred);
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100205 back_edge->ReplaceSuccessor(header, new_back_edge);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100206 }
207 info->ClearBackEdges();
208 info->AddBackEdge(new_back_edge);
209 new_back_edge->AddSuccessor(header);
210 }
211
212 // Make sure the loop has only one pre header. This simplifies SSA building by having
213 // to just look at the pre header to know which locals are initialized at entry of the
214 // loop.
215 size_t number_of_incomings = header->GetPredecessors().Size() - info->NumberOfBackEdges();
216 if (number_of_incomings != 1) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100217 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100218 AddBlock(pre_header);
219 pre_header->AddInstruction(new (arena_) HGoto());
220
221 ArenaBitVector back_edges(arena_, GetBlocks().Size(), false);
222 HBasicBlock* back_edge = info->GetBackEdges().Get(0);
223 for (size_t pred = 0; pred < header->GetPredecessors().Size(); ++pred) {
224 HBasicBlock* predecessor = header->GetPredecessors().Get(pred);
225 if (predecessor != back_edge) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100226 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100227 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100228 }
229 }
230 pre_header->AddSuccessor(header);
231 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100232
233 // Make sure the second predecessor of a loop header is the back edge.
234 if (header->GetPredecessors().Get(1) != info->GetBackEdges().Get(0)) {
235 header->SwapPredecessors();
236 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100237
238 // Place the suspend check at the beginning of the header, so that live registers
239 // will be known when allocating registers. Note that code generation can still
240 // generate the suspend check at the back edge, but needs to be careful with
241 // loop phi spill slots (which are not written to at back edge).
242 HInstruction* first_instruction = header->GetFirstInstruction();
243 if (!first_instruction->IsSuspendCheck()) {
244 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
245 header->InsertInstructionBefore(check, first_instruction);
246 first_instruction = check;
247 }
248 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100249}
250
251void HGraph::SimplifyCFG() {
252 // Simplify the CFG for future analysis, and code generation:
253 // (1): Split critical edges.
254 // (2): Simplify loops by having only one back edge, and one preheader.
255 for (size_t i = 0; i < blocks_.Size(); ++i) {
256 HBasicBlock* block = blocks_.Get(i);
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100257 if (block == nullptr) continue;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100258 if (block->GetSuccessors().Size() > 1) {
259 for (size_t j = 0; j < block->GetSuccessors().Size(); ++j) {
260 HBasicBlock* successor = block->GetSuccessors().Get(j);
261 if (successor->GetPredecessors().Size() > 1) {
262 SplitCriticalEdge(block, successor);
263 --j;
264 }
265 }
266 }
267 if (block->IsLoopHeader()) {
268 SimplifyLoop(block);
269 }
270 }
271}
272
Nicolas Geoffrayf5370122014-12-02 11:51:19 +0000273bool HGraph::AnalyzeNaturalLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100274 // Order does not matter.
275 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
276 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100277 if (block->IsLoopHeader()) {
278 HLoopInformation* info = block->GetLoopInformation();
279 if (!info->Populate()) {
280 // Abort if the loop is non natural. We currently bailout in such cases.
281 return false;
282 }
283 }
284 }
285 return true;
286}
287
David Brazdil8d5b8b22015-03-24 10:51:52 +0000288void HGraph::InsertConstant(HConstant* constant) {
289 // New constants are inserted before the final control-flow instruction
290 // of the graph, or at its end if called from the graph builder.
291 if (entry_block_->EndsWithControlFlowInstruction()) {
292 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000293 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000294 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000295 }
296}
297
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000298HNullConstant* HGraph::GetNullConstant() {
299 if (cached_null_constant_ == nullptr) {
300 cached_null_constant_ = new (arena_) HNullConstant();
David Brazdil8d5b8b22015-03-24 10:51:52 +0000301 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000302 }
303 return cached_null_constant_;
304}
305
David Brazdil8d5b8b22015-03-24 10:51:52 +0000306template <class InstructionType, typename ValueType>
307InstructionType* HGraph::CreateConstant(ValueType value,
308 ArenaSafeMap<ValueType, InstructionType*>* cache) {
309 // Try to find an existing constant of the given value.
310 InstructionType* constant = nullptr;
311 auto cached_constant = cache->find(value);
312 if (cached_constant != cache->end()) {
313 constant = cached_constant->second;
David Brazdil46e2a392015-03-16 17:31:52 +0000314 }
David Brazdil8d5b8b22015-03-24 10:51:52 +0000315
316 // If not found or previously deleted, create and cache a new instruction.
317 if (constant == nullptr || constant->GetBlock() == nullptr) {
318 constant = new (arena_) InstructionType(value);
319 cache->Overwrite(value, constant);
320 InsertConstant(constant);
321 }
322 return constant;
David Brazdil46e2a392015-03-16 17:31:52 +0000323}
324
David Brazdil8d5b8b22015-03-24 10:51:52 +0000325HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value) {
326 switch (type) {
327 case Primitive::Type::kPrimBoolean:
328 DCHECK(IsUint<1>(value));
329 FALLTHROUGH_INTENDED;
330 case Primitive::Type::kPrimByte:
331 case Primitive::Type::kPrimChar:
332 case Primitive::Type::kPrimShort:
333 case Primitive::Type::kPrimInt:
334 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
335 return GetIntConstant(static_cast<int32_t>(value));
336
337 case Primitive::Type::kPrimLong:
338 return GetLongConstant(value);
339
340 default:
341 LOG(FATAL) << "Unsupported constant type";
342 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000343 }
David Brazdil46e2a392015-03-16 17:31:52 +0000344}
345
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000346void HLoopInformation::Add(HBasicBlock* block) {
347 blocks_.SetBit(block->GetBlockId());
348}
349
David Brazdil46e2a392015-03-16 17:31:52 +0000350void HLoopInformation::Remove(HBasicBlock* block) {
351 blocks_.ClearBit(block->GetBlockId());
352}
353
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100354void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
355 if (blocks_.IsBitSet(block->GetBlockId())) {
356 return;
357 }
358
359 blocks_.SetBit(block->GetBlockId());
360 block->SetInLoop(this);
361 for (size_t i = 0, e = block->GetPredecessors().Size(); i < e; ++i) {
362 PopulateRecursive(block->GetPredecessors().Get(i));
363 }
364}
365
366bool HLoopInformation::Populate() {
367 DCHECK_EQ(GetBackEdges().Size(), 1u);
368 HBasicBlock* back_edge = GetBackEdges().Get(0);
369 DCHECK(back_edge->GetDominator() != nullptr);
370 if (!header_->Dominates(back_edge)) {
371 // This loop is not natural. Do not bother going further.
372 return false;
373 }
374
375 // Populate this loop: starting with the back edge, recursively add predecessors
376 // that are not already part of that loop. Set the header as part of the loop
377 // to end the recursion.
378 // This is a recursive implementation of the algorithm described in
379 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
380 blocks_.SetBit(header_->GetBlockId());
381 PopulateRecursive(back_edge);
382 return true;
383}
384
385HBasicBlock* HLoopInformation::GetPreHeader() const {
386 DCHECK_EQ(header_->GetPredecessors().Size(), 2u);
387 return header_->GetDominator();
388}
389
390bool HLoopInformation::Contains(const HBasicBlock& block) const {
391 return blocks_.IsBitSet(block.GetBlockId());
392}
393
394bool HLoopInformation::IsIn(const HLoopInformation& other) const {
395 return other.blocks_.IsBitSet(header_->GetBlockId());
396}
397
398bool HBasicBlock::Dominates(HBasicBlock* other) const {
399 // Walk up the dominator tree from `other`, to find out if `this`
400 // is an ancestor.
401 HBasicBlock* current = other;
402 while (current != nullptr) {
403 if (current == this) {
404 return true;
405 }
406 current = current->GetDominator();
407 }
408 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100409}
410
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100411static void UpdateInputsUsers(HInstruction* instruction) {
412 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
413 instruction->InputAt(i)->AddUseAt(instruction, i);
414 }
415 // Environment should be created later.
416 DCHECK(!instruction->HasEnvironment());
417}
418
Roland Levillainccc07a92014-09-16 14:48:16 +0100419void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
420 HInstruction* replacement) {
421 DCHECK(initial->GetBlock() == this);
422 InsertInstructionBefore(replacement, initial);
423 initial->ReplaceWith(replacement);
424 RemoveInstruction(initial);
425}
426
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100427static void Add(HInstructionList* instruction_list,
428 HBasicBlock* block,
429 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000430 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000431 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100432 instruction->SetBlock(block);
433 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100434 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100435 instruction_list->AddInstruction(instruction);
436}
437
438void HBasicBlock::AddInstruction(HInstruction* instruction) {
439 Add(&instructions_, this, instruction);
440}
441
442void HBasicBlock::AddPhi(HPhi* phi) {
443 Add(&phis_, this, phi);
444}
445
David Brazdilc3d743f2015-04-22 13:40:50 +0100446void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
447 DCHECK(!cursor->IsPhi());
448 DCHECK(!instruction->IsPhi());
449 DCHECK_EQ(instruction->GetId(), -1);
450 DCHECK_NE(cursor->GetId(), -1);
451 DCHECK_EQ(cursor->GetBlock(), this);
452 DCHECK(!instruction->IsControlFlow());
453 instruction->SetBlock(this);
454 instruction->SetId(GetGraph()->GetNextInstructionId());
455 UpdateInputsUsers(instruction);
456 instructions_.InsertInstructionBefore(instruction, cursor);
457}
458
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100459void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
460 DCHECK_EQ(phi->GetId(), -1);
461 DCHECK_NE(cursor->GetId(), -1);
462 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100463 phi->SetBlock(this);
464 phi->SetId(GetGraph()->GetNextInstructionId());
465 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100466 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100467}
468
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100469static void Remove(HInstructionList* instruction_list,
470 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000471 HInstruction* instruction,
472 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100473 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100474 instruction->SetBlock(nullptr);
475 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000476 if (ensure_safety) {
477 DCHECK(instruction->GetUses().IsEmpty());
478 DCHECK(instruction->GetEnvUses().IsEmpty());
479 RemoveAsUser(instruction);
480 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100481}
482
David Brazdil1abb4192015-02-17 18:33:36 +0000483void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
484 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100485}
486
David Brazdil1abb4192015-02-17 18:33:36 +0000487void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
488 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100489}
490
David Brazdiled596192015-01-23 10:39:45 +0000491void HEnvironment::CopyFrom(HEnvironment* env) {
492 for (size_t i = 0; i < env->Size(); i++) {
493 HInstruction* instruction = env->GetInstructionAt(i);
494 SetRawEnvAt(i, instruction);
495 if (instruction != nullptr) {
496 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100497 }
David Brazdiled596192015-01-23 10:39:45 +0000498 }
499}
500
David Brazdil1abb4192015-02-17 18:33:36 +0000501void HEnvironment::RemoveAsUserOfInput(size_t index) const {
502 const HUserRecord<HEnvironment*> user_record = vregs_.Get(index);
503 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100504}
505
Calin Juravle77520bc2015-01-12 18:45:46 +0000506HInstruction* HInstruction::GetNextDisregardingMoves() const {
507 HInstruction* next = GetNext();
508 while (next != nullptr && next->IsParallelMove()) {
509 next = next->GetNext();
510 }
511 return next;
512}
513
514HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
515 HInstruction* previous = GetPrevious();
516 while (previous != nullptr && previous->IsParallelMove()) {
517 previous = previous->GetPrevious();
518 }
519 return previous;
520}
521
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100522void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000523 if (first_instruction_ == nullptr) {
524 DCHECK(last_instruction_ == nullptr);
525 first_instruction_ = last_instruction_ = instruction;
526 } else {
527 last_instruction_->next_ = instruction;
528 instruction->previous_ = last_instruction_;
529 last_instruction_ = instruction;
530 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000531}
532
David Brazdilc3d743f2015-04-22 13:40:50 +0100533void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
534 DCHECK(Contains(cursor));
535 if (cursor == first_instruction_) {
536 cursor->previous_ = instruction;
537 instruction->next_ = cursor;
538 first_instruction_ = instruction;
539 } else {
540 instruction->previous_ = cursor->previous_;
541 instruction->next_ = cursor;
542 cursor->previous_ = instruction;
543 instruction->previous_->next_ = instruction;
544 }
545}
546
547void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
548 DCHECK(Contains(cursor));
549 if (cursor == last_instruction_) {
550 cursor->next_ = instruction;
551 instruction->previous_ = cursor;
552 last_instruction_ = instruction;
553 } else {
554 instruction->next_ = cursor->next_;
555 instruction->previous_ = cursor;
556 cursor->next_ = instruction;
557 instruction->next_->previous_ = instruction;
558 }
559}
560
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100561void HInstructionList::RemoveInstruction(HInstruction* instruction) {
562 if (instruction->previous_ != nullptr) {
563 instruction->previous_->next_ = instruction->next_;
564 }
565 if (instruction->next_ != nullptr) {
566 instruction->next_->previous_ = instruction->previous_;
567 }
568 if (instruction == first_instruction_) {
569 first_instruction_ = instruction->next_;
570 }
571 if (instruction == last_instruction_) {
572 last_instruction_ = instruction->previous_;
573 }
574}
575
Roland Levillain6b469232014-09-25 10:10:38 +0100576bool HInstructionList::Contains(HInstruction* instruction) const {
577 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
578 if (it.Current() == instruction) {
579 return true;
580 }
581 }
582 return false;
583}
584
Roland Levillainccc07a92014-09-16 14:48:16 +0100585bool HInstructionList::FoundBefore(const HInstruction* instruction1,
586 const HInstruction* instruction2) const {
587 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
588 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
589 if (it.Current() == instruction1) {
590 return true;
591 }
592 if (it.Current() == instruction2) {
593 return false;
594 }
595 }
596 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
597 return true;
598}
599
Roland Levillain6c82d402014-10-13 16:10:27 +0100600bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
601 if (other_instruction == this) {
602 // An instruction does not strictly dominate itself.
603 return false;
604 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100605 HBasicBlock* block = GetBlock();
606 HBasicBlock* other_block = other_instruction->GetBlock();
607 if (block != other_block) {
608 return GetBlock()->Dominates(other_instruction->GetBlock());
609 } else {
610 // If both instructions are in the same block, ensure this
611 // instruction comes before `other_instruction`.
612 if (IsPhi()) {
613 if (!other_instruction->IsPhi()) {
614 // Phis appear before non phi-instructions so this instruction
615 // dominates `other_instruction`.
616 return true;
617 } else {
618 // There is no order among phis.
619 LOG(FATAL) << "There is no dominance between phis of a same block.";
620 return false;
621 }
622 } else {
623 // `this` is not a phi.
624 if (other_instruction->IsPhi()) {
625 // Phis appear before non phi-instructions so this instruction
626 // does not dominate `other_instruction`.
627 return false;
628 } else {
629 // Check whether this instruction comes before
630 // `other_instruction` in the instruction list.
631 return block->GetInstructions().FoundBefore(this, other_instruction);
632 }
633 }
634 }
635}
636
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100637void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100638 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000639 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
640 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100641 HInstruction* user = current->GetUser();
642 size_t input_index = current->GetIndex();
643 user->SetRawInputAt(input_index, other);
644 other->AddUseAt(user, input_index);
645 }
646
David Brazdiled596192015-01-23 10:39:45 +0000647 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
648 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100649 HEnvironment* user = current->GetUser();
650 size_t input_index = current->GetIndex();
651 user->SetRawEnvAt(input_index, other);
652 other->AddEnvUseAt(user, input_index);
653 }
654
David Brazdiled596192015-01-23 10:39:45 +0000655 uses_.Clear();
656 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100657}
658
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100659void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +0000660 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100661 SetRawInputAt(index, replacement);
662 replacement->AddUseAt(this, index);
663}
664
Nicolas Geoffray39468442014-09-02 15:17:15 +0100665size_t HInstruction::EnvironmentSize() const {
666 return HasEnvironment() ? environment_->Size() : 0;
667}
668
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100669void HPhi::AddInput(HInstruction* input) {
670 DCHECK(input->GetBlock() != nullptr);
David Brazdil1abb4192015-02-17 18:33:36 +0000671 inputs_.Add(HUserRecord<HInstruction*>(input));
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100672 input->AddUseAt(this, inputs_.Size() - 1);
673}
674
David Brazdil2d7352b2015-04-20 14:52:42 +0100675void HPhi::RemoveInputAt(size_t index) {
676 RemoveAsUserOfInput(index);
677 inputs_.DeleteAt(index);
678}
679
Nicolas Geoffray360231a2014-10-08 21:07:48 +0100680#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000681void H##name::Accept(HGraphVisitor* visitor) { \
682 visitor->Visit##name(this); \
683}
684
685FOR_EACH_INSTRUCTION(DEFINE_ACCEPT)
686
687#undef DEFINE_ACCEPT
688
689void HGraphVisitor::VisitInsertionOrder() {
Nicolas Geoffray804d0932014-05-02 08:46:00 +0100690 const GrowableArray<HBasicBlock*>& blocks = graph_->GetBlocks();
691 for (size_t i = 0 ; i < blocks.Size(); i++) {
David Brazdil46e2a392015-03-16 17:31:52 +0000692 HBasicBlock* block = blocks.Get(i);
693 if (block != nullptr) {
694 VisitBasicBlock(block);
695 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000696 }
697}
698
Roland Levillain633021e2014-10-01 14:12:25 +0100699void HGraphVisitor::VisitReversePostOrder() {
700 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
701 VisitBasicBlock(it.Current());
702 }
703}
704
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000705void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100706 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100707 it.Current()->Accept(this);
708 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +0100709 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000710 it.Current()->Accept(this);
711 }
712}
713
Roland Levillain9240d6a2014-10-20 16:47:04 +0100714HConstant* HUnaryOperation::TryStaticEvaluation() const {
715 if (GetInput()->IsIntConstant()) {
716 int32_t value = Evaluate(GetInput()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000717 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain9240d6a2014-10-20 16:47:04 +0100718 } else if (GetInput()->IsLongConstant()) {
Roland Levillainb762d2e2014-10-22 10:11:06 +0100719 // TODO: Implement static evaluation of long unary operations.
720 //
721 // Do not exit with a fatal condition here. Instead, simply
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700722 // return `null' to notify the caller that this instruction
Roland Levillainb762d2e2014-10-22 10:11:06 +0100723 // cannot (yet) be statically evaluated.
Roland Levillain9240d6a2014-10-20 16:47:04 +0100724 return nullptr;
725 }
726 return nullptr;
727}
728
729HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain556c3d12014-09-18 15:25:07 +0100730 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
731 int32_t value = Evaluate(GetLeft()->AsIntConstant()->GetValue(),
732 GetRight()->AsIntConstant()->GetValue());
David Brazdil8d5b8b22015-03-24 10:51:52 +0000733 return GetBlock()->GetGraph()->GetIntConstant(value);
Roland Levillain556c3d12014-09-18 15:25:07 +0100734 } else if (GetLeft()->IsLongConstant() && GetRight()->IsLongConstant()) {
735 int64_t value = Evaluate(GetLeft()->AsLongConstant()->GetValue(),
736 GetRight()->AsLongConstant()->GetValue());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000737 if (GetResultType() == Primitive::kPrimLong) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000738 return GetBlock()->GetGraph()->GetLongConstant(value);
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000739 } else {
Nicolas Geoffray6c2dff82015-01-21 14:56:54 +0000740 DCHECK_EQ(GetResultType(), Primitive::kPrimInt);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000741 return GetBlock()->GetGraph()->GetIntConstant(static_cast<int32_t>(value));
Nicolas Geoffray9ee66182015-01-16 12:35:40 +0000742 }
Roland Levillain556c3d12014-09-18 15:25:07 +0100743 }
744 return nullptr;
745}
Dave Allison20dfc792014-06-16 20:44:29 -0700746
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000747HConstant* HBinaryOperation::GetConstantRight() const {
748 if (GetRight()->IsConstant()) {
749 return GetRight()->AsConstant();
750 } else if (IsCommutative() && GetLeft()->IsConstant()) {
751 return GetLeft()->AsConstant();
752 } else {
753 return nullptr;
754 }
755}
756
757// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700758// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000759HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
760 HInstruction* most_constant_right = GetConstantRight();
761 if (most_constant_right == nullptr) {
762 return nullptr;
763 } else if (most_constant_right == GetLeft()) {
764 return GetRight();
765 } else {
766 return GetLeft();
767 }
768}
769
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700770bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
771 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +0100772}
773
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100774bool HInstruction::Equals(HInstruction* other) const {
775 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100776 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100777 if (!InstructionDataEquals(other)) return false;
778 if (GetType() != other->GetType()) return false;
779 if (InputCount() != other->InputCount()) return false;
780
781 for (size_t i = 0, e = InputCount(); i < e; ++i) {
782 if (InputAt(i) != other->InputAt(i)) return false;
783 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +0100784 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +0100785 return true;
786}
787
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700788std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
789#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
790 switch (rhs) {
791 FOR_EACH_INSTRUCTION(DECLARE_CASE)
792 default:
793 os << "Unknown instruction kind " << static_cast<int>(rhs);
794 break;
795 }
796#undef DECLARE_CASE
797 return os;
798}
799
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000800void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000801 next_->previous_ = previous_;
802 if (previous_ != nullptr) {
803 previous_->next_ = next_;
804 }
805 if (block_->instructions_.first_instruction_ == this) {
806 block_->instructions_.first_instruction_ = next_;
807 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000808 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000809
810 previous_ = cursor->previous_;
811 if (previous_ != nullptr) {
812 previous_->next_ = this;
813 }
814 next_ = cursor;
815 cursor->previous_ = this;
816 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +0000817
818 if (block_->instructions_.first_instruction_ == cursor) {
819 block_->instructions_.first_instruction_ = this;
820 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000821}
822
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000823HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
824 DCHECK(!cursor->IsControlFlow());
825 DCHECK_NE(instructions_.last_instruction_, cursor);
826 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +0000827
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000828 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
829 new_block->instructions_.first_instruction_ = cursor->GetNext();
830 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
831 cursor->next_->previous_ = nullptr;
832 cursor->next_ = nullptr;
833 instructions_.last_instruction_ = cursor;
834
835 new_block->instructions_.SetBlockOfInstructions(new_block);
836 for (size_t i = 0, e = GetSuccessors().Size(); i < e; ++i) {
837 HBasicBlock* successor = GetSuccessors().Get(i);
838 new_block->successors_.Add(successor);
839 successor->predecessors_.Put(successor->GetPredecessorIndexOf(this), new_block);
840 }
841 successors_.Reset();
842
843 for (size_t i = 0, e = GetDominatedBlocks().Size(); i < e; ++i) {
844 HBasicBlock* dominated = GetDominatedBlocks().Get(i);
845 dominated->dominator_ = new_block;
846 new_block->dominated_blocks_.Add(dominated);
847 }
848 dominated_blocks_.Reset();
849 return new_block;
850}
851
David Brazdil46e2a392015-03-16 17:31:52 +0000852bool HBasicBlock::IsSingleGoto() const {
853 HLoopInformation* loop_info = GetLoopInformation();
854 // TODO: Remove the null check b/19084197.
855 return GetFirstInstruction() != nullptr
856 && GetPhis().IsEmpty()
857 && GetFirstInstruction() == GetLastInstruction()
858 && GetLastInstruction()->IsGoto()
859 // Back edges generate the suspend check.
860 && (loop_info == nullptr || !loop_info->IsBackEdge(*this));
861}
862
David Brazdil8d5b8b22015-03-24 10:51:52 +0000863bool HBasicBlock::EndsWithControlFlowInstruction() const {
864 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
865}
866
David Brazdilb2bd1c52015-03-25 11:17:37 +0000867bool HBasicBlock::EndsWithIf() const {
868 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
869}
870
871bool HBasicBlock::HasSinglePhi() const {
872 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
873}
874
David Brazdil2d7352b2015-04-20 14:52:42 +0100875size_t HInstructionList::CountSize() const {
876 size_t size = 0;
877 HInstruction* current = first_instruction_;
878 for (; current != nullptr; current = current->GetNext()) {
879 size++;
880 }
881 return size;
882}
883
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000884void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
885 for (HInstruction* current = first_instruction_;
886 current != nullptr;
887 current = current->GetNext()) {
888 current->SetBlock(block);
889 }
890}
891
892void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
893 DCHECK(Contains(cursor));
894 if (!instruction_list.IsEmpty()) {
895 if (cursor == last_instruction_) {
896 last_instruction_ = instruction_list.last_instruction_;
897 } else {
898 cursor->next_->previous_ = instruction_list.last_instruction_;
899 }
900 instruction_list.last_instruction_->next_ = cursor->next_;
901 cursor->next_ = instruction_list.first_instruction_;
902 instruction_list.first_instruction_->previous_ = cursor;
903 }
904}
905
906void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +0000907 if (IsEmpty()) {
908 first_instruction_ = instruction_list.first_instruction_;
909 last_instruction_ = instruction_list.last_instruction_;
910 } else {
911 AddAfter(last_instruction_, instruction_list);
912 }
913}
914
David Brazdil2d7352b2015-04-20 14:52:42 +0100915void HBasicBlock::DisconnectAndDelete() {
916 // Dominators must be removed after all the blocks they dominate. This way
917 // a loop header is removed last, a requirement for correct loop information
918 // iteration.
919 DCHECK(dominated_blocks_.IsEmpty());
David Brazdil46e2a392015-03-16 17:31:52 +0000920
David Brazdil2d7352b2015-04-20 14:52:42 +0100921 // Remove the block from all loops it is included in.
922 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
923 HLoopInformation* loop_info = it.Current();
924 loop_info->Remove(this);
925 if (loop_info->IsBackEdge(*this)) {
926 // This deliberately leaves the loop in an inconsistent state and will
927 // fail SSAChecker unless the entire loop is removed during the pass.
928 loop_info->RemoveBackEdge(this);
929 }
930 }
931
932 // Disconnect the block from its predecessors and update their control-flow
933 // instructions.
David Brazdil46e2a392015-03-16 17:31:52 +0000934 for (size_t i = 0, e = predecessors_.Size(); i < e; ++i) {
David Brazdil2d7352b2015-04-20 14:52:42 +0100935 HBasicBlock* predecessor = predecessors_.Get(i);
936 HInstruction* last_instruction = predecessor->GetLastInstruction();
937 predecessor->RemoveInstruction(last_instruction);
938 predecessor->RemoveSuccessor(this);
939 if (predecessor->GetSuccessors().Size() == 1u) {
940 DCHECK(last_instruction->IsIf());
941 predecessor->AddInstruction(new (graph_->GetArena()) HGoto());
942 } else {
943 // The predecessor has no remaining successors and therefore must be dead.
944 // We deliberately leave it without a control-flow instruction so that the
945 // SSAChecker fails unless it is not removed during the pass too.
946 DCHECK_EQ(predecessor->GetSuccessors().Size(), 0u);
947 }
David Brazdil46e2a392015-03-16 17:31:52 +0000948 }
David Brazdil46e2a392015-03-16 17:31:52 +0000949 predecessors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +0100950
951 // Disconnect the block from its successors and update their dominators
952 // and phis.
953 for (size_t i = 0, e = successors_.Size(); i < e; ++i) {
954 HBasicBlock* successor = successors_.Get(i);
955 // Delete this block from the list of predecessors.
956 size_t this_index = successor->GetPredecessorIndexOf(this);
957 successor->predecessors_.DeleteAt(this_index);
958
959 // Check that `successor` has other predecessors, otherwise `this` is the
960 // dominator of `successor` which violates the order DCHECKed at the top.
961 DCHECK(!successor->predecessors_.IsEmpty());
962
963 // Recompute the successor's dominator.
964 HBasicBlock* old_dominator = successor->GetDominator();
965 HBasicBlock* new_dominator = successor->predecessors_.Get(0);
966 for (size_t j = 1, f = successor->predecessors_.Size(); j < f; ++j) {
967 new_dominator = graph_->FindCommonDominator(
968 new_dominator, successor->predecessors_.Get(j));
969 }
970 if (old_dominator != new_dominator) {
971 successor->SetDominator(new_dominator);
972 old_dominator->RemoveDominatedBlock(successor);
973 new_dominator->AddDominatedBlock(successor);
974 }
975
976 // Remove this block's entries in the successor's phis.
977 if (successor->predecessors_.Size() == 1u) {
978 // The successor has just one predecessor left. Replace phis with the only
979 // remaining input.
980 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
981 HPhi* phi = phi_it.Current()->AsPhi();
982 phi->ReplaceWith(phi->InputAt(1 - this_index));
983 successor->RemovePhi(phi);
984 }
985 } else {
986 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
987 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
988 }
989 }
990 }
David Brazdil46e2a392015-03-16 17:31:52 +0000991 successors_.Reset();
David Brazdil2d7352b2015-04-20 14:52:42 +0100992
993 // Disconnect from the dominator.
994 dominator_->RemoveDominatedBlock(this);
995 SetDominator(nullptr);
996
997 // Delete from the graph. The function safely deletes remaining instructions
998 // and updates the reverse post order.
999 graph_->DeleteDeadBlock(this);
1000 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001001}
1002
1003void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001004 DCHECK_EQ(GetGraph(), other->GetGraph());
1005 DCHECK(GetDominatedBlocks().Contains(other));
1006 DCHECK_EQ(GetSuccessors().Size(), 1u);
1007 DCHECK_EQ(GetSuccessors().Get(0), other);
1008 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1009 DCHECK_EQ(other->GetPredecessors().Get(0), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001010 DCHECK(other->GetPhis().IsEmpty());
1011
David Brazdil2d7352b2015-04-20 14:52:42 +01001012 // Move instructions from `other` to `this`.
1013 DCHECK(EndsWithControlFlowInstruction());
1014 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001015 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001016 other->instructions_.SetBlockOfInstructions(this);
1017 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001018
David Brazdil2d7352b2015-04-20 14:52:42 +01001019 // Remove `other` from the loops it is included in.
1020 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1021 HLoopInformation* loop_info = it.Current();
1022 loop_info->Remove(other);
1023 if (loop_info->IsBackEdge(*other)) {
1024 loop_info->ClearBackEdges();
1025 loop_info->AddBackEdge(this);
1026 }
1027 }
1028
1029 // Update links to the successors of `other`.
1030 successors_.Reset();
1031 while (!other->successors_.IsEmpty()) {
1032 HBasicBlock* successor = other->successors_.Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001033 successor->ReplacePredecessor(other, this);
1034 }
1035
David Brazdil2d7352b2015-04-20 14:52:42 +01001036 // Update the dominator tree.
1037 dominated_blocks_.Delete(other);
1038 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1039 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1040 dominated_blocks_.Add(dominated);
1041 dominated->SetDominator(this);
1042 }
1043 other->dominated_blocks_.Reset();
1044 other->dominator_ = nullptr;
1045
1046 // Clear the list of predecessors of `other` in preparation of deleting it.
1047 other->predecessors_.Reset();
1048
1049 // Delete `other` from the graph. The function updates reverse post order.
1050 graph_->DeleteDeadBlock(other);
1051 other->SetGraph(nullptr);
1052}
1053
1054void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1055 DCHECK_NE(GetGraph(), other->GetGraph());
1056 DCHECK(GetDominatedBlocks().IsEmpty());
1057 DCHECK(GetSuccessors().IsEmpty());
1058 DCHECK(!EndsWithControlFlowInstruction());
1059 DCHECK_EQ(other->GetPredecessors().Size(), 1u);
1060 DCHECK(other->GetPredecessors().Get(0)->IsEntryBlock());
1061 DCHECK(other->GetPhis().IsEmpty());
1062 DCHECK(!other->IsInLoop());
1063
1064 // Move instructions from `other` to `this`.
1065 instructions_.Add(other->GetInstructions());
1066 other->instructions_.SetBlockOfInstructions(this);
1067
1068 // Update links to the successors of `other`.
1069 successors_.Reset();
1070 while (!other->successors_.IsEmpty()) {
1071 HBasicBlock* successor = other->successors_.Get(0);
1072 successor->ReplacePredecessor(other, this);
1073 }
1074
1075 // Update the dominator tree.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001076 for (size_t i = 0, e = other->GetDominatedBlocks().Size(); i < e; ++i) {
1077 HBasicBlock* dominated = other->GetDominatedBlocks().Get(i);
1078 dominated_blocks_.Add(dominated);
1079 dominated->SetDominator(this);
1080 }
1081 other->dominated_blocks_.Reset();
1082 other->dominator_ = nullptr;
1083 other->graph_ = nullptr;
1084}
1085
1086void HBasicBlock::ReplaceWith(HBasicBlock* other) {
1087 while (!GetPredecessors().IsEmpty()) {
1088 HBasicBlock* predecessor = GetPredecessors().Get(0);
1089 predecessor->ReplaceSuccessor(this, other);
1090 }
1091 while (!GetSuccessors().IsEmpty()) {
1092 HBasicBlock* successor = GetSuccessors().Get(0);
1093 successor->ReplacePredecessor(this, other);
1094 }
1095 for (size_t i = 0; i < dominated_blocks_.Size(); ++i) {
1096 other->AddDominatedBlock(dominated_blocks_.Get(i));
1097 }
1098 GetDominator()->ReplaceDominatedBlock(this, other);
1099 other->SetDominator(GetDominator());
1100 dominator_ = nullptr;
1101 graph_ = nullptr;
1102}
1103
1104// Create space in `blocks` for adding `number_of_new_blocks` entries
1105// starting at location `at`. Blocks after `at` are moved accordingly.
1106static void MakeRoomFor(GrowableArray<HBasicBlock*>* blocks,
1107 size_t number_of_new_blocks,
1108 size_t at) {
1109 size_t old_size = blocks->Size();
1110 size_t new_size = old_size + number_of_new_blocks;
1111 blocks->SetSize(new_size);
1112 for (size_t i = old_size - 1, j = new_size - 1; i > at; --i, --j) {
1113 blocks->Put(j, blocks->Get(i));
1114 }
1115}
1116
David Brazdil2d7352b2015-04-20 14:52:42 +01001117void HGraph::DeleteDeadBlock(HBasicBlock* block) {
1118 DCHECK_EQ(block->GetGraph(), this);
1119 DCHECK(block->GetSuccessors().IsEmpty());
1120 DCHECK(block->GetPredecessors().IsEmpty());
1121 DCHECK(block->GetDominatedBlocks().IsEmpty());
1122 DCHECK(block->GetDominator() == nullptr);
1123
1124 for (HBackwardInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
1125 block->RemoveInstruction(it.Current());
1126 }
1127 for (HBackwardInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
1128 block->RemovePhi(it.Current()->AsPhi());
1129 }
1130
1131 reverse_post_order_.Delete(block);
1132 blocks_.Put(block->GetBlockId(), nullptr);
1133}
1134
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001135void HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001136 if (GetBlocks().Size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001137 // Simple case of an entry block, a body block, and an exit block.
1138 // Put the body block's instruction into `invoke`'s block.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001139 HBasicBlock* body = GetBlocks().Get(1);
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001140 DCHECK(GetBlocks().Get(0)->IsEntryBlock());
1141 DCHECK(GetBlocks().Get(2)->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001142 DCHECK(!body->IsExitBlock());
1143 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001144
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001145 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1146 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001147
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001148 // Replace the invoke with the return value of the inlined graph.
1149 if (last->IsReturn()) {
1150 invoke->ReplaceWith(last->InputAt(0));
1151 } else {
1152 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001153 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001154
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001155 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001156 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001157 // Need to inline multiple blocks. We split `invoke`'s block
1158 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001159 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001160 // with the second half.
1161 ArenaAllocator* allocator = outer_graph->GetArena();
1162 HBasicBlock* at = invoke->GetBlock();
1163 HBasicBlock* to = at->SplitAfter(invoke);
1164
1165 HBasicBlock* first = entry_block_->GetSuccessors().Get(0);
1166 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001167 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001168 exit_block_->ReplaceWith(to);
1169
1170 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001171 // to not `HReturn` but `HGoto` instead.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001172 HInstruction* return_value = nullptr;
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001173 bool returns_void = to->GetPredecessors().Get(0)->GetLastInstruction()->IsReturnVoid();
1174 if (to->GetPredecessors().Size() == 1) {
1175 HBasicBlock* predecessor = to->GetPredecessors().Get(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001176 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001177 if (!returns_void) {
1178 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001179 }
1180 predecessor->AddInstruction(new (allocator) HGoto());
1181 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001182 } else {
1183 if (!returns_void) {
1184 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001185 return_value = new (allocator) HPhi(
1186 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001187 to->AddPhi(return_value->AsPhi());
1188 }
1189 for (size_t i = 0, e = to->GetPredecessors().Size(); i < e; ++i) {
1190 HBasicBlock* predecessor = to->GetPredecessors().Get(i);
1191 HInstruction* last = predecessor->GetLastInstruction();
1192 if (!returns_void) {
1193 return_value->AsPhi()->AddInput(last->InputAt(0));
1194 }
1195 predecessor->AddInstruction(new (allocator) HGoto());
1196 predecessor->RemoveInstruction(last);
1197 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001198 }
1199
1200 if (return_value != nullptr) {
1201 invoke->ReplaceWith(return_value);
1202 }
1203
1204 // Update the meta information surrounding blocks:
1205 // (1) the graph they are now in,
1206 // (2) the reverse post order of that graph,
1207 // (3) the potential loop information they are now in.
1208
1209 // We don't add the entry block, the exit block, and the first block, which
1210 // has been merged with `at`.
1211 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1212
1213 // We add the `to` block.
1214 static constexpr int kNumberOfNewBlocksInCaller = 1;
1215 size_t blocks_added = (reverse_post_order_.Size() - kNumberOfSkippedBlocksInCallee)
1216 + kNumberOfNewBlocksInCaller;
1217
1218 // Find the location of `at` in the outer graph's reverse post order. The new
1219 // blocks will be added after it.
1220 size_t index_of_at = 0;
1221 while (outer_graph->reverse_post_order_.Get(index_of_at) != at) {
1222 index_of_at++;
1223 }
1224 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1225
1226 // Do a reverse post order of the blocks in the callee and do (1), (2),
1227 // and (3) to the blocks that apply.
1228 HLoopInformation* info = at->GetLoopInformation();
1229 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1230 HBasicBlock* current = it.Current();
1231 if (current != exit_block_ && current != entry_block_ && current != first) {
1232 DCHECK(!current->IsInLoop());
1233 DCHECK(current->GetGraph() == this);
1234 current->SetGraph(outer_graph);
1235 outer_graph->AddBlock(current);
1236 outer_graph->reverse_post_order_.Put(++index_of_at, current);
1237 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001238 current->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001239 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1240 loop_it.Current()->Add(current);
1241 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001242 }
1243 }
1244 }
1245
1246 // Do (1), (2), and (3) to `to`.
1247 to->SetGraph(outer_graph);
1248 outer_graph->AddBlock(to);
1249 outer_graph->reverse_post_order_.Put(++index_of_at, to);
1250 if (info != nullptr) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001251 to->SetLoopInformation(info);
David Brazdil7d275372015-04-21 16:36:35 +01001252 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
1253 loop_it.Current()->Add(to);
1254 }
David Brazdil46e2a392015-03-16 17:31:52 +00001255 if (info->IsBackEdge(*at)) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001256 // Only `at` can become a back edge, as the inlined blocks
1257 // are predecessors of `at`.
1258 DCHECK_EQ(1u, info->NumberOfBackEdges());
1259 info->ClearBackEdges();
1260 info->AddBackEdge(to);
1261 }
1262 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001263 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001264
David Brazdil05144f42015-04-16 15:18:00 +01001265 // Update the next instruction id of the outer graph, so that instructions
1266 // added later get bigger ids than those in the inner graph.
1267 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
1268
1269 // Walk over the entry block and:
1270 // - Move constants from the entry block to the outer_graph's entry block,
1271 // - Replace HParameterValue instructions with their real value.
1272 // - Remove suspend checks, that hold an environment.
1273 // We must do this after the other blocks have been inlined, otherwise ids of
1274 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01001275 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01001276 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
1277 HInstruction* current = it.Current();
1278 if (current->IsNullConstant()) {
1279 current->ReplaceWith(outer_graph->GetNullConstant());
1280 } else if (current->IsIntConstant()) {
1281 current->ReplaceWith(outer_graph->GetIntConstant(current->AsIntConstant()->GetValue()));
1282 } else if (current->IsLongConstant()) {
1283 current->ReplaceWith(outer_graph->GetLongConstant(current->AsLongConstant()->GetValue()));
1284 } else if (current->IsFloatConstant() || current->IsDoubleConstant()) {
1285 // TODO: Don't duplicate floating-point constants.
1286 current->MoveBefore(outer_graph->GetEntryBlock()->GetLastInstruction());
1287 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01001288 if (kIsDebugBuild
1289 && invoke->IsInvokeStaticOrDirect()
1290 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
1291 // Ensure we do not use the last input of `invoke`, as it
1292 // contains a clinit check which is not an actual argument.
1293 size_t last_input_index = invoke->InputCount() - 1;
1294 DCHECK(parameter_index != last_input_index);
1295 }
David Brazdil05144f42015-04-16 15:18:00 +01001296 current->ReplaceWith(invoke->InputAt(parameter_index++));
1297 } else {
1298 DCHECK(current->IsGoto() || current->IsSuspendCheck());
1299 entry_block_->RemoveInstruction(current);
1300 }
1301 }
1302
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001303 // Finally remove the invoke from the caller.
1304 invoke->GetBlock()->RemoveInstruction(invoke);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001305}
1306
Calin Juravleacf735c2015-02-12 15:25:22 +00001307std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
1308 ScopedObjectAccess soa(Thread::Current());
1309 os << "["
1310 << " is_top=" << rhs.IsTop()
1311 << " type=" << (rhs.IsTop() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
1312 << " is_exact=" << rhs.IsExact()
1313 << " ]";
1314 return os;
1315}
1316
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001317} // namespace art