blob: 5091c7b62665c4f424ced7a2353923cb114d2a1a [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
Vladimir Markofd66c502016-04-18 15:37:01 +0100621 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
622 // When compiling in OSR mode, all loops in the compiled method may be entered
623 // from the interpreter. We treat this OSR entry point just like an extra entry
624 // to an irreducible loop, so we need to mark the method's loops as irreducible.
625 // This does not apply to inlined loops which do not act as OSR entry points.
626 if (suspend_check_ == nullptr) {
627 // Just building the graph in OSR mode, this loop is not inlined. We never build an
628 // inner graph in OSR mode as we can do OSR transition only from the outer method.
629 is_irreducible_loop = true;
630 } else {
631 // Look at the suspend check's environment to determine if the loop was inlined.
632 DCHECK(suspend_check_->HasEnvironment());
633 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
634 is_irreducible_loop = true;
635 }
636 }
637 }
638 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100639 irreducible_ = true;
640 graph->SetHasIrreducibleLoops(true);
641 }
David Brazdila4b8c212015-05-07 09:59:30 +0100642}
643
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100644HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000645 HBasicBlock* block = header_->GetPredecessors()[0];
646 DCHECK(irreducible_ || (block == header_->GetDominator()));
647 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100648}
649
650bool HLoopInformation::Contains(const HBasicBlock& block) const {
651 return blocks_.IsBitSet(block.GetBlockId());
652}
653
654bool HLoopInformation::IsIn(const HLoopInformation& other) const {
655 return other.blocks_.IsBitSet(header_->GetBlockId());
656}
657
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800658bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
659 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700660}
661
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100662size_t HLoopInformation::GetLifetimeEnd() const {
663 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100664 for (HBasicBlock* back_edge : GetBackEdges()) {
665 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100666 }
667 return last_position;
668}
669
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100670bool HBasicBlock::Dominates(HBasicBlock* other) const {
671 // Walk up the dominator tree from `other`, to find out if `this`
672 // is an ancestor.
673 HBasicBlock* current = other;
674 while (current != nullptr) {
675 if (current == this) {
676 return true;
677 }
678 current = current->GetDominator();
679 }
680 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100681}
682
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100683static void UpdateInputsUsers(HInstruction* instruction) {
684 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
685 instruction->InputAt(i)->AddUseAt(instruction, i);
686 }
687 // Environment should be created later.
688 DCHECK(!instruction->HasEnvironment());
689}
690
Roland Levillainccc07a92014-09-16 14:48:16 +0100691void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
692 HInstruction* replacement) {
693 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400694 if (initial->IsControlFlow()) {
695 // We can only replace a control flow instruction with another control flow instruction.
696 DCHECK(replacement->IsControlFlow());
697 DCHECK_EQ(replacement->GetId(), -1);
698 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
699 DCHECK_EQ(initial->GetBlock(), this);
700 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
701 DCHECK(initial->GetUses().IsEmpty());
702 DCHECK(initial->GetEnvUses().IsEmpty());
703 replacement->SetBlock(this);
704 replacement->SetId(GetGraph()->GetNextInstructionId());
705 instructions_.InsertInstructionBefore(replacement, initial);
706 UpdateInputsUsers(replacement);
707 } else {
708 InsertInstructionBefore(replacement, initial);
709 initial->ReplaceWith(replacement);
710 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100711 RemoveInstruction(initial);
712}
713
David Brazdil74eb1b22015-12-14 11:44:01 +0000714void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
715 DCHECK(!cursor->IsPhi());
716 DCHECK(!insn->IsPhi());
717 DCHECK(!insn->IsControlFlow());
718 DCHECK(insn->CanBeMoved());
719 DCHECK(!insn->HasSideEffects());
720
721 HBasicBlock* from_block = insn->GetBlock();
722 HBasicBlock* to_block = cursor->GetBlock();
723 DCHECK(from_block != to_block);
724
725 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
726 insn->SetBlock(to_block);
727 to_block->instructions_.InsertInstructionBefore(insn, cursor);
728}
729
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100730static void Add(HInstructionList* instruction_list,
731 HBasicBlock* block,
732 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000733 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000734 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100735 instruction->SetBlock(block);
736 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100737 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100738 instruction_list->AddInstruction(instruction);
739}
740
741void HBasicBlock::AddInstruction(HInstruction* instruction) {
742 Add(&instructions_, this, instruction);
743}
744
745void HBasicBlock::AddPhi(HPhi* phi) {
746 Add(&phis_, this, phi);
747}
748
David Brazdilc3d743f2015-04-22 13:40:50 +0100749void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
750 DCHECK(!cursor->IsPhi());
751 DCHECK(!instruction->IsPhi());
752 DCHECK_EQ(instruction->GetId(), -1);
753 DCHECK_NE(cursor->GetId(), -1);
754 DCHECK_EQ(cursor->GetBlock(), this);
755 DCHECK(!instruction->IsControlFlow());
756 instruction->SetBlock(this);
757 instruction->SetId(GetGraph()->GetNextInstructionId());
758 UpdateInputsUsers(instruction);
759 instructions_.InsertInstructionBefore(instruction, cursor);
760}
761
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100762void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
763 DCHECK(!cursor->IsPhi());
764 DCHECK(!instruction->IsPhi());
765 DCHECK_EQ(instruction->GetId(), -1);
766 DCHECK_NE(cursor->GetId(), -1);
767 DCHECK_EQ(cursor->GetBlock(), this);
768 DCHECK(!instruction->IsControlFlow());
769 DCHECK(!cursor->IsControlFlow());
770 instruction->SetBlock(this);
771 instruction->SetId(GetGraph()->GetNextInstructionId());
772 UpdateInputsUsers(instruction);
773 instructions_.InsertInstructionAfter(instruction, cursor);
774}
775
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100776void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
777 DCHECK_EQ(phi->GetId(), -1);
778 DCHECK_NE(cursor->GetId(), -1);
779 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100780 phi->SetBlock(this);
781 phi->SetId(GetGraph()->GetNextInstructionId());
782 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100783 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100784}
785
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100786static void Remove(HInstructionList* instruction_list,
787 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000788 HInstruction* instruction,
789 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100790 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100791 instruction->SetBlock(nullptr);
792 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000793 if (ensure_safety) {
794 DCHECK(instruction->GetUses().IsEmpty());
795 DCHECK(instruction->GetEnvUses().IsEmpty());
796 RemoveAsUser(instruction);
797 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100798}
799
David Brazdil1abb4192015-02-17 18:33:36 +0000800void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100801 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000802 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100803}
804
David Brazdil1abb4192015-02-17 18:33:36 +0000805void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
806 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100807}
808
David Brazdilc7508e92015-04-27 13:28:57 +0100809void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
810 if (instruction->IsPhi()) {
811 RemovePhi(instruction->AsPhi(), ensure_safety);
812 } else {
813 RemoveInstruction(instruction, ensure_safety);
814 }
815}
816
Vladimir Marko71bf8092015-09-15 15:33:14 +0100817void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
818 for (size_t i = 0; i < locals.size(); i++) {
819 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100820 SetRawEnvAt(i, instruction);
821 if (instruction != nullptr) {
822 instruction->AddEnvUseAt(this, i);
823 }
824 }
825}
826
David Brazdiled596192015-01-23 10:39:45 +0000827void HEnvironment::CopyFrom(HEnvironment* env) {
828 for (size_t i = 0; i < env->Size(); i++) {
829 HInstruction* instruction = env->GetInstructionAt(i);
830 SetRawEnvAt(i, instruction);
831 if (instruction != nullptr) {
832 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100833 }
David Brazdiled596192015-01-23 10:39:45 +0000834 }
835}
836
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700837void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
838 HBasicBlock* loop_header) {
839 DCHECK(loop_header->IsLoopHeader());
840 for (size_t i = 0; i < env->Size(); i++) {
841 HInstruction* instruction = env->GetInstructionAt(i);
842 SetRawEnvAt(i, instruction);
843 if (instruction == nullptr) {
844 continue;
845 }
846 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
847 // At the end of the loop pre-header, the corresponding value for instruction
848 // is the first input of the phi.
849 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700850 SetRawEnvAt(i, initial);
851 initial->AddEnvUseAt(this, i);
852 } else {
853 instruction->AddEnvUseAt(this, i);
854 }
855 }
856}
857
David Brazdil1abb4192015-02-17 18:33:36 +0000858void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100859 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000860 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100861}
862
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000863HInstruction::InstructionKind HInstruction::GetKind() const {
864 return GetKindInternal();
865}
866
Calin Juravle77520bc2015-01-12 18:45:46 +0000867HInstruction* HInstruction::GetNextDisregardingMoves() const {
868 HInstruction* next = GetNext();
869 while (next != nullptr && next->IsParallelMove()) {
870 next = next->GetNext();
871 }
872 return next;
873}
874
875HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
876 HInstruction* previous = GetPrevious();
877 while (previous != nullptr && previous->IsParallelMove()) {
878 previous = previous->GetPrevious();
879 }
880 return previous;
881}
882
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100883void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000884 if (first_instruction_ == nullptr) {
885 DCHECK(last_instruction_ == nullptr);
886 first_instruction_ = last_instruction_ = instruction;
887 } else {
888 last_instruction_->next_ = instruction;
889 instruction->previous_ = last_instruction_;
890 last_instruction_ = instruction;
891 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000892}
893
David Brazdilc3d743f2015-04-22 13:40:50 +0100894void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
895 DCHECK(Contains(cursor));
896 if (cursor == first_instruction_) {
897 cursor->previous_ = instruction;
898 instruction->next_ = cursor;
899 first_instruction_ = instruction;
900 } else {
901 instruction->previous_ = cursor->previous_;
902 instruction->next_ = cursor;
903 cursor->previous_ = instruction;
904 instruction->previous_->next_ = instruction;
905 }
906}
907
908void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
909 DCHECK(Contains(cursor));
910 if (cursor == last_instruction_) {
911 cursor->next_ = instruction;
912 instruction->previous_ = cursor;
913 last_instruction_ = instruction;
914 } else {
915 instruction->next_ = cursor->next_;
916 instruction->previous_ = cursor;
917 cursor->next_ = instruction;
918 instruction->next_->previous_ = instruction;
919 }
920}
921
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100922void HInstructionList::RemoveInstruction(HInstruction* instruction) {
923 if (instruction->previous_ != nullptr) {
924 instruction->previous_->next_ = instruction->next_;
925 }
926 if (instruction->next_ != nullptr) {
927 instruction->next_->previous_ = instruction->previous_;
928 }
929 if (instruction == first_instruction_) {
930 first_instruction_ = instruction->next_;
931 }
932 if (instruction == last_instruction_) {
933 last_instruction_ = instruction->previous_;
934 }
935}
936
Roland Levillain6b469232014-09-25 10:10:38 +0100937bool HInstructionList::Contains(HInstruction* instruction) const {
938 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
939 if (it.Current() == instruction) {
940 return true;
941 }
942 }
943 return false;
944}
945
Roland Levillainccc07a92014-09-16 14:48:16 +0100946bool HInstructionList::FoundBefore(const HInstruction* instruction1,
947 const HInstruction* instruction2) const {
948 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
949 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
950 if (it.Current() == instruction1) {
951 return true;
952 }
953 if (it.Current() == instruction2) {
954 return false;
955 }
956 }
957 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
958 return true;
959}
960
Roland Levillain6c82d402014-10-13 16:10:27 +0100961bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
962 if (other_instruction == this) {
963 // An instruction does not strictly dominate itself.
964 return false;
965 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100966 HBasicBlock* block = GetBlock();
967 HBasicBlock* other_block = other_instruction->GetBlock();
968 if (block != other_block) {
969 return GetBlock()->Dominates(other_instruction->GetBlock());
970 } else {
971 // If both instructions are in the same block, ensure this
972 // instruction comes before `other_instruction`.
973 if (IsPhi()) {
974 if (!other_instruction->IsPhi()) {
975 // Phis appear before non phi-instructions so this instruction
976 // dominates `other_instruction`.
977 return true;
978 } else {
979 // There is no order among phis.
980 LOG(FATAL) << "There is no dominance between phis of a same block.";
981 return false;
982 }
983 } else {
984 // `this` is not a phi.
985 if (other_instruction->IsPhi()) {
986 // Phis appear before non phi-instructions so this instruction
987 // does not dominate `other_instruction`.
988 return false;
989 } else {
990 // Check whether this instruction comes before
991 // `other_instruction` in the instruction list.
992 return block->GetInstructions().FoundBefore(this, other_instruction);
993 }
994 }
995 }
996}
997
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000998void HInstruction::RemoveEnvironment() {
999 RemoveEnvironmentUses(this);
1000 environment_ = nullptr;
1001}
1002
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001003void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001004 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +00001005 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
1006 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001007 HInstruction* user = current->GetUser();
1008 size_t input_index = current->GetIndex();
1009 user->SetRawInputAt(input_index, other);
1010 other->AddUseAt(user, input_index);
1011 }
1012
David Brazdiled596192015-01-23 10:39:45 +00001013 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
1014 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001015 HEnvironment* user = current->GetUser();
1016 size_t input_index = current->GetIndex();
1017 user->SetRawEnvAt(input_index, other);
1018 other->AddEnvUseAt(user, input_index);
1019 }
1020
David Brazdiled596192015-01-23 10:39:45 +00001021 uses_.Clear();
1022 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001023}
1024
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001025void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +00001026 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001027 SetRawInputAt(index, replacement);
1028 replacement->AddUseAt(this, index);
1029}
1030
Nicolas Geoffray39468442014-09-02 15:17:15 +01001031size_t HInstruction::EnvironmentSize() const {
1032 return HasEnvironment() ? environment_->Size() : 0;
1033}
1034
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001035void HPhi::AddInput(HInstruction* input) {
1036 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001037 inputs_.push_back(HUserRecord<HInstruction*>(input));
1038 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001039}
1040
David Brazdil2d7352b2015-04-20 14:52:42 +01001041void HPhi::RemoveInputAt(size_t index) {
1042 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001043 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001044 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001045 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001046 InputRecordAt(i).GetUseNode()->SetIndex(i);
1047 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001048}
1049
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001050#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001051void H##name::Accept(HGraphVisitor* visitor) { \
1052 visitor->Visit##name(this); \
1053}
1054
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001055FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001056
1057#undef DEFINE_ACCEPT
1058
1059void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001060 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1061 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001062 if (block != nullptr) {
1063 VisitBasicBlock(block);
1064 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001065 }
1066}
1067
Roland Levillain633021e2014-10-01 14:12:25 +01001068void HGraphVisitor::VisitReversePostOrder() {
1069 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1070 VisitBasicBlock(it.Current());
1071 }
1072}
1073
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001074void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001075 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001076 it.Current()->Accept(this);
1077 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001078 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001079 it.Current()->Accept(this);
1080 }
1081}
1082
Mark Mendelle82549b2015-05-06 10:55:34 -04001083HConstant* HTypeConversion::TryStaticEvaluation() const {
1084 HGraph* graph = GetBlock()->GetGraph();
1085 if (GetInput()->IsIntConstant()) {
1086 int32_t value = GetInput()->AsIntConstant()->GetValue();
1087 switch (GetResultType()) {
1088 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001089 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001090 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001091 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001092 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001093 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001094 default:
1095 return nullptr;
1096 }
1097 } else if (GetInput()->IsLongConstant()) {
1098 int64_t value = GetInput()->AsLongConstant()->GetValue();
1099 switch (GetResultType()) {
1100 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001101 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001102 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001103 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001104 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001105 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001106 default:
1107 return nullptr;
1108 }
1109 } else if (GetInput()->IsFloatConstant()) {
1110 float value = GetInput()->AsFloatConstant()->GetValue();
1111 switch (GetResultType()) {
1112 case Primitive::kPrimInt:
1113 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001114 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001115 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001116 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001117 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001118 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1119 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001120 case Primitive::kPrimLong:
1121 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001122 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001123 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001124 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001125 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001126 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1127 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001128 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001129 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001130 default:
1131 return nullptr;
1132 }
1133 } else if (GetInput()->IsDoubleConstant()) {
1134 double value = GetInput()->AsDoubleConstant()->GetValue();
1135 switch (GetResultType()) {
1136 case Primitive::kPrimInt:
1137 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001138 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001139 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001140 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001141 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001142 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1143 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001144 case Primitive::kPrimLong:
1145 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001146 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001147 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001148 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001149 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001150 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1151 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001152 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001153 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001154 default:
1155 return nullptr;
1156 }
1157 }
1158 return nullptr;
1159}
1160
Roland Levillain9240d6a2014-10-20 16:47:04 +01001161HConstant* HUnaryOperation::TryStaticEvaluation() const {
1162 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001163 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001164 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001165 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001166 } else if (kEnableFloatingPointStaticEvaluation) {
1167 if (GetInput()->IsFloatConstant()) {
1168 return Evaluate(GetInput()->AsFloatConstant());
1169 } else if (GetInput()->IsDoubleConstant()) {
1170 return Evaluate(GetInput()->AsDoubleConstant());
1171 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001172 }
1173 return nullptr;
1174}
1175
1176HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001177 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1178 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001179 } else if (GetLeft()->IsLongConstant()) {
1180 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001181 // The binop(long, int) case is only valid for shifts and rotations.
1182 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001183 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1184 } else if (GetRight()->IsLongConstant()) {
1185 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001186 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001187 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001188 // The binop(null, null) case is only valid for equal and not-equal conditions.
1189 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001190 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001191 } else if (kEnableFloatingPointStaticEvaluation) {
1192 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1193 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1194 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1195 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1196 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001197 }
1198 return nullptr;
1199}
Dave Allison20dfc792014-06-16 20:44:29 -07001200
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001201HConstant* HBinaryOperation::GetConstantRight() const {
1202 if (GetRight()->IsConstant()) {
1203 return GetRight()->AsConstant();
1204 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1205 return GetLeft()->AsConstant();
1206 } else {
1207 return nullptr;
1208 }
1209}
1210
1211// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001212// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001213HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1214 HInstruction* most_constant_right = GetConstantRight();
1215 if (most_constant_right == nullptr) {
1216 return nullptr;
1217 } else if (most_constant_right == GetLeft()) {
1218 return GetRight();
1219 } else {
1220 return GetLeft();
1221 }
1222}
1223
Roland Levillain31dd3d62016-02-16 12:21:02 +00001224std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1225 switch (rhs) {
1226 case ComparisonBias::kNoBias:
1227 return os << "no_bias";
1228 case ComparisonBias::kGtBias:
1229 return os << "gt_bias";
1230 case ComparisonBias::kLtBias:
1231 return os << "lt_bias";
1232 default:
1233 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1234 UNREACHABLE();
1235 }
1236}
1237
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001238bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1239 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001240}
1241
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001242bool HInstruction::Equals(HInstruction* other) const {
1243 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001244 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001245 if (!InstructionDataEquals(other)) return false;
1246 if (GetType() != other->GetType()) return false;
1247 if (InputCount() != other->InputCount()) return false;
1248
1249 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1250 if (InputAt(i) != other->InputAt(i)) return false;
1251 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001252 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001253 return true;
1254}
1255
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001256std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1257#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1258 switch (rhs) {
1259 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1260 default:
1261 os << "Unknown instruction kind " << static_cast<int>(rhs);
1262 break;
1263 }
1264#undef DECLARE_CASE
1265 return os;
1266}
1267
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001268void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001269 next_->previous_ = previous_;
1270 if (previous_ != nullptr) {
1271 previous_->next_ = next_;
1272 }
1273 if (block_->instructions_.first_instruction_ == this) {
1274 block_->instructions_.first_instruction_ = next_;
1275 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001276 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001277
1278 previous_ = cursor->previous_;
1279 if (previous_ != nullptr) {
1280 previous_->next_ = this;
1281 }
1282 next_ = cursor;
1283 cursor->previous_ = this;
1284 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001285
1286 if (block_->instructions_.first_instruction_ == cursor) {
1287 block_->instructions_.first_instruction_ = this;
1288 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001289}
1290
Vladimir Markofb337ea2015-11-25 15:25:10 +00001291void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1292 DCHECK(!CanThrow());
1293 DCHECK(!HasSideEffects());
1294 DCHECK(!HasEnvironmentUses());
1295 DCHECK(HasNonEnvironmentUses());
1296 DCHECK(!IsPhi()); // Makes no sense for Phi.
1297 DCHECK_EQ(InputCount(), 0u);
1298
1299 // Find the target block.
1300 HUseIterator<HInstruction*> uses_it(GetUses());
1301 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1302 uses_it.Advance();
1303 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1304 uses_it.Advance();
1305 }
1306 if (!uses_it.Done()) {
1307 // This instruction has uses in two or more blocks. Find the common dominator.
1308 CommonDominator finder(target_block);
1309 for (; !uses_it.Done(); uses_it.Advance()) {
1310 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1311 }
1312 target_block = finder.Get();
1313 DCHECK(target_block != nullptr);
1314 }
1315 // Move to the first dominator not in a loop.
1316 while (target_block->IsInLoop()) {
1317 target_block = target_block->GetDominator();
1318 DCHECK(target_block != nullptr);
1319 }
1320
1321 // Find insertion position.
1322 HInstruction* insert_pos = nullptr;
1323 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1324 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1325 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1326 insert_pos = uses_it2.Current()->GetUser();
1327 }
1328 }
1329 if (insert_pos == nullptr) {
1330 // No user in `target_block`, insert before the control flow instruction.
1331 insert_pos = target_block->GetLastInstruction();
1332 DCHECK(insert_pos->IsControlFlow());
1333 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1334 if (insert_pos->IsIf()) {
1335 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1336 if (if_input == insert_pos->GetPrevious()) {
1337 insert_pos = if_input;
1338 }
1339 }
1340 }
1341 MoveBefore(insert_pos);
1342}
1343
David Brazdilfc6a86a2015-06-26 10:33:45 +00001344HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001345 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001346 DCHECK_EQ(cursor->GetBlock(), this);
1347
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001348 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1349 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001350 new_block->instructions_.first_instruction_ = cursor;
1351 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1352 instructions_.last_instruction_ = cursor->previous_;
1353 if (cursor->previous_ == nullptr) {
1354 instructions_.first_instruction_ = nullptr;
1355 } else {
1356 cursor->previous_->next_ = nullptr;
1357 cursor->previous_ = nullptr;
1358 }
1359
1360 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001361 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001362
Vladimir Marko60584552015-09-03 13:35:12 +00001363 for (HBasicBlock* successor : GetSuccessors()) {
1364 new_block->successors_.push_back(successor);
1365 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001366 }
Vladimir Marko60584552015-09-03 13:35:12 +00001367 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001368 AddSuccessor(new_block);
1369
David Brazdil56e1acc2015-06-30 15:41:36 +01001370 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001371 return new_block;
1372}
1373
David Brazdild7558da2015-09-22 13:04:14 +01001374HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001375 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001376 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1377
1378 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1379
1380 for (HBasicBlock* predecessor : GetPredecessors()) {
1381 new_block->predecessors_.push_back(predecessor);
1382 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1383 }
1384 predecessors_.clear();
1385 AddPredecessor(new_block);
1386
1387 GetGraph()->AddBlock(new_block);
1388 return new_block;
1389}
1390
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001391HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1392 DCHECK_EQ(cursor->GetBlock(), this);
1393
1394 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1395 cursor->GetDexPc());
1396 new_block->instructions_.first_instruction_ = cursor;
1397 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1398 instructions_.last_instruction_ = cursor->previous_;
1399 if (cursor->previous_ == nullptr) {
1400 instructions_.first_instruction_ = nullptr;
1401 } else {
1402 cursor->previous_->next_ = nullptr;
1403 cursor->previous_ = nullptr;
1404 }
1405
1406 new_block->instructions_.SetBlockOfInstructions(new_block);
1407
1408 for (HBasicBlock* successor : GetSuccessors()) {
1409 new_block->successors_.push_back(successor);
1410 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1411 }
1412 successors_.clear();
1413
1414 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1415 dominated->dominator_ = new_block;
1416 new_block->dominated_blocks_.push_back(dominated);
1417 }
1418 dominated_blocks_.clear();
1419 return new_block;
1420}
1421
1422HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001423 DCHECK(!cursor->IsControlFlow());
1424 DCHECK_NE(instructions_.last_instruction_, cursor);
1425 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001426
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001427 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1428 new_block->instructions_.first_instruction_ = cursor->GetNext();
1429 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1430 cursor->next_->previous_ = nullptr;
1431 cursor->next_ = nullptr;
1432 instructions_.last_instruction_ = cursor;
1433
1434 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001435 for (HBasicBlock* successor : GetSuccessors()) {
1436 new_block->successors_.push_back(successor);
1437 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001438 }
Vladimir Marko60584552015-09-03 13:35:12 +00001439 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001440
Vladimir Marko60584552015-09-03 13:35:12 +00001441 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001442 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001443 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001444 }
Vladimir Marko60584552015-09-03 13:35:12 +00001445 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001446 return new_block;
1447}
1448
David Brazdilec16f792015-08-19 15:04:01 +01001449const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001450 if (EndsWithTryBoundary()) {
1451 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1452 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001453 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001454 return try_boundary;
1455 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001456 DCHECK(IsTryBlock());
1457 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001458 return nullptr;
1459 }
David Brazdilec16f792015-08-19 15:04:01 +01001460 } else if (IsTryBlock()) {
1461 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001462 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001463 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001464 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001465}
1466
David Brazdild7558da2015-09-22 13:04:14 +01001467bool HBasicBlock::HasThrowingInstructions() const {
1468 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1469 if (it.Current()->CanThrow()) {
1470 return true;
1471 }
1472 }
1473 return false;
1474}
1475
David Brazdilfc6a86a2015-06-26 10:33:45 +00001476static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1477 return block.GetPhis().IsEmpty()
1478 && !block.GetInstructions().IsEmpty()
1479 && block.GetFirstInstruction() == block.GetLastInstruction();
1480}
1481
David Brazdil46e2a392015-03-16 17:31:52 +00001482bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001483 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1484}
1485
1486bool HBasicBlock::IsSingleTryBoundary() const {
1487 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001488}
1489
David Brazdil8d5b8b22015-03-24 10:51:52 +00001490bool HBasicBlock::EndsWithControlFlowInstruction() const {
1491 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1492}
1493
David Brazdilb2bd1c52015-03-25 11:17:37 +00001494bool HBasicBlock::EndsWithIf() const {
1495 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1496}
1497
David Brazdilffee3d32015-07-06 11:48:53 +01001498bool HBasicBlock::EndsWithTryBoundary() const {
1499 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1500}
1501
David Brazdilb2bd1c52015-03-25 11:17:37 +00001502bool HBasicBlock::HasSinglePhi() const {
1503 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1504}
1505
David Brazdild26a4112015-11-10 11:07:31 +00001506ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1507 if (EndsWithTryBoundary()) {
1508 // The normal-flow successor of HTryBoundary is always stored at index zero.
1509 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1510 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1511 } else {
1512 // All successors of blocks not ending with TryBoundary are normal.
1513 return ArrayRef<HBasicBlock* const>(successors_);
1514 }
1515}
1516
1517ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1518 if (EndsWithTryBoundary()) {
1519 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1520 } else {
1521 // Blocks not ending with TryBoundary do not have exceptional successors.
1522 return ArrayRef<HBasicBlock* const>();
1523 }
1524}
1525
David Brazdilffee3d32015-07-06 11:48:53 +01001526bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001527 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1528 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1529
1530 size_t length = handlers1.size();
1531 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001532 return false;
1533 }
1534
David Brazdilb618ade2015-07-29 10:31:29 +01001535 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001536 for (size_t i = 0; i < length; ++i) {
1537 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001538 return false;
1539 }
1540 }
1541 return true;
1542}
1543
David Brazdil2d7352b2015-04-20 14:52:42 +01001544size_t HInstructionList::CountSize() const {
1545 size_t size = 0;
1546 HInstruction* current = first_instruction_;
1547 for (; current != nullptr; current = current->GetNext()) {
1548 size++;
1549 }
1550 return size;
1551}
1552
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001553void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1554 for (HInstruction* current = first_instruction_;
1555 current != nullptr;
1556 current = current->GetNext()) {
1557 current->SetBlock(block);
1558 }
1559}
1560
1561void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1562 DCHECK(Contains(cursor));
1563 if (!instruction_list.IsEmpty()) {
1564 if (cursor == last_instruction_) {
1565 last_instruction_ = instruction_list.last_instruction_;
1566 } else {
1567 cursor->next_->previous_ = instruction_list.last_instruction_;
1568 }
1569 instruction_list.last_instruction_->next_ = cursor->next_;
1570 cursor->next_ = instruction_list.first_instruction_;
1571 instruction_list.first_instruction_->previous_ = cursor;
1572 }
1573}
1574
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001575void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1576 DCHECK(Contains(cursor));
1577 if (!instruction_list.IsEmpty()) {
1578 if (cursor == first_instruction_) {
1579 first_instruction_ = instruction_list.first_instruction_;
1580 } else {
1581 cursor->previous_->next_ = instruction_list.first_instruction_;
1582 }
1583 instruction_list.last_instruction_->next_ = cursor;
1584 instruction_list.first_instruction_->previous_ = cursor->previous_;
1585 cursor->previous_ = instruction_list.last_instruction_;
1586 }
1587}
1588
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001589void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001590 if (IsEmpty()) {
1591 first_instruction_ = instruction_list.first_instruction_;
1592 last_instruction_ = instruction_list.last_instruction_;
1593 } else {
1594 AddAfter(last_instruction_, instruction_list);
1595 }
1596}
1597
David Brazdil04ff4e82015-12-10 13:54:52 +00001598// Should be called on instructions in a dead block in post order. This method
1599// assumes `insn` has been removed from all users with the exception of catch
1600// phis because of missing exceptional edges in the graph. It removes the
1601// instruction from catch phi uses, together with inputs of other catch phis in
1602// the catch block at the same index, as these must be dead too.
1603static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1604 DCHECK(!insn->HasEnvironmentUses());
1605 while (insn->HasNonEnvironmentUses()) {
1606 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1607 size_t use_index = use->GetIndex();
1608 HBasicBlock* user_block = use->GetUser()->GetBlock();
1609 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1610 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1611 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1612 }
1613 }
1614}
1615
David Brazdil2d7352b2015-04-20 14:52:42 +01001616void HBasicBlock::DisconnectAndDelete() {
1617 // Dominators must be removed after all the blocks they dominate. This way
1618 // a loop header is removed last, a requirement for correct loop information
1619 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001620 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001621
David Brazdil9eeebf62016-03-24 11:18:15 +00001622 // The following steps gradually remove the block from all its dependants in
1623 // post order (b/27683071).
1624
1625 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1626 // We need to do this before step (4) which destroys the predecessor list.
1627 HBasicBlock* loop_update_start = this;
1628 if (IsLoopHeader()) {
1629 HLoopInformation* loop_info = GetLoopInformation();
1630 // All other blocks in this loop should have been removed because the header
1631 // was their dominator.
1632 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1633 DCHECK(!loop_info->IsIrreducible());
1634 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1635 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1636 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001637 }
1638
David Brazdil9eeebf62016-03-24 11:18:15 +00001639 // (2) Disconnect the block from its successors and update their phis.
1640 for (HBasicBlock* successor : successors_) {
1641 // Delete this block from the list of predecessors.
1642 size_t this_index = successor->GetPredecessorIndexOf(this);
1643 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1644
1645 // Check that `successor` has other predecessors, otherwise `this` is the
1646 // dominator of `successor` which violates the order DCHECKed at the top.
1647 DCHECK(!successor->predecessors_.empty());
1648
1649 // Remove this block's entries in the successor's phis. Skip exceptional
1650 // successors because catch phi inputs do not correspond to predecessor
1651 // blocks but throwing instructions. The inputs of the catch phis will be
1652 // updated in step (3).
1653 if (!successor->IsCatchBlock()) {
1654 if (successor->predecessors_.size() == 1u) {
1655 // The successor has just one predecessor left. Replace phis with the only
1656 // remaining input.
1657 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1658 HPhi* phi = phi_it.Current()->AsPhi();
1659 phi->ReplaceWith(phi->InputAt(1 - this_index));
1660 successor->RemovePhi(phi);
1661 }
1662 } else {
1663 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1664 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1665 }
1666 }
1667 }
1668 }
1669 successors_.clear();
1670
1671 // (3) Remove instructions and phis. Instructions should have no remaining uses
1672 // except in catch phis. If an instruction is used by a catch phi at `index`,
1673 // remove `index`-th input of all phis in the catch block since they are
1674 // guaranteed dead. Note that we may miss dead inputs this way but the
1675 // graph will always remain consistent.
1676 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1677 HInstruction* insn = it.Current();
1678 RemoveUsesOfDeadInstruction(insn);
1679 RemoveInstruction(insn);
1680 }
1681 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1682 HPhi* insn = it.Current()->AsPhi();
1683 RemoveUsesOfDeadInstruction(insn);
1684 RemovePhi(insn);
1685 }
1686
1687 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001688 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001689 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001690 // We should not see any back edges as they would have been removed by step (3).
1691 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1692
David Brazdil2d7352b2015-04-20 14:52:42 +01001693 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001694 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1695 // This block is the only normal-flow successor of the TryBoundary which
1696 // makes `predecessor` dead. Since DCE removes blocks in post order,
1697 // exception handlers of this TryBoundary were already visited and any
1698 // remaining handlers therefore must be live. We remove `predecessor` from
1699 // their list of predecessors.
1700 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1701 while (predecessor->GetSuccessors().size() > 1) {
1702 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1703 DCHECK(handler->IsCatchBlock());
1704 predecessor->RemoveSuccessor(handler);
1705 handler->RemovePredecessor(predecessor);
1706 }
1707 }
1708
David Brazdil2d7352b2015-04-20 14:52:42 +01001709 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001710 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1711 if (num_pred_successors == 1u) {
1712 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001713 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1714 // successor. Replace those with a HGoto.
1715 DCHECK(last_instruction->IsIf() ||
1716 last_instruction->IsPackedSwitch() ||
1717 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001718 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001719 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001720 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001721 // The predecessor has no remaining successors and therefore must be dead.
1722 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001723 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001724 predecessor->RemoveInstruction(last_instruction);
1725 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001726 // There are multiple successors left. The removed block might be a successor
1727 // of a PackedSwitch which will be completely removed (perhaps replaced with
1728 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1729 // case, leave `last_instruction` as is for now.
1730 DCHECK(last_instruction->IsPackedSwitch() ||
1731 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001732 }
David Brazdil46e2a392015-03-16 17:31:52 +00001733 }
Vladimir Marko60584552015-09-03 13:35:12 +00001734 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001735
David Brazdil9eeebf62016-03-24 11:18:15 +00001736 // (5) Remove the block from all loops it is included in. Skip the inner-most
1737 // loop if this is the loop header (see definition of `loop_update_start`)
1738 // because the loop header's predecessor list has been destroyed in step (4).
1739 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1740 HLoopInformation* loop_info = it.Current();
1741 loop_info->Remove(this);
1742 if (loop_info->IsBackEdge(*this)) {
1743 // If this was the last back edge of the loop, we deliberately leave the
1744 // loop in an inconsistent state and will fail GraphChecker unless the
1745 // entire loop is removed during the pass.
1746 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001747 }
1748 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001749
David Brazdil9eeebf62016-03-24 11:18:15 +00001750 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001751 dominator_->RemoveDominatedBlock(this);
1752 SetDominator(nullptr);
1753
David Brazdil9eeebf62016-03-24 11:18:15 +00001754 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001755 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001756 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001757}
1758
1759void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001760 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001761 DCHECK(ContainsElement(dominated_blocks_, other));
1762 DCHECK_EQ(GetSingleSuccessor(), other);
1763 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001764 DCHECK(other->GetPhis().IsEmpty());
1765
David Brazdil2d7352b2015-04-20 14:52:42 +01001766 // Move instructions from `other` to `this`.
1767 DCHECK(EndsWithControlFlowInstruction());
1768 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001769 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001770 other->instructions_.SetBlockOfInstructions(this);
1771 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001772
David Brazdil2d7352b2015-04-20 14:52:42 +01001773 // Remove `other` from the loops it is included in.
1774 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1775 HLoopInformation* loop_info = it.Current();
1776 loop_info->Remove(other);
1777 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001778 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001779 }
1780 }
1781
1782 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001783 successors_.clear();
1784 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001785 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001786 successor->ReplacePredecessor(other, this);
1787 }
1788
David Brazdil2d7352b2015-04-20 14:52:42 +01001789 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001790 RemoveDominatedBlock(other);
1791 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1792 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001793 dominated->SetDominator(this);
1794 }
Vladimir Marko60584552015-09-03 13:35:12 +00001795 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001796 other->dominator_ = nullptr;
1797
1798 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001799 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001800
1801 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001802 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001803 other->SetGraph(nullptr);
1804}
1805
1806void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1807 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001808 DCHECK(GetDominatedBlocks().empty());
1809 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001810 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001811 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001812 DCHECK(other->GetPhis().IsEmpty());
1813 DCHECK(!other->IsInLoop());
1814
1815 // Move instructions from `other` to `this`.
1816 instructions_.Add(other->GetInstructions());
1817 other->instructions_.SetBlockOfInstructions(this);
1818
1819 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001820 successors_.clear();
1821 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001822 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001823 successor->ReplacePredecessor(other, this);
1824 }
1825
1826 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001827 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1828 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001829 dominated->SetDominator(this);
1830 }
Vladimir Marko60584552015-09-03 13:35:12 +00001831 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001832 other->dominator_ = nullptr;
1833 other->graph_ = nullptr;
1834}
1835
1836void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001837 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001838 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001839 predecessor->ReplaceSuccessor(this, other);
1840 }
Vladimir Marko60584552015-09-03 13:35:12 +00001841 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001842 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001843 successor->ReplacePredecessor(this, other);
1844 }
Vladimir Marko60584552015-09-03 13:35:12 +00001845 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1846 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001847 }
1848 GetDominator()->ReplaceDominatedBlock(this, other);
1849 other->SetDominator(GetDominator());
1850 dominator_ = nullptr;
1851 graph_ = nullptr;
1852}
1853
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001854void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001855 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001856 DCHECK(block->GetSuccessors().empty());
1857 DCHECK(block->GetPredecessors().empty());
1858 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001859 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001860 DCHECK(block->GetInstructions().IsEmpty());
1861 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001862
David Brazdilc7af85d2015-05-26 12:05:55 +01001863 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06001864 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01001865 }
1866
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001867 RemoveElement(reverse_post_order_, block);
1868 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00001869 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01001870}
1871
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001872void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
1873 HBasicBlock* reference,
1874 bool replace_if_back_edge) {
1875 if (block->IsLoopHeader()) {
1876 // Clear the information of which blocks are contained in that loop. Since the
1877 // information is stored as a bit vector based on block ids, we have to update
1878 // it, as those block ids were specific to the callee graph and we are now adding
1879 // these blocks to the caller graph.
1880 block->GetLoopInformation()->ClearAllBlocks();
1881 }
1882
1883 // If not already in a loop, update the loop information.
1884 if (!block->IsInLoop()) {
1885 block->SetLoopInformation(reference->GetLoopInformation());
1886 }
1887
1888 // If the block is in a loop, update all its outward loops.
1889 HLoopInformation* loop_info = block->GetLoopInformation();
1890 if (loop_info != nullptr) {
1891 for (HLoopInformationOutwardIterator loop_it(*block);
1892 !loop_it.Done();
1893 loop_it.Advance()) {
1894 loop_it.Current()->Add(block);
1895 }
1896 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
1897 loop_info->ReplaceBackEdge(reference, block);
1898 }
1899 }
1900
1901 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
1902 TryCatchInformation* try_catch_info = reference->IsTryBlock()
1903 ? reference->GetTryCatchInformation()
1904 : nullptr;
1905 block->SetTryCatchInformation(try_catch_info);
1906}
1907
Calin Juravle2e768302015-07-28 14:41:11 +00001908HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001909 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001910 // Update the environments in this graph to have the invoke's environment
1911 // as parent.
1912 {
1913 HReversePostOrderIterator it(*this);
1914 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1915 for (; !it.Done(); it.Advance()) {
1916 HBasicBlock* block = it.Current();
1917 for (HInstructionIterator instr_it(block->GetInstructions());
1918 !instr_it.Done();
1919 instr_it.Advance()) {
1920 HInstruction* current = instr_it.Current();
1921 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00001922 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001923 current->GetEnvironment()->SetAndCopyParentChain(
1924 outer_graph->GetArena(), invoke->GetEnvironment());
1925 }
1926 }
1927 }
1928 }
1929 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1930 if (HasBoundsChecks()) {
1931 outer_graph->SetHasBoundsChecks(true);
1932 }
1933
Calin Juravle2e768302015-07-28 14:41:11 +00001934 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001935 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001936 // Simple case of an entry block, a body block, and an exit block.
1937 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001938 HBasicBlock* body = GetBlocks()[1];
1939 DCHECK(GetBlocks()[0]->IsEntryBlock());
1940 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001941 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001942 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001943 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001944
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001945 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
1946 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001947 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001948
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001949 // Replace the invoke with the return value of the inlined graph.
1950 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001951 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001952 } else {
1953 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001954 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001955
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001956 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001957 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001958 // Need to inline multiple blocks. We split `invoke`'s block
1959 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001960 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001961 // with the second half.
1962 ArenaAllocator* allocator = outer_graph->GetArena();
1963 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001964 // Note that we split before the invoke only to simplify polymorphic inlining.
1965 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001966
Vladimir Markoec7802a2015-10-01 20:57:57 +01001967 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001968 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001969 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001970 exit_block_->ReplaceWith(to);
1971
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001972 // Update the meta information surrounding blocks:
1973 // (1) the graph they are now in,
1974 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001975 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05001976 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001977 // Note that we do not need to update catch phi inputs because they
1978 // correspond to the register file of the outer method which the inlinee
1979 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001980
1981 // We don't add the entry block, the exit block, and the first block, which
1982 // has been merged with `at`.
1983 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1984
1985 // We add the `to` block.
1986 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001987 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001988 + kNumberOfNewBlocksInCaller;
1989
1990 // Find the location of `at` in the outer graph's reverse post order. The new
1991 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001992 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001993 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1994
David Brazdil95177982015-10-30 12:56:58 -05001995 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1996 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001997 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1998 HBasicBlock* current = it.Current();
1999 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002000 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002001 DCHECK(current->GetGraph() == this);
2002 current->SetGraph(outer_graph);
2003 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002004 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002005 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002006 }
2007 }
2008
David Brazdil95177982015-10-30 12:56:58 -05002009 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002010 to->SetGraph(outer_graph);
2011 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002012 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002013 // Only `to` can become a back edge, as the inlined blocks
2014 // are predecessors of `to`.
2015 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002016
David Brazdil3f523062016-02-29 16:53:33 +00002017 // Update all predecessors of the exit block (now the `to` block)
2018 // to not `HReturn` but `HGoto` instead.
2019 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
2020 if (to->GetPredecessors().size() == 1) {
2021 HBasicBlock* predecessor = to->GetPredecessors()[0];
2022 HInstruction* last = predecessor->GetLastInstruction();
2023 if (!returns_void) {
2024 return_value = last->InputAt(0);
2025 }
2026 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2027 predecessor->RemoveInstruction(last);
2028 } else {
2029 if (!returns_void) {
2030 // There will be multiple returns.
2031 return_value = new (allocator) HPhi(
2032 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2033 to->AddPhi(return_value->AsPhi());
2034 }
2035 for (HBasicBlock* predecessor : to->GetPredecessors()) {
2036 HInstruction* last = predecessor->GetLastInstruction();
2037 if (!returns_void) {
2038 DCHECK(last->IsReturn());
2039 return_value->AsPhi()->AddInput(last->InputAt(0));
2040 }
2041 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2042 predecessor->RemoveInstruction(last);
2043 }
2044 }
2045 }
David Brazdil05144f42015-04-16 15:18:00 +01002046
2047 // Walk over the entry block and:
2048 // - Move constants from the entry block to the outer_graph's entry block,
2049 // - Replace HParameterValue instructions with their real value.
2050 // - Remove suspend checks, that hold an environment.
2051 // We must do this after the other blocks have been inlined, otherwise ids of
2052 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002053 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002054 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2055 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002056 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002057 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002058 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002059 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002060 replacement = outer_graph->GetIntConstant(
2061 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002062 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002063 replacement = outer_graph->GetLongConstant(
2064 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002065 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002066 replacement = outer_graph->GetFloatConstant(
2067 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002068 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002069 replacement = outer_graph->GetDoubleConstant(
2070 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002071 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002072 if (kIsDebugBuild
2073 && invoke->IsInvokeStaticOrDirect()
2074 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2075 // Ensure we do not use the last input of `invoke`, as it
2076 // contains a clinit check which is not an actual argument.
2077 size_t last_input_index = invoke->InputCount() - 1;
2078 DCHECK(parameter_index != last_input_index);
2079 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002080 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002081 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002082 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002083 } else {
2084 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2085 entry_block_->RemoveInstruction(current);
2086 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002087 if (replacement != nullptr) {
2088 current->ReplaceWith(replacement);
2089 // If the current is the return value then we need to update the latter.
2090 if (current == return_value) {
2091 DCHECK_EQ(entry_block_, return_value->GetBlock());
2092 return_value = replacement;
2093 }
2094 }
2095 }
2096
Calin Juravle2e768302015-07-28 14:41:11 +00002097 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002098}
2099
Mingyao Yang3584bce2015-05-19 16:01:59 -07002100/*
2101 * Loop will be transformed to:
2102 * old_pre_header
2103 * |
2104 * if_block
2105 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002106 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002107 * \ /
2108 * new_pre_header
2109 * |
2110 * header
2111 */
2112void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2113 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002114 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002115
Aart Bik3fc7f352015-11-20 22:03:03 -08002116 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002117 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002118 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2119 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002120 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2121 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002122 AddBlock(true_block);
2123 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002124 AddBlock(new_pre_header);
2125
Aart Bik3fc7f352015-11-20 22:03:03 -08002126 header->ReplacePredecessor(old_pre_header, new_pre_header);
2127 old_pre_header->successors_.clear();
2128 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002129
Aart Bik3fc7f352015-11-20 22:03:03 -08002130 old_pre_header->AddSuccessor(if_block);
2131 if_block->AddSuccessor(true_block); // True successor
2132 if_block->AddSuccessor(false_block); // False successor
2133 true_block->AddSuccessor(new_pre_header);
2134 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002135
Aart Bik3fc7f352015-11-20 22:03:03 -08002136 old_pre_header->dominated_blocks_.push_back(if_block);
2137 if_block->SetDominator(old_pre_header);
2138 if_block->dominated_blocks_.push_back(true_block);
2139 true_block->SetDominator(if_block);
2140 if_block->dominated_blocks_.push_back(false_block);
2141 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002142 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002143 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002144 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002145 header->SetDominator(new_pre_header);
2146
Aart Bik3fc7f352015-11-20 22:03:03 -08002147 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002148 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002149 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002150 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002151 reverse_post_order_[index_of_header++] = true_block;
2152 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002153 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002154
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002155 // The pre_header can never be a back edge of a loop.
2156 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2157 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2158 UpdateLoopAndTryInformationOfNewBlock(
2159 if_block, old_pre_header, /* replace_if_back_edge */ false);
2160 UpdateLoopAndTryInformationOfNewBlock(
2161 true_block, old_pre_header, /* replace_if_back_edge */ false);
2162 UpdateLoopAndTryInformationOfNewBlock(
2163 false_block, old_pre_header, /* replace_if_back_edge */ false);
2164 UpdateLoopAndTryInformationOfNewBlock(
2165 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002166}
2167
David Brazdilf5552582015-12-27 13:36:12 +00002168static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2169 SHARED_REQUIRES(Locks::mutator_lock_) {
2170 if (rti.IsValid()) {
2171 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2172 << " upper_bound_rti: " << upper_bound_rti
2173 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002174 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2175 << " upper_bound_rti: " << upper_bound_rti
2176 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002177 }
2178}
2179
Calin Juravle2e768302015-07-28 14:41:11 +00002180void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2181 if (kIsDebugBuild) {
2182 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2183 ScopedObjectAccess soa(Thread::Current());
2184 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2185 if (IsBoundType()) {
2186 // Having the test here spares us from making the method virtual just for
2187 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002188 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002189 }
2190 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002191 reference_type_handle_ = rti.GetTypeHandle();
2192 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002193}
2194
David Brazdilf5552582015-12-27 13:36:12 +00002195void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2196 if (kIsDebugBuild) {
2197 ScopedObjectAccess soa(Thread::Current());
2198 DCHECK(upper_bound.IsValid());
2199 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2200 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2201 }
2202 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002203 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002204}
2205
Vladimir Markoa1de9182016-02-25 11:37:38 +00002206ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002207 if (kIsDebugBuild) {
2208 ScopedObjectAccess soa(Thread::Current());
2209 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002210 if (!is_exact) {
2211 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2212 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2213 }
Calin Juravle2e768302015-07-28 14:41:11 +00002214 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002215 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002216}
2217
Calin Juravleacf735c2015-02-12 15:25:22 +00002218std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2219 ScopedObjectAccess soa(Thread::Current());
2220 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002221 << " is_valid=" << rhs.IsValid()
2222 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002223 << " is_exact=" << rhs.IsExact()
2224 << " ]";
2225 return os;
2226}
2227
Mark Mendellc4701932015-04-10 13:18:51 -04002228bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2229 // For now, assume that instructions in different blocks may use the
2230 // environment.
2231 // TODO: Use the control flow to decide if this is true.
2232 if (GetBlock() != other->GetBlock()) {
2233 return true;
2234 }
2235
2236 // We know that we are in the same block. Walk from 'this' to 'other',
2237 // checking to see if there is any instruction with an environment.
2238 HInstruction* current = this;
2239 for (; current != other && current != nullptr; current = current->GetNext()) {
2240 // This is a conservative check, as the instruction result may not be in
2241 // the referenced environment.
2242 if (current->HasEnvironment()) {
2243 return true;
2244 }
2245 }
2246
2247 // We should have been called with 'this' before 'other' in the block.
2248 // Just confirm this.
2249 DCHECK(current != nullptr);
2250 return false;
2251}
2252
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002253void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002254 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2255 IntrinsicSideEffects side_effects,
2256 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002257 intrinsic_ = intrinsic;
2258 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002259
Aart Bik5d75afe2015-12-14 11:57:01 -08002260 // Adjust method's side effects from intrinsic table.
2261 switch (side_effects) {
2262 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2263 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2264 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2265 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2266 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002267
2268 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2269 opt.SetDoesNotNeedDexCache();
2270 opt.SetDoesNotNeedEnvironment();
2271 } else {
2272 // If we need an environment, that means there will be a call, which can trigger GC.
2273 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2274 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002275 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002276 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002277}
2278
David Brazdil6de19382016-01-08 17:37:10 +00002279bool HNewInstance::IsStringAlloc() const {
2280 ScopedObjectAccess soa(Thread::Current());
2281 return GetReferenceTypeInfo().IsStringClass();
2282}
2283
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002284bool HInvoke::NeedsEnvironment() const {
2285 if (!IsIntrinsic()) {
2286 return true;
2287 }
2288 IntrinsicOptimizations opt(*this);
2289 return !opt.GetDoesNotNeedEnvironment();
2290}
2291
Vladimir Markodc151b22015-10-15 18:02:30 +01002292bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2293 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002294 return false;
2295 }
2296 if (!IsIntrinsic()) {
2297 return true;
2298 }
2299 IntrinsicOptimizations opt(*this);
2300 return !opt.GetDoesNotNeedDexCache();
2301}
2302
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002303void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2304 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2305 input->AddUseAt(this, index);
2306 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2307 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2308 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2309 InputRecordAt(i).GetUseNode()->SetIndex(i);
2310 }
2311}
2312
Vladimir Markob554b5a2015-11-06 12:57:55 +00002313void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2314 RemoveAsUserOfInput(index);
2315 inputs_.erase(inputs_.begin() + index);
2316 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2317 for (size_t i = index, e = InputCount(); i < e; ++i) {
2318 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2319 InputRecordAt(i).GetUseNode()->SetIndex(i);
2320 }
2321}
2322
Vladimir Markof64242a2015-12-01 14:58:23 +00002323std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2324 switch (rhs) {
2325 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2326 return os << "string_init";
2327 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2328 return os << "recursive";
2329 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2330 return os << "direct";
2331 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2332 return os << "direct_fixup";
2333 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2334 return os << "dex_cache_pc_relative";
2335 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2336 return os << "dex_cache_via_method";
2337 default:
2338 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2339 UNREACHABLE();
2340 }
2341}
2342
Vladimir Markofbb184a2015-11-13 14:47:00 +00002343std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2344 switch (rhs) {
2345 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2346 return os << "explicit";
2347 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2348 return os << "implicit";
2349 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2350 return os << "none";
2351 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002352 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2353 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002354 }
2355}
2356
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002357bool HLoadString::InstructionDataEquals(HInstruction* other) const {
2358 HLoadString* other_load_string = other->AsLoadString();
2359 if (string_index_ != other_load_string->string_index_ ||
2360 GetPackedFields() != other_load_string->GetPackedFields()) {
2361 return false;
2362 }
2363 LoadKind load_kind = GetLoadKind();
2364 if (HasAddress(load_kind)) {
2365 return GetAddress() == other_load_string->GetAddress();
2366 } else if (HasStringReference(load_kind)) {
2367 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2368 } else {
2369 DCHECK(HasDexCacheReference(load_kind)) << load_kind;
2370 // If the string indexes and dex files are the same, dex cache element offsets
2371 // must also be the same, so we don't need to compare them.
2372 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2373 }
2374}
2375
2376void HLoadString::SetLoadKindInternal(LoadKind load_kind) {
2377 // Once sharpened, the load kind should not be changed again.
2378 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2379 SetPackedField<LoadKindField>(load_kind);
2380
2381 if (load_kind != LoadKind::kDexCacheViaMethod) {
2382 RemoveAsUserOfInput(0u);
2383 SetRawInputAt(0u, nullptr);
2384 }
2385 if (!NeedsEnvironment()) {
2386 RemoveEnvironment();
2387 }
2388}
2389
2390std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2391 switch (rhs) {
2392 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2393 return os << "BootImageLinkTimeAddress";
2394 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2395 return os << "BootImageLinkTimePcRelative";
2396 case HLoadString::LoadKind::kBootImageAddress:
2397 return os << "BootImageAddress";
2398 case HLoadString::LoadKind::kDexCacheAddress:
2399 return os << "DexCacheAddress";
2400 case HLoadString::LoadKind::kDexCachePcRelative:
2401 return os << "DexCachePcRelative";
2402 case HLoadString::LoadKind::kDexCacheViaMethod:
2403 return os << "DexCacheViaMethod";
2404 default:
2405 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2406 UNREACHABLE();
2407 }
2408}
2409
Mark Mendellc4701932015-04-10 13:18:51 -04002410void HInstruction::RemoveEnvironmentUsers() {
2411 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2412 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2413 HEnvironment* user = user_node->GetUser();
2414 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2415 }
2416 env_uses_.Clear();
2417}
2418
Roland Levillainc9b21f82016-03-23 16:36:59 +00002419// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002420HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2421 ArenaAllocator* allocator = GetArena();
2422
2423 if (cond->IsCondition() &&
2424 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2425 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2426 HInstruction* lhs = cond->InputAt(0);
2427 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002428 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002429 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2430 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2431 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2432 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2433 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2434 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2435 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2436 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2437 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2438 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2439 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002440 default:
2441 LOG(FATAL) << "Unexpected condition";
2442 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002443 }
2444 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2445 return replacement;
2446 } else if (cond->IsIntConstant()) {
2447 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002448 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002449 return GetIntConstant(1);
2450 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002451 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002452 return GetIntConstant(0);
2453 }
2454 } else {
2455 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2456 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2457 return replacement;
2458 }
2459}
2460
Roland Levillainc9285912015-12-18 10:38:42 +00002461std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2462 os << "["
2463 << " source=" << rhs.GetSource()
2464 << " destination=" << rhs.GetDestination()
2465 << " type=" << rhs.GetType()
2466 << " instruction=";
2467 if (rhs.GetInstruction() != nullptr) {
2468 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2469 } else {
2470 os << "null";
2471 }
2472 os << " ]";
2473 return os;
2474}
2475
Roland Levillain86503782016-02-11 19:07:30 +00002476std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2477 switch (rhs) {
2478 case TypeCheckKind::kUnresolvedCheck:
2479 return os << "unresolved_check";
2480 case TypeCheckKind::kExactCheck:
2481 return os << "exact_check";
2482 case TypeCheckKind::kClassHierarchyCheck:
2483 return os << "class_hierarchy_check";
2484 case TypeCheckKind::kAbstractClassCheck:
2485 return os << "abstract_class_check";
2486 case TypeCheckKind::kInterfaceCheck:
2487 return os << "interface_check";
2488 case TypeCheckKind::kArrayObjectCheck:
2489 return os << "array_object_check";
2490 case TypeCheckKind::kArrayCheck:
2491 return os << "array_check";
2492 default:
2493 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2494 UNREACHABLE();
2495 }
2496}
2497
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002498} // namespace art