blob: 1afa36a89c23c54da95f6eaca8034ba7079a7dd6 [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 */
Nicolas Geoffray818f2102014-02-18 16:43:35 +000016#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000017
Roland Levillain31dd3d62016-02-16 12:21:02 +000018#include <cfloat>
19
Mark Mendelle82549b2015-05-06 10:55:34 -040020#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000021#include "common_dominator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010022#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010023#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010024#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010025#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010026#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010027#include "mirror/class-inl.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000028#include "scoped_thread_state_change.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000029
30namespace art {
31
Roland Levillain31dd3d62016-02-16 12:21:02 +000032// Enable floating-point static evaluation during constant folding
33// only if all floating-point operations and constants evaluate in the
34// range and precision of the type used (i.e., 32-bit float, 64-bit
35// double).
36static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
37
David Brazdilbadd8262016-02-02 16:28:56 +000038void HGraph::InitializeInexactObjectRTI(StackHandleScopeCollection* handles) {
39 ScopedObjectAccess soa(Thread::Current());
40 // Create the inexact Object reference type and store it in the HGraph.
41 ClassLinker* linker = Runtime::Current()->GetClassLinker();
42 inexact_object_rti_ = ReferenceTypeInfo::Create(
43 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
44 /* is_exact */ false);
45}
46
Nicolas Geoffray818f2102014-02-18 16:43:35 +000047void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010048 block->SetBlockId(blocks_.size());
49 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000050}
51
Nicolas Geoffray804d0932014-05-02 08:46:00 +010052void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010053 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
54 DCHECK_EQ(visited->GetHighestBitSet(), -1);
55
56 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markof6a35de2016-03-21 12:01:50 +000057 ArenaBitVector visiting(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010058 // Number of successors visited from a given node, indexed by block id.
59 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
60 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
61 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
62 constexpr size_t kDefaultWorklistSize = 8;
63 worklist.reserve(kDefaultWorklistSize);
64 visited->SetBit(entry_block_->GetBlockId());
65 visiting.SetBit(entry_block_->GetBlockId());
66 worklist.push_back(entry_block_);
67
68 while (!worklist.empty()) {
69 HBasicBlock* current = worklist.back();
70 uint32_t current_id = current->GetBlockId();
71 if (successors_visited[current_id] == current->GetSuccessors().size()) {
72 visiting.ClearBit(current_id);
73 worklist.pop_back();
74 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010075 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
76 uint32_t successor_id = successor->GetBlockId();
77 if (visiting.IsBitSet(successor_id)) {
78 DCHECK(ContainsElement(worklist, successor));
79 successor->AddBackEdge(current);
80 } else if (!visited->IsBitSet(successor_id)) {
81 visited->SetBit(successor_id);
82 visiting.SetBit(successor_id);
83 worklist.push_back(successor);
84 }
85 }
86 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000087}
88
Vladimir Markocac5a7e2016-02-22 10:39:50 +000089static void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010090 for (HEnvironment* environment = instruction->GetEnvironment();
91 environment != nullptr;
92 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000093 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000094 if (environment->GetInstructionAt(i) != nullptr) {
95 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000096 }
97 }
98 }
99}
100
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000101static void RemoveAsUser(HInstruction* instruction) {
102 for (size_t i = 0; i < instruction->InputCount(); i++) {
103 instruction->RemoveAsUserOfInput(i);
104 }
105
106 RemoveEnvironmentUses(instruction);
107}
108
Roland Levillainfc600dc2014-12-02 17:16:31 +0000109void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100110 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000111 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100112 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000113 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100114 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000115 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
116 RemoveAsUser(it.Current());
117 }
118 }
119 }
120}
121
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100122void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100123 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000124 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100125 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000126 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100127 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000128 for (HBasicBlock* successor : block->GetSuccessors()) {
129 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000130 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100131 // Remove the block from the list of blocks, so that further analyses
132 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100133 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600134 if (block->IsExitBlock()) {
135 SetExitBlock(nullptr);
136 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000137 // Mark the block as removed. This is used by the HGraphBuilder to discard
138 // the block as a branch target.
139 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000140 }
141 }
142}
143
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000144GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000145 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000146
David Brazdil86ea7ee2016-02-16 09:26:07 +0000147 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000148 FindBackEdges(&visited);
149
David Brazdil86ea7ee2016-02-16 09:26:07 +0000150 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000151 // the initial DFS as users from other instructions, so that
152 // users can be safely removed before uses later.
153 RemoveInstructionsAsUsersFromDeadBlocks(visited);
154
David Brazdil86ea7ee2016-02-16 09:26:07 +0000155 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000156 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000157 // predecessors list of live blocks.
158 RemoveDeadBlocks(visited);
159
David Brazdil86ea7ee2016-02-16 09:26:07 +0000160 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100161 // dominators and the reverse post order.
162 SimplifyCFG();
163
David Brazdil86ea7ee2016-02-16 09:26:07 +0000164 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100165 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000166
David Brazdil86ea7ee2016-02-16 09:26:07 +0000167 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000168 // set the loop information on each block.
169 GraphAnalysisResult result = AnalyzeLoops();
170 if (result != kAnalysisSuccess) {
171 return result;
172 }
173
David Brazdil86ea7ee2016-02-16 09:26:07 +0000174 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000175 // which needs the information to build catch block phis from values of
176 // locals at throwing instructions inside try blocks.
177 ComputeTryBlockInformation();
178
179 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100180}
181
182void HGraph::ClearDominanceInformation() {
183 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
184 it.Current()->ClearDominanceInformation();
185 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100186 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100187}
188
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000189void HGraph::ClearLoopInformation() {
190 SetHasIrreducibleLoops(false);
191 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000192 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000193 }
194}
195
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100196void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000197 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100198 dominator_ = nullptr;
199}
200
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000201HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
202 HInstruction* instruction = GetFirstInstruction();
203 while (instruction->IsParallelMove()) {
204 instruction = instruction->GetNext();
205 }
206 return instruction;
207}
208
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100209void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100210 DCHECK(reverse_post_order_.empty());
211 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100212 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100213
214 // Number of visits of a given node, indexed by block id.
215 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
216 // Number of successors visited from a given node, indexed by block id.
217 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
218 // Nodes for which we need to visit successors.
219 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
220 constexpr size_t kDefaultWorklistSize = 8;
221 worklist.reserve(kDefaultWorklistSize);
222 worklist.push_back(entry_block_);
223
224 while (!worklist.empty()) {
225 HBasicBlock* current = worklist.back();
226 uint32_t current_id = current->GetBlockId();
227 if (successors_visited[current_id] == current->GetSuccessors().size()) {
228 worklist.pop_back();
229 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100230 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
231
232 if (successor->GetDominator() == nullptr) {
233 successor->SetDominator(current);
234 } else {
Vladimir Marko391d01f2015-11-06 11:02:08 +0000235 // The CommonDominator can work for multiple blocks as long as the
236 // domination information doesn't change. However, since we're changing
237 // that information here, we can use the finder only for pairs of blocks.
238 successor->SetDominator(CommonDominator::ForPair(successor->GetDominator(), current));
Vladimir Markod76d1392015-09-23 16:07:14 +0100239 }
240
241 // Once all the forward edges have been visited, we know the immediate
242 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100243 if (++visits[successor->GetBlockId()] ==
244 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100245 reverse_post_order_.push_back(successor);
246 worklist.push_back(successor);
247 }
248 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000249 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000250
251 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000252 // The potential presence of irreducible loops requires to do it after.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000253 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
254 HBasicBlock* block = it.Current();
255 if (!block->IsEntryBlock()) {
256 block->GetDominator()->AddDominatedBlock(block);
257 }
258 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000259}
260
David Brazdilfc6a86a2015-06-26 10:33:45 +0000261HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000262 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
263 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000264 // Use `InsertBetween` to ensure the predecessor index and successor index of
265 // `block` and `successor` are preserved.
266 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000267 return new_block;
268}
269
270void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
271 // Insert a new node between `block` and `successor` to split the
272 // critical edge.
273 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600274 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100275 if (successor->IsLoopHeader()) {
276 // If we split at a back edge boundary, make the new block the back edge.
277 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000278 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100279 info->RemoveBackEdge(block);
280 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100281 }
282 }
283}
284
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100285void HGraph::SimplifyLoop(HBasicBlock* header) {
286 HLoopInformation* info = header->GetLoopInformation();
287
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100288 // Make sure the loop has only one pre header. This simplifies SSA building by having
289 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000290 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
291 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000292 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000293 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100294 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100295 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600296 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100297
Vladimir Marko60584552015-09-03 13:35:12 +0000298 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100299 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100300 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100301 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100302 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100303 }
304 }
305 pre_header->AddSuccessor(header);
306 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100307
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100308 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100309 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
310 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000311 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100312 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100313 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000314 header->predecessors_[pred] = to_swap;
315 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100316 break;
317 }
318 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100319 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100320
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100321 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000322 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
323 // Called from DeadBlockElimination. Update SuspendCheck pointer.
324 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100325 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100326}
327
David Brazdilffee3d32015-07-06 11:48:53 +0100328void HGraph::ComputeTryBlockInformation() {
329 // Iterate in reverse post order to propagate try membership information from
330 // predecessors to their successors.
331 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
332 HBasicBlock* block = it.Current();
333 if (block->IsEntryBlock() || block->IsCatchBlock()) {
334 // Catch blocks after simplification have only exceptional predecessors
335 // and hence are never in tries.
336 continue;
337 }
338
339 // Infer try membership from the first predecessor. Having simplified loops,
340 // the first predecessor can never be a back edge and therefore it must have
341 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100342 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100343 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100344 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000345 if (try_entry != nullptr &&
346 (block->GetTryCatchInformation() == nullptr ||
347 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
348 // We are either setting try block membership for the first time or it
349 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100350 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
351 }
David Brazdilffee3d32015-07-06 11:48:53 +0100352 }
353}
354
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100355void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000356// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100357 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000358 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100359 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
360 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
361 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
362 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100363 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000364 if (block->GetSuccessors().size() > 1) {
365 // Only split normal-flow edges. We cannot split exceptional edges as they
366 // are synthesized (approximate real control flow), and we do not need to
367 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000368 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
369 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
370 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100371 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000372 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000373 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
374 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000375 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000376 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100377 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000378 // SplitCriticalEdge could have invalidated the `normal_successors`
379 // ArrayRef. We must re-acquire it.
380 normal_successors = block->GetNormalSuccessors();
381 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
382 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100383 }
384 }
385 }
386 if (block->IsLoopHeader()) {
387 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000388 } else if (!block->IsEntryBlock() &&
389 block->GetFirstInstruction() != nullptr &&
390 block->GetFirstInstruction()->IsSuspendCheck()) {
391 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000392 // a loop got dismantled. Just remove the suspend check.
393 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100394 }
395 }
396}
397
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000398GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100399 // Order does not matter.
400 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
401 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100402 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100403 if (block->IsCatchBlock()) {
404 // TODO: Dealing with exceptional back edges could be tricky because
405 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000406 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100407 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000408 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100409 }
410 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000411 return kAnalysisSuccess;
412}
413
414void HLoopInformation::Dump(std::ostream& os) {
415 os << "header: " << header_->GetBlockId() << std::endl;
416 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
417 for (HBasicBlock* block : back_edges_) {
418 os << "back edge: " << block->GetBlockId() << std::endl;
419 }
420 for (HBasicBlock* block : header_->GetPredecessors()) {
421 os << "predecessor: " << block->GetBlockId() << std::endl;
422 }
423 for (uint32_t idx : blocks_.Indexes()) {
424 os << " in loop: " << idx << std::endl;
425 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100426}
427
David Brazdil8d5b8b22015-03-24 10:51:52 +0000428void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000429 // New constants are inserted before the SuspendCheck at the bottom of the
430 // entry block. Note that this method can be called from the graph builder and
431 // the entry block therefore may not end with SuspendCheck->Goto yet.
432 HInstruction* insert_before = nullptr;
433
434 HInstruction* gota = entry_block_->GetLastInstruction();
435 if (gota != nullptr && gota->IsGoto()) {
436 HInstruction* suspend_check = gota->GetPrevious();
437 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
438 insert_before = suspend_check;
439 } else {
440 insert_before = gota;
441 }
442 }
443
444 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000445 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000446 } else {
447 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000448 }
449}
450
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600451HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100452 // For simplicity, don't bother reviving the cached null constant if it is
453 // not null and not in a block. Otherwise, we need to clear the instruction
454 // id and/or any invariants the graph is assuming when adding new instructions.
455 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600456 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000457 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000458 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000459 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000460 if (kIsDebugBuild) {
461 ScopedObjectAccess soa(Thread::Current());
462 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
463 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000464 return cached_null_constant_;
465}
466
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100467HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100468 // For simplicity, don't bother reviving the cached current method if it is
469 // not null and not in a block. Otherwise, we need to clear the instruction
470 // id and/or any invariants the graph is assuming when adding new instructions.
471 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700472 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600473 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
474 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100475 if (entry_block_->GetFirstInstruction() == nullptr) {
476 entry_block_->AddInstruction(cached_current_method_);
477 } else {
478 entry_block_->InsertInstructionBefore(
479 cached_current_method_, entry_block_->GetFirstInstruction());
480 }
481 }
482 return cached_current_method_;
483}
484
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600485HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000486 switch (type) {
487 case Primitive::Type::kPrimBoolean:
488 DCHECK(IsUint<1>(value));
489 FALLTHROUGH_INTENDED;
490 case Primitive::Type::kPrimByte:
491 case Primitive::Type::kPrimChar:
492 case Primitive::Type::kPrimShort:
493 case Primitive::Type::kPrimInt:
494 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600495 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000496
497 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600498 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000499
500 default:
501 LOG(FATAL) << "Unsupported constant type";
502 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000503 }
David Brazdil46e2a392015-03-16 17:31:52 +0000504}
505
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000506void HGraph::CacheFloatConstant(HFloatConstant* constant) {
507 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
508 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
509 cached_float_constants_.Overwrite(value, constant);
510}
511
512void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
513 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
514 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
515 cached_double_constants_.Overwrite(value, constant);
516}
517
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000518void HLoopInformation::Add(HBasicBlock* block) {
519 blocks_.SetBit(block->GetBlockId());
520}
521
David Brazdil46e2a392015-03-16 17:31:52 +0000522void HLoopInformation::Remove(HBasicBlock* block) {
523 blocks_.ClearBit(block->GetBlockId());
524}
525
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100526void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
527 if (blocks_.IsBitSet(block->GetBlockId())) {
528 return;
529 }
530
531 blocks_.SetBit(block->GetBlockId());
532 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000533 for (HBasicBlock* predecessor : block->GetPredecessors()) {
534 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100535 }
536}
537
David Brazdilc2e8af92016-04-05 17:15:19 +0100538void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
539 size_t block_id = block->GetBlockId();
540
541 // If `block` is in `finalized`, we know its membership in the loop has been
542 // decided and it does not need to be revisited.
543 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000544 return;
545 }
546
David Brazdilc2e8af92016-04-05 17:15:19 +0100547 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000548 if (block->IsLoopHeader()) {
549 // If we hit a loop header in an irreducible loop, we first check if the
550 // pre header of that loop belongs to the currently analyzed loop. If it does,
551 // then we visit the back edges.
552 // Note that we cannot use GetPreHeader, as the loop may have not been populated
553 // yet.
554 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100555 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000556 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000557 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100558 blocks_.SetBit(block_id);
559 finalized->SetBit(block_id);
560 is_finalized = true;
561
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000562 HLoopInformation* info = block->GetLoopInformation();
563 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100564 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000565 }
566 }
567 } else {
568 // Visit all predecessors. If one predecessor is part of the loop, this
569 // block is also part of this loop.
570 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100571 PopulateIrreducibleRecursive(predecessor, finalized);
572 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000573 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100574 blocks_.SetBit(block_id);
575 finalized->SetBit(block_id);
576 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000577 }
578 }
579 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100580
581 // All predecessors have been recursively visited. Mark finalized if not marked yet.
582 if (!is_finalized) {
583 finalized->SetBit(block_id);
584 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000585}
586
587void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100588 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000589 // Populate this loop: starting with the back edge, recursively add predecessors
590 // that are not already part of that loop. Set the header as part of the loop
591 // to end the recursion.
592 // This is a recursive implementation of the algorithm described in
593 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100594 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000595 blocks_.SetBit(header_->GetBlockId());
596 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100597
598 bool is_irreducible_loop = false;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100599 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100600 DCHECK(back_edge->GetDominator() != nullptr);
601 if (!header_->Dominates(back_edge)) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100602 is_irreducible_loop = true;
603 break;
604 }
605 }
606
607 if (is_irreducible_loop) {
608 ArenaBitVector visited(graph->GetArena(),
609 graph->GetBlocks().size(),
610 /* expandable */ false,
611 kArenaAllocGraphBuilder);
612 for (HBasicBlock* back_edge : GetBackEdges()) {
613 PopulateIrreducibleRecursive(back_edge, &visited);
614 }
615 } else {
616 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000617 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100618 }
David Brazdila4b8c212015-05-07 09:59:30 +0100619 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100620
621 if (is_irreducible_loop || graph->IsCompilingOsr()) {
622 irreducible_ = true;
623 graph->SetHasIrreducibleLoops(true);
624 }
David Brazdila4b8c212015-05-07 09:59:30 +0100625}
626
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100627HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000628 HBasicBlock* block = header_->GetPredecessors()[0];
629 DCHECK(irreducible_ || (block == header_->GetDominator()));
630 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100631}
632
633bool HLoopInformation::Contains(const HBasicBlock& block) const {
634 return blocks_.IsBitSet(block.GetBlockId());
635}
636
637bool HLoopInformation::IsIn(const HLoopInformation& other) const {
638 return other.blocks_.IsBitSet(header_->GetBlockId());
639}
640
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800641bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
642 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700643}
644
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100645size_t HLoopInformation::GetLifetimeEnd() const {
646 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100647 for (HBasicBlock* back_edge : GetBackEdges()) {
648 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100649 }
650 return last_position;
651}
652
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100653bool HBasicBlock::Dominates(HBasicBlock* other) const {
654 // Walk up the dominator tree from `other`, to find out if `this`
655 // is an ancestor.
656 HBasicBlock* current = other;
657 while (current != nullptr) {
658 if (current == this) {
659 return true;
660 }
661 current = current->GetDominator();
662 }
663 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100664}
665
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100666static void UpdateInputsUsers(HInstruction* instruction) {
667 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
668 instruction->InputAt(i)->AddUseAt(instruction, i);
669 }
670 // Environment should be created later.
671 DCHECK(!instruction->HasEnvironment());
672}
673
Roland Levillainccc07a92014-09-16 14:48:16 +0100674void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
675 HInstruction* replacement) {
676 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400677 if (initial->IsControlFlow()) {
678 // We can only replace a control flow instruction with another control flow instruction.
679 DCHECK(replacement->IsControlFlow());
680 DCHECK_EQ(replacement->GetId(), -1);
681 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
682 DCHECK_EQ(initial->GetBlock(), this);
683 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
684 DCHECK(initial->GetUses().IsEmpty());
685 DCHECK(initial->GetEnvUses().IsEmpty());
686 replacement->SetBlock(this);
687 replacement->SetId(GetGraph()->GetNextInstructionId());
688 instructions_.InsertInstructionBefore(replacement, initial);
689 UpdateInputsUsers(replacement);
690 } else {
691 InsertInstructionBefore(replacement, initial);
692 initial->ReplaceWith(replacement);
693 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100694 RemoveInstruction(initial);
695}
696
David Brazdil74eb1b22015-12-14 11:44:01 +0000697void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
698 DCHECK(!cursor->IsPhi());
699 DCHECK(!insn->IsPhi());
700 DCHECK(!insn->IsControlFlow());
701 DCHECK(insn->CanBeMoved());
702 DCHECK(!insn->HasSideEffects());
703
704 HBasicBlock* from_block = insn->GetBlock();
705 HBasicBlock* to_block = cursor->GetBlock();
706 DCHECK(from_block != to_block);
707
708 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
709 insn->SetBlock(to_block);
710 to_block->instructions_.InsertInstructionBefore(insn, cursor);
711}
712
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100713static void Add(HInstructionList* instruction_list,
714 HBasicBlock* block,
715 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000716 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000717 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100718 instruction->SetBlock(block);
719 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100720 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100721 instruction_list->AddInstruction(instruction);
722}
723
724void HBasicBlock::AddInstruction(HInstruction* instruction) {
725 Add(&instructions_, this, instruction);
726}
727
728void HBasicBlock::AddPhi(HPhi* phi) {
729 Add(&phis_, this, phi);
730}
731
David Brazdilc3d743f2015-04-22 13:40:50 +0100732void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
733 DCHECK(!cursor->IsPhi());
734 DCHECK(!instruction->IsPhi());
735 DCHECK_EQ(instruction->GetId(), -1);
736 DCHECK_NE(cursor->GetId(), -1);
737 DCHECK_EQ(cursor->GetBlock(), this);
738 DCHECK(!instruction->IsControlFlow());
739 instruction->SetBlock(this);
740 instruction->SetId(GetGraph()->GetNextInstructionId());
741 UpdateInputsUsers(instruction);
742 instructions_.InsertInstructionBefore(instruction, cursor);
743}
744
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100745void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
746 DCHECK(!cursor->IsPhi());
747 DCHECK(!instruction->IsPhi());
748 DCHECK_EQ(instruction->GetId(), -1);
749 DCHECK_NE(cursor->GetId(), -1);
750 DCHECK_EQ(cursor->GetBlock(), this);
751 DCHECK(!instruction->IsControlFlow());
752 DCHECK(!cursor->IsControlFlow());
753 instruction->SetBlock(this);
754 instruction->SetId(GetGraph()->GetNextInstructionId());
755 UpdateInputsUsers(instruction);
756 instructions_.InsertInstructionAfter(instruction, cursor);
757}
758
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100759void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
760 DCHECK_EQ(phi->GetId(), -1);
761 DCHECK_NE(cursor->GetId(), -1);
762 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100763 phi->SetBlock(this);
764 phi->SetId(GetGraph()->GetNextInstructionId());
765 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100766 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100767}
768
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100769static void Remove(HInstructionList* instruction_list,
770 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000771 HInstruction* instruction,
772 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100773 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100774 instruction->SetBlock(nullptr);
775 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000776 if (ensure_safety) {
777 DCHECK(instruction->GetUses().IsEmpty());
778 DCHECK(instruction->GetEnvUses().IsEmpty());
779 RemoveAsUser(instruction);
780 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100781}
782
David Brazdil1abb4192015-02-17 18:33:36 +0000783void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100784 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000785 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100786}
787
David Brazdil1abb4192015-02-17 18:33:36 +0000788void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
789 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100790}
791
David Brazdilc7508e92015-04-27 13:28:57 +0100792void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
793 if (instruction->IsPhi()) {
794 RemovePhi(instruction->AsPhi(), ensure_safety);
795 } else {
796 RemoveInstruction(instruction, ensure_safety);
797 }
798}
799
Vladimir Marko71bf8092015-09-15 15:33:14 +0100800void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
801 for (size_t i = 0; i < locals.size(); i++) {
802 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100803 SetRawEnvAt(i, instruction);
804 if (instruction != nullptr) {
805 instruction->AddEnvUseAt(this, i);
806 }
807 }
808}
809
David Brazdiled596192015-01-23 10:39:45 +0000810void HEnvironment::CopyFrom(HEnvironment* env) {
811 for (size_t i = 0; i < env->Size(); i++) {
812 HInstruction* instruction = env->GetInstructionAt(i);
813 SetRawEnvAt(i, instruction);
814 if (instruction != nullptr) {
815 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100816 }
David Brazdiled596192015-01-23 10:39:45 +0000817 }
818}
819
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700820void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
821 HBasicBlock* loop_header) {
822 DCHECK(loop_header->IsLoopHeader());
823 for (size_t i = 0; i < env->Size(); i++) {
824 HInstruction* instruction = env->GetInstructionAt(i);
825 SetRawEnvAt(i, instruction);
826 if (instruction == nullptr) {
827 continue;
828 }
829 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
830 // At the end of the loop pre-header, the corresponding value for instruction
831 // is the first input of the phi.
832 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700833 SetRawEnvAt(i, initial);
834 initial->AddEnvUseAt(this, i);
835 } else {
836 instruction->AddEnvUseAt(this, i);
837 }
838 }
839}
840
David Brazdil1abb4192015-02-17 18:33:36 +0000841void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100842 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000843 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100844}
845
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000846HInstruction::InstructionKind HInstruction::GetKind() const {
847 return GetKindInternal();
848}
849
Calin Juravle77520bc2015-01-12 18:45:46 +0000850HInstruction* HInstruction::GetNextDisregardingMoves() const {
851 HInstruction* next = GetNext();
852 while (next != nullptr && next->IsParallelMove()) {
853 next = next->GetNext();
854 }
855 return next;
856}
857
858HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
859 HInstruction* previous = GetPrevious();
860 while (previous != nullptr && previous->IsParallelMove()) {
861 previous = previous->GetPrevious();
862 }
863 return previous;
864}
865
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100866void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000867 if (first_instruction_ == nullptr) {
868 DCHECK(last_instruction_ == nullptr);
869 first_instruction_ = last_instruction_ = instruction;
870 } else {
871 last_instruction_->next_ = instruction;
872 instruction->previous_ = last_instruction_;
873 last_instruction_ = instruction;
874 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000875}
876
David Brazdilc3d743f2015-04-22 13:40:50 +0100877void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
878 DCHECK(Contains(cursor));
879 if (cursor == first_instruction_) {
880 cursor->previous_ = instruction;
881 instruction->next_ = cursor;
882 first_instruction_ = instruction;
883 } else {
884 instruction->previous_ = cursor->previous_;
885 instruction->next_ = cursor;
886 cursor->previous_ = instruction;
887 instruction->previous_->next_ = instruction;
888 }
889}
890
891void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
892 DCHECK(Contains(cursor));
893 if (cursor == last_instruction_) {
894 cursor->next_ = instruction;
895 instruction->previous_ = cursor;
896 last_instruction_ = instruction;
897 } else {
898 instruction->next_ = cursor->next_;
899 instruction->previous_ = cursor;
900 cursor->next_ = instruction;
901 instruction->next_->previous_ = instruction;
902 }
903}
904
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100905void HInstructionList::RemoveInstruction(HInstruction* instruction) {
906 if (instruction->previous_ != nullptr) {
907 instruction->previous_->next_ = instruction->next_;
908 }
909 if (instruction->next_ != nullptr) {
910 instruction->next_->previous_ = instruction->previous_;
911 }
912 if (instruction == first_instruction_) {
913 first_instruction_ = instruction->next_;
914 }
915 if (instruction == last_instruction_) {
916 last_instruction_ = instruction->previous_;
917 }
918}
919
Roland Levillain6b469232014-09-25 10:10:38 +0100920bool HInstructionList::Contains(HInstruction* instruction) const {
921 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
922 if (it.Current() == instruction) {
923 return true;
924 }
925 }
926 return false;
927}
928
Roland Levillainccc07a92014-09-16 14:48:16 +0100929bool HInstructionList::FoundBefore(const HInstruction* instruction1,
930 const HInstruction* instruction2) const {
931 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
932 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
933 if (it.Current() == instruction1) {
934 return true;
935 }
936 if (it.Current() == instruction2) {
937 return false;
938 }
939 }
940 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
941 return true;
942}
943
Roland Levillain6c82d402014-10-13 16:10:27 +0100944bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
945 if (other_instruction == this) {
946 // An instruction does not strictly dominate itself.
947 return false;
948 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100949 HBasicBlock* block = GetBlock();
950 HBasicBlock* other_block = other_instruction->GetBlock();
951 if (block != other_block) {
952 return GetBlock()->Dominates(other_instruction->GetBlock());
953 } else {
954 // If both instructions are in the same block, ensure this
955 // instruction comes before `other_instruction`.
956 if (IsPhi()) {
957 if (!other_instruction->IsPhi()) {
958 // Phis appear before non phi-instructions so this instruction
959 // dominates `other_instruction`.
960 return true;
961 } else {
962 // There is no order among phis.
963 LOG(FATAL) << "There is no dominance between phis of a same block.";
964 return false;
965 }
966 } else {
967 // `this` is not a phi.
968 if (other_instruction->IsPhi()) {
969 // Phis appear before non phi-instructions so this instruction
970 // does not dominate `other_instruction`.
971 return false;
972 } else {
973 // Check whether this instruction comes before
974 // `other_instruction` in the instruction list.
975 return block->GetInstructions().FoundBefore(this, other_instruction);
976 }
977 }
978 }
979}
980
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000981void HInstruction::RemoveEnvironment() {
982 RemoveEnvironmentUses(this);
983 environment_ = nullptr;
984}
985
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100986void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +0100987 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +0000988 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
989 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100990 HInstruction* user = current->GetUser();
991 size_t input_index = current->GetIndex();
992 user->SetRawInputAt(input_index, other);
993 other->AddUseAt(user, input_index);
994 }
995
David Brazdiled596192015-01-23 10:39:45 +0000996 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
997 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100998 HEnvironment* user = current->GetUser();
999 size_t input_index = current->GetIndex();
1000 user->SetRawEnvAt(input_index, other);
1001 other->AddEnvUseAt(user, input_index);
1002 }
1003
David Brazdiled596192015-01-23 10:39:45 +00001004 uses_.Clear();
1005 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001006}
1007
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001008void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +00001009 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001010 SetRawInputAt(index, replacement);
1011 replacement->AddUseAt(this, index);
1012}
1013
Nicolas Geoffray39468442014-09-02 15:17:15 +01001014size_t HInstruction::EnvironmentSize() const {
1015 return HasEnvironment() ? environment_->Size() : 0;
1016}
1017
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001018void HPhi::AddInput(HInstruction* input) {
1019 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001020 inputs_.push_back(HUserRecord<HInstruction*>(input));
1021 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001022}
1023
David Brazdil2d7352b2015-04-20 14:52:42 +01001024void HPhi::RemoveInputAt(size_t index) {
1025 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001026 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001027 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001028 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001029 InputRecordAt(i).GetUseNode()->SetIndex(i);
1030 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001031}
1032
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001033#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001034void H##name::Accept(HGraphVisitor* visitor) { \
1035 visitor->Visit##name(this); \
1036}
1037
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001038FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001039
1040#undef DEFINE_ACCEPT
1041
1042void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001043 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1044 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001045 if (block != nullptr) {
1046 VisitBasicBlock(block);
1047 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001048 }
1049}
1050
Roland Levillain633021e2014-10-01 14:12:25 +01001051void HGraphVisitor::VisitReversePostOrder() {
1052 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1053 VisitBasicBlock(it.Current());
1054 }
1055}
1056
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001057void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001058 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001059 it.Current()->Accept(this);
1060 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001061 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001062 it.Current()->Accept(this);
1063 }
1064}
1065
Mark Mendelle82549b2015-05-06 10:55:34 -04001066HConstant* HTypeConversion::TryStaticEvaluation() const {
1067 HGraph* graph = GetBlock()->GetGraph();
1068 if (GetInput()->IsIntConstant()) {
1069 int32_t value = GetInput()->AsIntConstant()->GetValue();
1070 switch (GetResultType()) {
1071 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001072 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001073 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001074 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001075 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001076 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001077 default:
1078 return nullptr;
1079 }
1080 } else if (GetInput()->IsLongConstant()) {
1081 int64_t value = GetInput()->AsLongConstant()->GetValue();
1082 switch (GetResultType()) {
1083 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001084 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001085 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001086 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001087 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001088 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001089 default:
1090 return nullptr;
1091 }
1092 } else if (GetInput()->IsFloatConstant()) {
1093 float value = GetInput()->AsFloatConstant()->GetValue();
1094 switch (GetResultType()) {
1095 case Primitive::kPrimInt:
1096 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001097 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001098 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001099 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001100 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001101 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1102 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001103 case Primitive::kPrimLong:
1104 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001105 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001106 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001107 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001108 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001109 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1110 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001111 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001112 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001113 default:
1114 return nullptr;
1115 }
1116 } else if (GetInput()->IsDoubleConstant()) {
1117 double value = GetInput()->AsDoubleConstant()->GetValue();
1118 switch (GetResultType()) {
1119 case Primitive::kPrimInt:
1120 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001121 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001122 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001123 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001124 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001125 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1126 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001127 case Primitive::kPrimLong:
1128 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001129 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001130 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001131 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001132 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001133 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1134 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001135 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001136 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001137 default:
1138 return nullptr;
1139 }
1140 }
1141 return nullptr;
1142}
1143
Roland Levillain9240d6a2014-10-20 16:47:04 +01001144HConstant* HUnaryOperation::TryStaticEvaluation() const {
1145 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001146 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001147 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001148 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001149 } else if (kEnableFloatingPointStaticEvaluation) {
1150 if (GetInput()->IsFloatConstant()) {
1151 return Evaluate(GetInput()->AsFloatConstant());
1152 } else if (GetInput()->IsDoubleConstant()) {
1153 return Evaluate(GetInput()->AsDoubleConstant());
1154 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001155 }
1156 return nullptr;
1157}
1158
1159HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001160 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1161 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001162 } else if (GetLeft()->IsLongConstant()) {
1163 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001164 // The binop(long, int) case is only valid for shifts and rotations.
1165 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001166 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1167 } else if (GetRight()->IsLongConstant()) {
1168 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001169 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001170 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001171 // The binop(null, null) case is only valid for equal and not-equal conditions.
1172 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001173 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001174 } else if (kEnableFloatingPointStaticEvaluation) {
1175 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1176 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1177 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1178 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1179 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001180 }
1181 return nullptr;
1182}
Dave Allison20dfc792014-06-16 20:44:29 -07001183
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001184HConstant* HBinaryOperation::GetConstantRight() const {
1185 if (GetRight()->IsConstant()) {
1186 return GetRight()->AsConstant();
1187 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1188 return GetLeft()->AsConstant();
1189 } else {
1190 return nullptr;
1191 }
1192}
1193
1194// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001195// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001196HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1197 HInstruction* most_constant_right = GetConstantRight();
1198 if (most_constant_right == nullptr) {
1199 return nullptr;
1200 } else if (most_constant_right == GetLeft()) {
1201 return GetRight();
1202 } else {
1203 return GetLeft();
1204 }
1205}
1206
Roland Levillain31dd3d62016-02-16 12:21:02 +00001207std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1208 switch (rhs) {
1209 case ComparisonBias::kNoBias:
1210 return os << "no_bias";
1211 case ComparisonBias::kGtBias:
1212 return os << "gt_bias";
1213 case ComparisonBias::kLtBias:
1214 return os << "lt_bias";
1215 default:
1216 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1217 UNREACHABLE();
1218 }
1219}
1220
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001221bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1222 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001223}
1224
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001225bool HInstruction::Equals(HInstruction* other) const {
1226 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001227 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001228 if (!InstructionDataEquals(other)) return false;
1229 if (GetType() != other->GetType()) return false;
1230 if (InputCount() != other->InputCount()) return false;
1231
1232 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1233 if (InputAt(i) != other->InputAt(i)) return false;
1234 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001235 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001236 return true;
1237}
1238
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001239std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1240#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1241 switch (rhs) {
1242 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1243 default:
1244 os << "Unknown instruction kind " << static_cast<int>(rhs);
1245 break;
1246 }
1247#undef DECLARE_CASE
1248 return os;
1249}
1250
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001251void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001252 next_->previous_ = previous_;
1253 if (previous_ != nullptr) {
1254 previous_->next_ = next_;
1255 }
1256 if (block_->instructions_.first_instruction_ == this) {
1257 block_->instructions_.first_instruction_ = next_;
1258 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001259 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001260
1261 previous_ = cursor->previous_;
1262 if (previous_ != nullptr) {
1263 previous_->next_ = this;
1264 }
1265 next_ = cursor;
1266 cursor->previous_ = this;
1267 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001268
1269 if (block_->instructions_.first_instruction_ == cursor) {
1270 block_->instructions_.first_instruction_ = this;
1271 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001272}
1273
Vladimir Markofb337ea2015-11-25 15:25:10 +00001274void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1275 DCHECK(!CanThrow());
1276 DCHECK(!HasSideEffects());
1277 DCHECK(!HasEnvironmentUses());
1278 DCHECK(HasNonEnvironmentUses());
1279 DCHECK(!IsPhi()); // Makes no sense for Phi.
1280 DCHECK_EQ(InputCount(), 0u);
1281
1282 // Find the target block.
1283 HUseIterator<HInstruction*> uses_it(GetUses());
1284 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1285 uses_it.Advance();
1286 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1287 uses_it.Advance();
1288 }
1289 if (!uses_it.Done()) {
1290 // This instruction has uses in two or more blocks. Find the common dominator.
1291 CommonDominator finder(target_block);
1292 for (; !uses_it.Done(); uses_it.Advance()) {
1293 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1294 }
1295 target_block = finder.Get();
1296 DCHECK(target_block != nullptr);
1297 }
1298 // Move to the first dominator not in a loop.
1299 while (target_block->IsInLoop()) {
1300 target_block = target_block->GetDominator();
1301 DCHECK(target_block != nullptr);
1302 }
1303
1304 // Find insertion position.
1305 HInstruction* insert_pos = nullptr;
1306 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1307 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1308 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1309 insert_pos = uses_it2.Current()->GetUser();
1310 }
1311 }
1312 if (insert_pos == nullptr) {
1313 // No user in `target_block`, insert before the control flow instruction.
1314 insert_pos = target_block->GetLastInstruction();
1315 DCHECK(insert_pos->IsControlFlow());
1316 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1317 if (insert_pos->IsIf()) {
1318 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1319 if (if_input == insert_pos->GetPrevious()) {
1320 insert_pos = if_input;
1321 }
1322 }
1323 }
1324 MoveBefore(insert_pos);
1325}
1326
David Brazdilfc6a86a2015-06-26 10:33:45 +00001327HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001328 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001329 DCHECK_EQ(cursor->GetBlock(), this);
1330
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001331 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1332 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001333 new_block->instructions_.first_instruction_ = cursor;
1334 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1335 instructions_.last_instruction_ = cursor->previous_;
1336 if (cursor->previous_ == nullptr) {
1337 instructions_.first_instruction_ = nullptr;
1338 } else {
1339 cursor->previous_->next_ = nullptr;
1340 cursor->previous_ = nullptr;
1341 }
1342
1343 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001344 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001345
Vladimir Marko60584552015-09-03 13:35:12 +00001346 for (HBasicBlock* successor : GetSuccessors()) {
1347 new_block->successors_.push_back(successor);
1348 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001349 }
Vladimir Marko60584552015-09-03 13:35:12 +00001350 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001351 AddSuccessor(new_block);
1352
David Brazdil56e1acc2015-06-30 15:41:36 +01001353 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001354 return new_block;
1355}
1356
David Brazdild7558da2015-09-22 13:04:14 +01001357HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001358 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001359 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1360
1361 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1362
1363 for (HBasicBlock* predecessor : GetPredecessors()) {
1364 new_block->predecessors_.push_back(predecessor);
1365 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1366 }
1367 predecessors_.clear();
1368 AddPredecessor(new_block);
1369
1370 GetGraph()->AddBlock(new_block);
1371 return new_block;
1372}
1373
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001374HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1375 DCHECK_EQ(cursor->GetBlock(), this);
1376
1377 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1378 cursor->GetDexPc());
1379 new_block->instructions_.first_instruction_ = cursor;
1380 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1381 instructions_.last_instruction_ = cursor->previous_;
1382 if (cursor->previous_ == nullptr) {
1383 instructions_.first_instruction_ = nullptr;
1384 } else {
1385 cursor->previous_->next_ = nullptr;
1386 cursor->previous_ = nullptr;
1387 }
1388
1389 new_block->instructions_.SetBlockOfInstructions(new_block);
1390
1391 for (HBasicBlock* successor : GetSuccessors()) {
1392 new_block->successors_.push_back(successor);
1393 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1394 }
1395 successors_.clear();
1396
1397 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1398 dominated->dominator_ = new_block;
1399 new_block->dominated_blocks_.push_back(dominated);
1400 }
1401 dominated_blocks_.clear();
1402 return new_block;
1403}
1404
1405HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001406 DCHECK(!cursor->IsControlFlow());
1407 DCHECK_NE(instructions_.last_instruction_, cursor);
1408 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001409
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001410 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1411 new_block->instructions_.first_instruction_ = cursor->GetNext();
1412 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1413 cursor->next_->previous_ = nullptr;
1414 cursor->next_ = nullptr;
1415 instructions_.last_instruction_ = cursor;
1416
1417 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001418 for (HBasicBlock* successor : GetSuccessors()) {
1419 new_block->successors_.push_back(successor);
1420 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001421 }
Vladimir Marko60584552015-09-03 13:35:12 +00001422 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001423
Vladimir Marko60584552015-09-03 13:35:12 +00001424 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001425 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001426 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001427 }
Vladimir Marko60584552015-09-03 13:35:12 +00001428 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001429 return new_block;
1430}
1431
David Brazdilec16f792015-08-19 15:04:01 +01001432const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001433 if (EndsWithTryBoundary()) {
1434 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1435 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001436 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001437 return try_boundary;
1438 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001439 DCHECK(IsTryBlock());
1440 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001441 return nullptr;
1442 }
David Brazdilec16f792015-08-19 15:04:01 +01001443 } else if (IsTryBlock()) {
1444 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001445 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001446 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001447 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001448}
1449
David Brazdild7558da2015-09-22 13:04:14 +01001450bool HBasicBlock::HasThrowingInstructions() const {
1451 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1452 if (it.Current()->CanThrow()) {
1453 return true;
1454 }
1455 }
1456 return false;
1457}
1458
David Brazdilfc6a86a2015-06-26 10:33:45 +00001459static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1460 return block.GetPhis().IsEmpty()
1461 && !block.GetInstructions().IsEmpty()
1462 && block.GetFirstInstruction() == block.GetLastInstruction();
1463}
1464
David Brazdil46e2a392015-03-16 17:31:52 +00001465bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001466 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1467}
1468
1469bool HBasicBlock::IsSingleTryBoundary() const {
1470 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001471}
1472
David Brazdil8d5b8b22015-03-24 10:51:52 +00001473bool HBasicBlock::EndsWithControlFlowInstruction() const {
1474 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1475}
1476
David Brazdilb2bd1c52015-03-25 11:17:37 +00001477bool HBasicBlock::EndsWithIf() const {
1478 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1479}
1480
David Brazdilffee3d32015-07-06 11:48:53 +01001481bool HBasicBlock::EndsWithTryBoundary() const {
1482 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1483}
1484
David Brazdilb2bd1c52015-03-25 11:17:37 +00001485bool HBasicBlock::HasSinglePhi() const {
1486 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1487}
1488
David Brazdild26a4112015-11-10 11:07:31 +00001489ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1490 if (EndsWithTryBoundary()) {
1491 // The normal-flow successor of HTryBoundary is always stored at index zero.
1492 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1493 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1494 } else {
1495 // All successors of blocks not ending with TryBoundary are normal.
1496 return ArrayRef<HBasicBlock* const>(successors_);
1497 }
1498}
1499
1500ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1501 if (EndsWithTryBoundary()) {
1502 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1503 } else {
1504 // Blocks not ending with TryBoundary do not have exceptional successors.
1505 return ArrayRef<HBasicBlock* const>();
1506 }
1507}
1508
David Brazdilffee3d32015-07-06 11:48:53 +01001509bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001510 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1511 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1512
1513 size_t length = handlers1.size();
1514 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001515 return false;
1516 }
1517
David Brazdilb618ade2015-07-29 10:31:29 +01001518 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001519 for (size_t i = 0; i < length; ++i) {
1520 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001521 return false;
1522 }
1523 }
1524 return true;
1525}
1526
David Brazdil2d7352b2015-04-20 14:52:42 +01001527size_t HInstructionList::CountSize() const {
1528 size_t size = 0;
1529 HInstruction* current = first_instruction_;
1530 for (; current != nullptr; current = current->GetNext()) {
1531 size++;
1532 }
1533 return size;
1534}
1535
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001536void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1537 for (HInstruction* current = first_instruction_;
1538 current != nullptr;
1539 current = current->GetNext()) {
1540 current->SetBlock(block);
1541 }
1542}
1543
1544void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1545 DCHECK(Contains(cursor));
1546 if (!instruction_list.IsEmpty()) {
1547 if (cursor == last_instruction_) {
1548 last_instruction_ = instruction_list.last_instruction_;
1549 } else {
1550 cursor->next_->previous_ = instruction_list.last_instruction_;
1551 }
1552 instruction_list.last_instruction_->next_ = cursor->next_;
1553 cursor->next_ = instruction_list.first_instruction_;
1554 instruction_list.first_instruction_->previous_ = cursor;
1555 }
1556}
1557
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001558void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1559 DCHECK(Contains(cursor));
1560 if (!instruction_list.IsEmpty()) {
1561 if (cursor == first_instruction_) {
1562 first_instruction_ = instruction_list.first_instruction_;
1563 } else {
1564 cursor->previous_->next_ = instruction_list.first_instruction_;
1565 }
1566 instruction_list.last_instruction_->next_ = cursor;
1567 instruction_list.first_instruction_->previous_ = cursor->previous_;
1568 cursor->previous_ = instruction_list.last_instruction_;
1569 }
1570}
1571
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001572void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001573 if (IsEmpty()) {
1574 first_instruction_ = instruction_list.first_instruction_;
1575 last_instruction_ = instruction_list.last_instruction_;
1576 } else {
1577 AddAfter(last_instruction_, instruction_list);
1578 }
1579}
1580
David Brazdil04ff4e82015-12-10 13:54:52 +00001581// Should be called on instructions in a dead block in post order. This method
1582// assumes `insn` has been removed from all users with the exception of catch
1583// phis because of missing exceptional edges in the graph. It removes the
1584// instruction from catch phi uses, together with inputs of other catch phis in
1585// the catch block at the same index, as these must be dead too.
1586static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1587 DCHECK(!insn->HasEnvironmentUses());
1588 while (insn->HasNonEnvironmentUses()) {
1589 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1590 size_t use_index = use->GetIndex();
1591 HBasicBlock* user_block = use->GetUser()->GetBlock();
1592 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1593 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1594 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1595 }
1596 }
1597}
1598
David Brazdil2d7352b2015-04-20 14:52:42 +01001599void HBasicBlock::DisconnectAndDelete() {
1600 // Dominators must be removed after all the blocks they dominate. This way
1601 // a loop header is removed last, a requirement for correct loop information
1602 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001603 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001604
David Brazdil9eeebf62016-03-24 11:18:15 +00001605 // The following steps gradually remove the block from all its dependants in
1606 // post order (b/27683071).
1607
1608 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1609 // We need to do this before step (4) which destroys the predecessor list.
1610 HBasicBlock* loop_update_start = this;
1611 if (IsLoopHeader()) {
1612 HLoopInformation* loop_info = GetLoopInformation();
1613 // All other blocks in this loop should have been removed because the header
1614 // was their dominator.
1615 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1616 DCHECK(!loop_info->IsIrreducible());
1617 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1618 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1619 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001620 }
1621
David Brazdil9eeebf62016-03-24 11:18:15 +00001622 // (2) Disconnect the block from its successors and update their phis.
1623 for (HBasicBlock* successor : successors_) {
1624 // Delete this block from the list of predecessors.
1625 size_t this_index = successor->GetPredecessorIndexOf(this);
1626 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1627
1628 // Check that `successor` has other predecessors, otherwise `this` is the
1629 // dominator of `successor` which violates the order DCHECKed at the top.
1630 DCHECK(!successor->predecessors_.empty());
1631
1632 // Remove this block's entries in the successor's phis. Skip exceptional
1633 // successors because catch phi inputs do not correspond to predecessor
1634 // blocks but throwing instructions. The inputs of the catch phis will be
1635 // updated in step (3).
1636 if (!successor->IsCatchBlock()) {
1637 if (successor->predecessors_.size() == 1u) {
1638 // The successor has just one predecessor left. Replace phis with the only
1639 // remaining input.
1640 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1641 HPhi* phi = phi_it.Current()->AsPhi();
1642 phi->ReplaceWith(phi->InputAt(1 - this_index));
1643 successor->RemovePhi(phi);
1644 }
1645 } else {
1646 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1647 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1648 }
1649 }
1650 }
1651 }
1652 successors_.clear();
1653
1654 // (3) Remove instructions and phis. Instructions should have no remaining uses
1655 // except in catch phis. If an instruction is used by a catch phi at `index`,
1656 // remove `index`-th input of all phis in the catch block since they are
1657 // guaranteed dead. Note that we may miss dead inputs this way but the
1658 // graph will always remain consistent.
1659 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1660 HInstruction* insn = it.Current();
1661 RemoveUsesOfDeadInstruction(insn);
1662 RemoveInstruction(insn);
1663 }
1664 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1665 HPhi* insn = it.Current()->AsPhi();
1666 RemoveUsesOfDeadInstruction(insn);
1667 RemovePhi(insn);
1668 }
1669
1670 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001671 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001672 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001673 // We should not see any back edges as they would have been removed by step (3).
1674 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1675
David Brazdil2d7352b2015-04-20 14:52:42 +01001676 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001677 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1678 // This block is the only normal-flow successor of the TryBoundary which
1679 // makes `predecessor` dead. Since DCE removes blocks in post order,
1680 // exception handlers of this TryBoundary were already visited and any
1681 // remaining handlers therefore must be live. We remove `predecessor` from
1682 // their list of predecessors.
1683 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1684 while (predecessor->GetSuccessors().size() > 1) {
1685 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1686 DCHECK(handler->IsCatchBlock());
1687 predecessor->RemoveSuccessor(handler);
1688 handler->RemovePredecessor(predecessor);
1689 }
1690 }
1691
David Brazdil2d7352b2015-04-20 14:52:42 +01001692 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001693 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1694 if (num_pred_successors == 1u) {
1695 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001696 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1697 // successor. Replace those with a HGoto.
1698 DCHECK(last_instruction->IsIf() ||
1699 last_instruction->IsPackedSwitch() ||
1700 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001701 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001702 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001703 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001704 // The predecessor has no remaining successors and therefore must be dead.
1705 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001706 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001707 predecessor->RemoveInstruction(last_instruction);
1708 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001709 // There are multiple successors left. The removed block might be a successor
1710 // of a PackedSwitch which will be completely removed (perhaps replaced with
1711 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1712 // case, leave `last_instruction` as is for now.
1713 DCHECK(last_instruction->IsPackedSwitch() ||
1714 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001715 }
David Brazdil46e2a392015-03-16 17:31:52 +00001716 }
Vladimir Marko60584552015-09-03 13:35:12 +00001717 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001718
David Brazdil9eeebf62016-03-24 11:18:15 +00001719 // (5) Remove the block from all loops it is included in. Skip the inner-most
1720 // loop if this is the loop header (see definition of `loop_update_start`)
1721 // because the loop header's predecessor list has been destroyed in step (4).
1722 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1723 HLoopInformation* loop_info = it.Current();
1724 loop_info->Remove(this);
1725 if (loop_info->IsBackEdge(*this)) {
1726 // If this was the last back edge of the loop, we deliberately leave the
1727 // loop in an inconsistent state and will fail GraphChecker unless the
1728 // entire loop is removed during the pass.
1729 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001730 }
1731 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001732
David Brazdil9eeebf62016-03-24 11:18:15 +00001733 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001734 dominator_->RemoveDominatedBlock(this);
1735 SetDominator(nullptr);
1736
David Brazdil9eeebf62016-03-24 11:18:15 +00001737 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001738 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001739 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001740}
1741
1742void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001743 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001744 DCHECK(ContainsElement(dominated_blocks_, other));
1745 DCHECK_EQ(GetSingleSuccessor(), other);
1746 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001747 DCHECK(other->GetPhis().IsEmpty());
1748
David Brazdil2d7352b2015-04-20 14:52:42 +01001749 // Move instructions from `other` to `this`.
1750 DCHECK(EndsWithControlFlowInstruction());
1751 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001752 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001753 other->instructions_.SetBlockOfInstructions(this);
1754 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001755
David Brazdil2d7352b2015-04-20 14:52:42 +01001756 // Remove `other` from the loops it is included in.
1757 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1758 HLoopInformation* loop_info = it.Current();
1759 loop_info->Remove(other);
1760 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001761 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001762 }
1763 }
1764
1765 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001766 successors_.clear();
1767 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001768 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001769 successor->ReplacePredecessor(other, this);
1770 }
1771
David Brazdil2d7352b2015-04-20 14:52:42 +01001772 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001773 RemoveDominatedBlock(other);
1774 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1775 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001776 dominated->SetDominator(this);
1777 }
Vladimir Marko60584552015-09-03 13:35:12 +00001778 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001779 other->dominator_ = nullptr;
1780
1781 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001782 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001783
1784 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001785 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001786 other->SetGraph(nullptr);
1787}
1788
1789void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1790 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001791 DCHECK(GetDominatedBlocks().empty());
1792 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001793 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001794 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001795 DCHECK(other->GetPhis().IsEmpty());
1796 DCHECK(!other->IsInLoop());
1797
1798 // Move instructions from `other` to `this`.
1799 instructions_.Add(other->GetInstructions());
1800 other->instructions_.SetBlockOfInstructions(this);
1801
1802 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001803 successors_.clear();
1804 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001805 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001806 successor->ReplacePredecessor(other, this);
1807 }
1808
1809 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001810 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1811 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001812 dominated->SetDominator(this);
1813 }
Vladimir Marko60584552015-09-03 13:35:12 +00001814 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001815 other->dominator_ = nullptr;
1816 other->graph_ = nullptr;
1817}
1818
1819void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001820 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001821 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001822 predecessor->ReplaceSuccessor(this, other);
1823 }
Vladimir Marko60584552015-09-03 13:35:12 +00001824 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001825 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001826 successor->ReplacePredecessor(this, other);
1827 }
Vladimir Marko60584552015-09-03 13:35:12 +00001828 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1829 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001830 }
1831 GetDominator()->ReplaceDominatedBlock(this, other);
1832 other->SetDominator(GetDominator());
1833 dominator_ = nullptr;
1834 graph_ = nullptr;
1835}
1836
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001837void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001838 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001839 DCHECK(block->GetSuccessors().empty());
1840 DCHECK(block->GetPredecessors().empty());
1841 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001842 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001843 DCHECK(block->GetInstructions().IsEmpty());
1844 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001845
David Brazdilc7af85d2015-05-26 12:05:55 +01001846 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06001847 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01001848 }
1849
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001850 RemoveElement(reverse_post_order_, block);
1851 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00001852 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01001853}
1854
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001855void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
1856 HBasicBlock* reference,
1857 bool replace_if_back_edge) {
1858 if (block->IsLoopHeader()) {
1859 // Clear the information of which blocks are contained in that loop. Since the
1860 // information is stored as a bit vector based on block ids, we have to update
1861 // it, as those block ids were specific to the callee graph and we are now adding
1862 // these blocks to the caller graph.
1863 block->GetLoopInformation()->ClearAllBlocks();
1864 }
1865
1866 // If not already in a loop, update the loop information.
1867 if (!block->IsInLoop()) {
1868 block->SetLoopInformation(reference->GetLoopInformation());
1869 }
1870
1871 // If the block is in a loop, update all its outward loops.
1872 HLoopInformation* loop_info = block->GetLoopInformation();
1873 if (loop_info != nullptr) {
1874 for (HLoopInformationOutwardIterator loop_it(*block);
1875 !loop_it.Done();
1876 loop_it.Advance()) {
1877 loop_it.Current()->Add(block);
1878 }
1879 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
1880 loop_info->ReplaceBackEdge(reference, block);
1881 }
1882 }
1883
1884 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
1885 TryCatchInformation* try_catch_info = reference->IsTryBlock()
1886 ? reference->GetTryCatchInformation()
1887 : nullptr;
1888 block->SetTryCatchInformation(try_catch_info);
1889}
1890
Calin Juravle2e768302015-07-28 14:41:11 +00001891HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001892 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001893 // Update the environments in this graph to have the invoke's environment
1894 // as parent.
1895 {
1896 HReversePostOrderIterator it(*this);
1897 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1898 for (; !it.Done(); it.Advance()) {
1899 HBasicBlock* block = it.Current();
1900 for (HInstructionIterator instr_it(block->GetInstructions());
1901 !instr_it.Done();
1902 instr_it.Advance()) {
1903 HInstruction* current = instr_it.Current();
1904 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00001905 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001906 current->GetEnvironment()->SetAndCopyParentChain(
1907 outer_graph->GetArena(), invoke->GetEnvironment());
1908 }
1909 }
1910 }
1911 }
1912 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1913 if (HasBoundsChecks()) {
1914 outer_graph->SetHasBoundsChecks(true);
1915 }
1916
Calin Juravle2e768302015-07-28 14:41:11 +00001917 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001918 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001919 // Simple case of an entry block, a body block, and an exit block.
1920 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001921 HBasicBlock* body = GetBlocks()[1];
1922 DCHECK(GetBlocks()[0]->IsEntryBlock());
1923 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001924 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001925 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001926 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001927
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001928 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
1929 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001930 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001931
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001932 // Replace the invoke with the return value of the inlined graph.
1933 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001934 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001935 } else {
1936 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001937 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001938
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001939 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001940 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001941 // Need to inline multiple blocks. We split `invoke`'s block
1942 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001943 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001944 // with the second half.
1945 ArenaAllocator* allocator = outer_graph->GetArena();
1946 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001947 // Note that we split before the invoke only to simplify polymorphic inlining.
1948 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001949
Vladimir Markoec7802a2015-10-01 20:57:57 +01001950 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001951 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001952 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001953 exit_block_->ReplaceWith(to);
1954
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001955 // Update the meta information surrounding blocks:
1956 // (1) the graph they are now in,
1957 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001958 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05001959 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001960 // Note that we do not need to update catch phi inputs because they
1961 // correspond to the register file of the outer method which the inlinee
1962 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001963
1964 // We don't add the entry block, the exit block, and the first block, which
1965 // has been merged with `at`.
1966 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1967
1968 // We add the `to` block.
1969 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001970 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001971 + kNumberOfNewBlocksInCaller;
1972
1973 // Find the location of `at` in the outer graph's reverse post order. The new
1974 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001975 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001976 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1977
David Brazdil95177982015-10-30 12:56:58 -05001978 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1979 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001980 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1981 HBasicBlock* current = it.Current();
1982 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05001983 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001984 DCHECK(current->GetGraph() == this);
1985 current->SetGraph(outer_graph);
1986 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001987 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001988 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001989 }
1990 }
1991
David Brazdil95177982015-10-30 12:56:58 -05001992 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001993 to->SetGraph(outer_graph);
1994 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001995 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001996 // Only `to` can become a back edge, as the inlined blocks
1997 // are predecessors of `to`.
1998 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00001999
David Brazdil3f523062016-02-29 16:53:33 +00002000 // Update all predecessors of the exit block (now the `to` block)
2001 // to not `HReturn` but `HGoto` instead.
2002 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
2003 if (to->GetPredecessors().size() == 1) {
2004 HBasicBlock* predecessor = to->GetPredecessors()[0];
2005 HInstruction* last = predecessor->GetLastInstruction();
2006 if (!returns_void) {
2007 return_value = last->InputAt(0);
2008 }
2009 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2010 predecessor->RemoveInstruction(last);
2011 } else {
2012 if (!returns_void) {
2013 // There will be multiple returns.
2014 return_value = new (allocator) HPhi(
2015 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2016 to->AddPhi(return_value->AsPhi());
2017 }
2018 for (HBasicBlock* predecessor : to->GetPredecessors()) {
2019 HInstruction* last = predecessor->GetLastInstruction();
2020 if (!returns_void) {
2021 DCHECK(last->IsReturn());
2022 return_value->AsPhi()->AddInput(last->InputAt(0));
2023 }
2024 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2025 predecessor->RemoveInstruction(last);
2026 }
2027 }
2028 }
David Brazdil05144f42015-04-16 15:18:00 +01002029
2030 // Walk over the entry block and:
2031 // - Move constants from the entry block to the outer_graph's entry block,
2032 // - Replace HParameterValue instructions with their real value.
2033 // - Remove suspend checks, that hold an environment.
2034 // We must do this after the other blocks have been inlined, otherwise ids of
2035 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002036 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002037 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2038 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002039 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002040 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002041 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002042 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002043 replacement = outer_graph->GetIntConstant(
2044 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002045 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002046 replacement = outer_graph->GetLongConstant(
2047 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002048 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002049 replacement = outer_graph->GetFloatConstant(
2050 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002051 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002052 replacement = outer_graph->GetDoubleConstant(
2053 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002054 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002055 if (kIsDebugBuild
2056 && invoke->IsInvokeStaticOrDirect()
2057 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2058 // Ensure we do not use the last input of `invoke`, as it
2059 // contains a clinit check which is not an actual argument.
2060 size_t last_input_index = invoke->InputCount() - 1;
2061 DCHECK(parameter_index != last_input_index);
2062 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002063 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002064 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002065 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002066 } else {
2067 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2068 entry_block_->RemoveInstruction(current);
2069 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002070 if (replacement != nullptr) {
2071 current->ReplaceWith(replacement);
2072 // If the current is the return value then we need to update the latter.
2073 if (current == return_value) {
2074 DCHECK_EQ(entry_block_, return_value->GetBlock());
2075 return_value = replacement;
2076 }
2077 }
2078 }
2079
Calin Juravle2e768302015-07-28 14:41:11 +00002080 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002081}
2082
Mingyao Yang3584bce2015-05-19 16:01:59 -07002083/*
2084 * Loop will be transformed to:
2085 * old_pre_header
2086 * |
2087 * if_block
2088 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002089 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002090 * \ /
2091 * new_pre_header
2092 * |
2093 * header
2094 */
2095void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2096 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002097 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002098
Aart Bik3fc7f352015-11-20 22:03:03 -08002099 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002100 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002101 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2102 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002103 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2104 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002105 AddBlock(true_block);
2106 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002107 AddBlock(new_pre_header);
2108
Aart Bik3fc7f352015-11-20 22:03:03 -08002109 header->ReplacePredecessor(old_pre_header, new_pre_header);
2110 old_pre_header->successors_.clear();
2111 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002112
Aart Bik3fc7f352015-11-20 22:03:03 -08002113 old_pre_header->AddSuccessor(if_block);
2114 if_block->AddSuccessor(true_block); // True successor
2115 if_block->AddSuccessor(false_block); // False successor
2116 true_block->AddSuccessor(new_pre_header);
2117 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002118
Aart Bik3fc7f352015-11-20 22:03:03 -08002119 old_pre_header->dominated_blocks_.push_back(if_block);
2120 if_block->SetDominator(old_pre_header);
2121 if_block->dominated_blocks_.push_back(true_block);
2122 true_block->SetDominator(if_block);
2123 if_block->dominated_blocks_.push_back(false_block);
2124 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002125 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002126 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002127 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002128 header->SetDominator(new_pre_header);
2129
Aart Bik3fc7f352015-11-20 22:03:03 -08002130 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002131 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002132 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002133 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002134 reverse_post_order_[index_of_header++] = true_block;
2135 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002136 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002137
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002138 // The pre_header can never be a back edge of a loop.
2139 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2140 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2141 UpdateLoopAndTryInformationOfNewBlock(
2142 if_block, old_pre_header, /* replace_if_back_edge */ false);
2143 UpdateLoopAndTryInformationOfNewBlock(
2144 true_block, old_pre_header, /* replace_if_back_edge */ false);
2145 UpdateLoopAndTryInformationOfNewBlock(
2146 false_block, old_pre_header, /* replace_if_back_edge */ false);
2147 UpdateLoopAndTryInformationOfNewBlock(
2148 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002149}
2150
David Brazdilf5552582015-12-27 13:36:12 +00002151static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2152 SHARED_REQUIRES(Locks::mutator_lock_) {
2153 if (rti.IsValid()) {
2154 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2155 << " upper_bound_rti: " << upper_bound_rti
2156 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002157 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2158 << " upper_bound_rti: " << upper_bound_rti
2159 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002160 }
2161}
2162
Calin Juravle2e768302015-07-28 14:41:11 +00002163void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2164 if (kIsDebugBuild) {
2165 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2166 ScopedObjectAccess soa(Thread::Current());
2167 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2168 if (IsBoundType()) {
2169 // Having the test here spares us from making the method virtual just for
2170 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002171 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002172 }
2173 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002174 reference_type_handle_ = rti.GetTypeHandle();
2175 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002176}
2177
David Brazdilf5552582015-12-27 13:36:12 +00002178void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2179 if (kIsDebugBuild) {
2180 ScopedObjectAccess soa(Thread::Current());
2181 DCHECK(upper_bound.IsValid());
2182 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2183 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2184 }
2185 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002186 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002187}
2188
Vladimir Markoa1de9182016-02-25 11:37:38 +00002189ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002190 if (kIsDebugBuild) {
2191 ScopedObjectAccess soa(Thread::Current());
2192 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002193 if (!is_exact) {
2194 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2195 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2196 }
Calin Juravle2e768302015-07-28 14:41:11 +00002197 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002198 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002199}
2200
Calin Juravleacf735c2015-02-12 15:25:22 +00002201std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2202 ScopedObjectAccess soa(Thread::Current());
2203 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002204 << " is_valid=" << rhs.IsValid()
2205 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002206 << " is_exact=" << rhs.IsExact()
2207 << " ]";
2208 return os;
2209}
2210
Mark Mendellc4701932015-04-10 13:18:51 -04002211bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2212 // For now, assume that instructions in different blocks may use the
2213 // environment.
2214 // TODO: Use the control flow to decide if this is true.
2215 if (GetBlock() != other->GetBlock()) {
2216 return true;
2217 }
2218
2219 // We know that we are in the same block. Walk from 'this' to 'other',
2220 // checking to see if there is any instruction with an environment.
2221 HInstruction* current = this;
2222 for (; current != other && current != nullptr; current = current->GetNext()) {
2223 // This is a conservative check, as the instruction result may not be in
2224 // the referenced environment.
2225 if (current->HasEnvironment()) {
2226 return true;
2227 }
2228 }
2229
2230 // We should have been called with 'this' before 'other' in the block.
2231 // Just confirm this.
2232 DCHECK(current != nullptr);
2233 return false;
2234}
2235
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002236void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002237 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2238 IntrinsicSideEffects side_effects,
2239 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002240 intrinsic_ = intrinsic;
2241 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002242
Aart Bik5d75afe2015-12-14 11:57:01 -08002243 // Adjust method's side effects from intrinsic table.
2244 switch (side_effects) {
2245 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2246 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2247 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2248 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2249 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002250
2251 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2252 opt.SetDoesNotNeedDexCache();
2253 opt.SetDoesNotNeedEnvironment();
2254 } else {
2255 // If we need an environment, that means there will be a call, which can trigger GC.
2256 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2257 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002258 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002259 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002260}
2261
David Brazdil6de19382016-01-08 17:37:10 +00002262bool HNewInstance::IsStringAlloc() const {
2263 ScopedObjectAccess soa(Thread::Current());
2264 return GetReferenceTypeInfo().IsStringClass();
2265}
2266
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002267bool HInvoke::NeedsEnvironment() const {
2268 if (!IsIntrinsic()) {
2269 return true;
2270 }
2271 IntrinsicOptimizations opt(*this);
2272 return !opt.GetDoesNotNeedEnvironment();
2273}
2274
Vladimir Markodc151b22015-10-15 18:02:30 +01002275bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2276 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002277 return false;
2278 }
2279 if (!IsIntrinsic()) {
2280 return true;
2281 }
2282 IntrinsicOptimizations opt(*this);
2283 return !opt.GetDoesNotNeedDexCache();
2284}
2285
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002286void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2287 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2288 input->AddUseAt(this, index);
2289 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2290 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2291 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2292 InputRecordAt(i).GetUseNode()->SetIndex(i);
2293 }
2294}
2295
Vladimir Markob554b5a2015-11-06 12:57:55 +00002296void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2297 RemoveAsUserOfInput(index);
2298 inputs_.erase(inputs_.begin() + index);
2299 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2300 for (size_t i = index, e = InputCount(); i < e; ++i) {
2301 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2302 InputRecordAt(i).GetUseNode()->SetIndex(i);
2303 }
2304}
2305
Vladimir Markof64242a2015-12-01 14:58:23 +00002306std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2307 switch (rhs) {
2308 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2309 return os << "string_init";
2310 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2311 return os << "recursive";
2312 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2313 return os << "direct";
2314 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2315 return os << "direct_fixup";
2316 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2317 return os << "dex_cache_pc_relative";
2318 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2319 return os << "dex_cache_via_method";
2320 default:
2321 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2322 UNREACHABLE();
2323 }
2324}
2325
Vladimir Markofbb184a2015-11-13 14:47:00 +00002326std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2327 switch (rhs) {
2328 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2329 return os << "explicit";
2330 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2331 return os << "implicit";
2332 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2333 return os << "none";
2334 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002335 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2336 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002337 }
2338}
2339
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002340bool HLoadString::InstructionDataEquals(HInstruction* other) const {
2341 HLoadString* other_load_string = other->AsLoadString();
2342 if (string_index_ != other_load_string->string_index_ ||
2343 GetPackedFields() != other_load_string->GetPackedFields()) {
2344 return false;
2345 }
2346 LoadKind load_kind = GetLoadKind();
2347 if (HasAddress(load_kind)) {
2348 return GetAddress() == other_load_string->GetAddress();
2349 } else if (HasStringReference(load_kind)) {
2350 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2351 } else {
2352 DCHECK(HasDexCacheReference(load_kind)) << load_kind;
2353 // If the string indexes and dex files are the same, dex cache element offsets
2354 // must also be the same, so we don't need to compare them.
2355 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2356 }
2357}
2358
2359void HLoadString::SetLoadKindInternal(LoadKind load_kind) {
2360 // Once sharpened, the load kind should not be changed again.
2361 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2362 SetPackedField<LoadKindField>(load_kind);
2363
2364 if (load_kind != LoadKind::kDexCacheViaMethod) {
2365 RemoveAsUserOfInput(0u);
2366 SetRawInputAt(0u, nullptr);
2367 }
2368 if (!NeedsEnvironment()) {
2369 RemoveEnvironment();
2370 }
2371}
2372
2373std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2374 switch (rhs) {
2375 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2376 return os << "BootImageLinkTimeAddress";
2377 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2378 return os << "BootImageLinkTimePcRelative";
2379 case HLoadString::LoadKind::kBootImageAddress:
2380 return os << "BootImageAddress";
2381 case HLoadString::LoadKind::kDexCacheAddress:
2382 return os << "DexCacheAddress";
2383 case HLoadString::LoadKind::kDexCachePcRelative:
2384 return os << "DexCachePcRelative";
2385 case HLoadString::LoadKind::kDexCacheViaMethod:
2386 return os << "DexCacheViaMethod";
2387 default:
2388 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2389 UNREACHABLE();
2390 }
2391}
2392
Mark Mendellc4701932015-04-10 13:18:51 -04002393void HInstruction::RemoveEnvironmentUsers() {
2394 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2395 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2396 HEnvironment* user = user_node->GetUser();
2397 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2398 }
2399 env_uses_.Clear();
2400}
2401
Roland Levillainc9b21f82016-03-23 16:36:59 +00002402// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002403HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2404 ArenaAllocator* allocator = GetArena();
2405
2406 if (cond->IsCondition() &&
2407 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2408 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2409 HInstruction* lhs = cond->InputAt(0);
2410 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002411 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002412 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2413 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2414 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2415 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2416 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2417 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2418 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2419 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2420 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2421 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2422 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002423 default:
2424 LOG(FATAL) << "Unexpected condition";
2425 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002426 }
2427 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2428 return replacement;
2429 } else if (cond->IsIntConstant()) {
2430 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002431 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002432 return GetIntConstant(1);
2433 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002434 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002435 return GetIntConstant(0);
2436 }
2437 } else {
2438 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2439 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2440 return replacement;
2441 }
2442}
2443
Roland Levillainc9285912015-12-18 10:38:42 +00002444std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2445 os << "["
2446 << " source=" << rhs.GetSource()
2447 << " destination=" << rhs.GetDestination()
2448 << " type=" << rhs.GetType()
2449 << " instruction=";
2450 if (rhs.GetInstruction() != nullptr) {
2451 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2452 } else {
2453 os << "null";
2454 }
2455 os << " ]";
2456 return os;
2457}
2458
Roland Levillain86503782016-02-11 19:07:30 +00002459std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2460 switch (rhs) {
2461 case TypeCheckKind::kUnresolvedCheck:
2462 return os << "unresolved_check";
2463 case TypeCheckKind::kExactCheck:
2464 return os << "exact_check";
2465 case TypeCheckKind::kClassHierarchyCheck:
2466 return os << "class_hierarchy_check";
2467 case TypeCheckKind::kAbstractClassCheck:
2468 return os << "abstract_class_check";
2469 case TypeCheckKind::kInterfaceCheck:
2470 return os << "interface_check";
2471 case TypeCheckKind::kArrayObjectCheck:
2472 return os << "array_object_check";
2473 case TypeCheckKind::kArrayCheck:
2474 return os << "array_check";
2475 default:
2476 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2477 UNREACHABLE();
2478 }
2479}
2480
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002481} // namespace art