blob: 679c274e621e5e37671303aabbf2cad9b5b4dc9d [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);
David Brazdil5a620592016-05-05 11:27:03 +0100612 // Stop marking blocks at the loop header.
613 visited.SetBit(header_->GetBlockId());
614
David Brazdilc2e8af92016-04-05 17:15:19 +0100615 for (HBasicBlock* back_edge : GetBackEdges()) {
616 PopulateIrreducibleRecursive(back_edge, &visited);
617 }
618 } else {
619 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000620 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100621 }
David Brazdila4b8c212015-05-07 09:59:30 +0100622 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100623
Vladimir Markofd66c502016-04-18 15:37:01 +0100624 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
625 // When compiling in OSR mode, all loops in the compiled method may be entered
626 // from the interpreter. We treat this OSR entry point just like an extra entry
627 // to an irreducible loop, so we need to mark the method's loops as irreducible.
628 // This does not apply to inlined loops which do not act as OSR entry points.
629 if (suspend_check_ == nullptr) {
630 // Just building the graph in OSR mode, this loop is not inlined. We never build an
631 // inner graph in OSR mode as we can do OSR transition only from the outer method.
632 is_irreducible_loop = true;
633 } else {
634 // Look at the suspend check's environment to determine if the loop was inlined.
635 DCHECK(suspend_check_->HasEnvironment());
636 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
637 is_irreducible_loop = true;
638 }
639 }
640 }
641 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100642 irreducible_ = true;
643 graph->SetHasIrreducibleLoops(true);
644 }
David Brazdila4b8c212015-05-07 09:59:30 +0100645}
646
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100647HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000648 HBasicBlock* block = header_->GetPredecessors()[0];
649 DCHECK(irreducible_ || (block == header_->GetDominator()));
650 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100651}
652
653bool HLoopInformation::Contains(const HBasicBlock& block) const {
654 return blocks_.IsBitSet(block.GetBlockId());
655}
656
657bool HLoopInformation::IsIn(const HLoopInformation& other) const {
658 return other.blocks_.IsBitSet(header_->GetBlockId());
659}
660
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800661bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
662 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700663}
664
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100665size_t HLoopInformation::GetLifetimeEnd() const {
666 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100667 for (HBasicBlock* back_edge : GetBackEdges()) {
668 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100669 }
670 return last_position;
671}
672
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100673bool HBasicBlock::Dominates(HBasicBlock* other) const {
674 // Walk up the dominator tree from `other`, to find out if `this`
675 // is an ancestor.
676 HBasicBlock* current = other;
677 while (current != nullptr) {
678 if (current == this) {
679 return true;
680 }
681 current = current->GetDominator();
682 }
683 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100684}
685
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100686static void UpdateInputsUsers(HInstruction* instruction) {
687 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
688 instruction->InputAt(i)->AddUseAt(instruction, i);
689 }
690 // Environment should be created later.
691 DCHECK(!instruction->HasEnvironment());
692}
693
Roland Levillainccc07a92014-09-16 14:48:16 +0100694void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
695 HInstruction* replacement) {
696 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400697 if (initial->IsControlFlow()) {
698 // We can only replace a control flow instruction with another control flow instruction.
699 DCHECK(replacement->IsControlFlow());
700 DCHECK_EQ(replacement->GetId(), -1);
701 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
702 DCHECK_EQ(initial->GetBlock(), this);
703 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100704 DCHECK(initial->GetUses().empty());
705 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400706 replacement->SetBlock(this);
707 replacement->SetId(GetGraph()->GetNextInstructionId());
708 instructions_.InsertInstructionBefore(replacement, initial);
709 UpdateInputsUsers(replacement);
710 } else {
711 InsertInstructionBefore(replacement, initial);
712 initial->ReplaceWith(replacement);
713 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100714 RemoveInstruction(initial);
715}
716
David Brazdil74eb1b22015-12-14 11:44:01 +0000717void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
718 DCHECK(!cursor->IsPhi());
719 DCHECK(!insn->IsPhi());
720 DCHECK(!insn->IsControlFlow());
721 DCHECK(insn->CanBeMoved());
722 DCHECK(!insn->HasSideEffects());
723
724 HBasicBlock* from_block = insn->GetBlock();
725 HBasicBlock* to_block = cursor->GetBlock();
726 DCHECK(from_block != to_block);
727
728 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
729 insn->SetBlock(to_block);
730 to_block->instructions_.InsertInstructionBefore(insn, cursor);
731}
732
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100733static void Add(HInstructionList* instruction_list,
734 HBasicBlock* block,
735 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000736 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000737 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100738 instruction->SetBlock(block);
739 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100740 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100741 instruction_list->AddInstruction(instruction);
742}
743
744void HBasicBlock::AddInstruction(HInstruction* instruction) {
745 Add(&instructions_, this, instruction);
746}
747
748void HBasicBlock::AddPhi(HPhi* phi) {
749 Add(&phis_, this, phi);
750}
751
David Brazdilc3d743f2015-04-22 13:40:50 +0100752void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
753 DCHECK(!cursor->IsPhi());
754 DCHECK(!instruction->IsPhi());
755 DCHECK_EQ(instruction->GetId(), -1);
756 DCHECK_NE(cursor->GetId(), -1);
757 DCHECK_EQ(cursor->GetBlock(), this);
758 DCHECK(!instruction->IsControlFlow());
759 instruction->SetBlock(this);
760 instruction->SetId(GetGraph()->GetNextInstructionId());
761 UpdateInputsUsers(instruction);
762 instructions_.InsertInstructionBefore(instruction, cursor);
763}
764
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100765void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
766 DCHECK(!cursor->IsPhi());
767 DCHECK(!instruction->IsPhi());
768 DCHECK_EQ(instruction->GetId(), -1);
769 DCHECK_NE(cursor->GetId(), -1);
770 DCHECK_EQ(cursor->GetBlock(), this);
771 DCHECK(!instruction->IsControlFlow());
772 DCHECK(!cursor->IsControlFlow());
773 instruction->SetBlock(this);
774 instruction->SetId(GetGraph()->GetNextInstructionId());
775 UpdateInputsUsers(instruction);
776 instructions_.InsertInstructionAfter(instruction, cursor);
777}
778
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100779void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
780 DCHECK_EQ(phi->GetId(), -1);
781 DCHECK_NE(cursor->GetId(), -1);
782 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100783 phi->SetBlock(this);
784 phi->SetId(GetGraph()->GetNextInstructionId());
785 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100786 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100787}
788
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100789static void Remove(HInstructionList* instruction_list,
790 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000791 HInstruction* instruction,
792 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100793 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100794 instruction->SetBlock(nullptr);
795 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000796 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100797 DCHECK(instruction->GetUses().empty());
798 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000799 RemoveAsUser(instruction);
800 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100801}
802
David Brazdil1abb4192015-02-17 18:33:36 +0000803void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100804 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000805 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100806}
807
David Brazdil1abb4192015-02-17 18:33:36 +0000808void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
809 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100810}
811
David Brazdilc7508e92015-04-27 13:28:57 +0100812void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
813 if (instruction->IsPhi()) {
814 RemovePhi(instruction->AsPhi(), ensure_safety);
815 } else {
816 RemoveInstruction(instruction, ensure_safety);
817 }
818}
819
Vladimir Marko71bf8092015-09-15 15:33:14 +0100820void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
821 for (size_t i = 0; i < locals.size(); i++) {
822 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100823 SetRawEnvAt(i, instruction);
824 if (instruction != nullptr) {
825 instruction->AddEnvUseAt(this, i);
826 }
827 }
828}
829
David Brazdiled596192015-01-23 10:39:45 +0000830void HEnvironment::CopyFrom(HEnvironment* env) {
831 for (size_t i = 0; i < env->Size(); i++) {
832 HInstruction* instruction = env->GetInstructionAt(i);
833 SetRawEnvAt(i, instruction);
834 if (instruction != nullptr) {
835 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100836 }
David Brazdiled596192015-01-23 10:39:45 +0000837 }
838}
839
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700840void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
841 HBasicBlock* loop_header) {
842 DCHECK(loop_header->IsLoopHeader());
843 for (size_t i = 0; i < env->Size(); i++) {
844 HInstruction* instruction = env->GetInstructionAt(i);
845 SetRawEnvAt(i, instruction);
846 if (instruction == nullptr) {
847 continue;
848 }
849 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
850 // At the end of the loop pre-header, the corresponding value for instruction
851 // is the first input of the phi.
852 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700853 SetRawEnvAt(i, initial);
854 initial->AddEnvUseAt(this, i);
855 } else {
856 instruction->AddEnvUseAt(this, i);
857 }
858 }
859}
860
David Brazdil1abb4192015-02-17 18:33:36 +0000861void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100862 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
863 HInstruction* user = env_use.GetInstruction();
864 auto before_env_use_node = env_use.GetBeforeUseNode();
865 user->env_uses_.erase_after(before_env_use_node);
866 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100867}
868
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000869HInstruction::InstructionKind HInstruction::GetKind() const {
870 return GetKindInternal();
871}
872
Calin Juravle77520bc2015-01-12 18:45:46 +0000873HInstruction* HInstruction::GetNextDisregardingMoves() const {
874 HInstruction* next = GetNext();
875 while (next != nullptr && next->IsParallelMove()) {
876 next = next->GetNext();
877 }
878 return next;
879}
880
881HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
882 HInstruction* previous = GetPrevious();
883 while (previous != nullptr && previous->IsParallelMove()) {
884 previous = previous->GetPrevious();
885 }
886 return previous;
887}
888
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100889void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000890 if (first_instruction_ == nullptr) {
891 DCHECK(last_instruction_ == nullptr);
892 first_instruction_ = last_instruction_ = instruction;
893 } else {
894 last_instruction_->next_ = instruction;
895 instruction->previous_ = last_instruction_;
896 last_instruction_ = instruction;
897 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000898}
899
David Brazdilc3d743f2015-04-22 13:40:50 +0100900void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
901 DCHECK(Contains(cursor));
902 if (cursor == first_instruction_) {
903 cursor->previous_ = instruction;
904 instruction->next_ = cursor;
905 first_instruction_ = instruction;
906 } else {
907 instruction->previous_ = cursor->previous_;
908 instruction->next_ = cursor;
909 cursor->previous_ = instruction;
910 instruction->previous_->next_ = instruction;
911 }
912}
913
914void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
915 DCHECK(Contains(cursor));
916 if (cursor == last_instruction_) {
917 cursor->next_ = instruction;
918 instruction->previous_ = cursor;
919 last_instruction_ = instruction;
920 } else {
921 instruction->next_ = cursor->next_;
922 instruction->previous_ = cursor;
923 cursor->next_ = instruction;
924 instruction->next_->previous_ = instruction;
925 }
926}
927
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100928void HInstructionList::RemoveInstruction(HInstruction* instruction) {
929 if (instruction->previous_ != nullptr) {
930 instruction->previous_->next_ = instruction->next_;
931 }
932 if (instruction->next_ != nullptr) {
933 instruction->next_->previous_ = instruction->previous_;
934 }
935 if (instruction == first_instruction_) {
936 first_instruction_ = instruction->next_;
937 }
938 if (instruction == last_instruction_) {
939 last_instruction_ = instruction->previous_;
940 }
941}
942
Roland Levillain6b469232014-09-25 10:10:38 +0100943bool HInstructionList::Contains(HInstruction* instruction) const {
944 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
945 if (it.Current() == instruction) {
946 return true;
947 }
948 }
949 return false;
950}
951
Roland Levillainccc07a92014-09-16 14:48:16 +0100952bool HInstructionList::FoundBefore(const HInstruction* instruction1,
953 const HInstruction* instruction2) const {
954 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
955 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
956 if (it.Current() == instruction1) {
957 return true;
958 }
959 if (it.Current() == instruction2) {
960 return false;
961 }
962 }
963 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
964 return true;
965}
966
Roland Levillain6c82d402014-10-13 16:10:27 +0100967bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
968 if (other_instruction == this) {
969 // An instruction does not strictly dominate itself.
970 return false;
971 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100972 HBasicBlock* block = GetBlock();
973 HBasicBlock* other_block = other_instruction->GetBlock();
974 if (block != other_block) {
975 return GetBlock()->Dominates(other_instruction->GetBlock());
976 } else {
977 // If both instructions are in the same block, ensure this
978 // instruction comes before `other_instruction`.
979 if (IsPhi()) {
980 if (!other_instruction->IsPhi()) {
981 // Phis appear before non phi-instructions so this instruction
982 // dominates `other_instruction`.
983 return true;
984 } else {
985 // There is no order among phis.
986 LOG(FATAL) << "There is no dominance between phis of a same block.";
987 return false;
988 }
989 } else {
990 // `this` is not a phi.
991 if (other_instruction->IsPhi()) {
992 // Phis appear before non phi-instructions so this instruction
993 // does not dominate `other_instruction`.
994 return false;
995 } else {
996 // Check whether this instruction comes before
997 // `other_instruction` in the instruction list.
998 return block->GetInstructions().FoundBefore(this, other_instruction);
999 }
1000 }
1001 }
1002}
1003
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001004void HInstruction::RemoveEnvironment() {
1005 RemoveEnvironmentUses(this);
1006 environment_ = nullptr;
1007}
1008
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001009void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001010 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001011 // Note: fixup_end remains valid across splice_after().
1012 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1013 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1014 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001015
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001016 // Note: env_fixup_end remains valid across splice_after().
1017 auto env_fixup_end =
1018 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1019 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1020 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001021
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001022 DCHECK(uses_.empty());
1023 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001024}
1025
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001026void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001027 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001028 if (input_use.GetInstruction() == replacement) {
1029 // Nothing to do.
1030 return;
1031 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001032 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001033 // Note: fixup_end remains valid across splice_after().
1034 auto fixup_end =
1035 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1036 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1037 input_use.GetInstruction()->uses_,
1038 before_use_node);
1039 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1040 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001041}
1042
Nicolas Geoffray39468442014-09-02 15:17:15 +01001043size_t HInstruction::EnvironmentSize() const {
1044 return HasEnvironment() ? environment_->Size() : 0;
1045}
1046
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001047void HPhi::AddInput(HInstruction* input) {
1048 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001049 inputs_.push_back(HUserRecord<HInstruction*>(input));
1050 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001051}
1052
David Brazdil2d7352b2015-04-20 14:52:42 +01001053void HPhi::RemoveInputAt(size_t index) {
1054 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001055 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001056 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001057 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001058 InputRecordAt(i).GetUseNode()->SetIndex(i);
1059 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001060}
1061
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001062#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001063void H##name::Accept(HGraphVisitor* visitor) { \
1064 visitor->Visit##name(this); \
1065}
1066
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001067FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001068
1069#undef DEFINE_ACCEPT
1070
1071void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001072 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1073 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001074 if (block != nullptr) {
1075 VisitBasicBlock(block);
1076 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001077 }
1078}
1079
Roland Levillain633021e2014-10-01 14:12:25 +01001080void HGraphVisitor::VisitReversePostOrder() {
1081 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1082 VisitBasicBlock(it.Current());
1083 }
1084}
1085
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001086void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001087 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001088 it.Current()->Accept(this);
1089 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001090 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001091 it.Current()->Accept(this);
1092 }
1093}
1094
Mark Mendelle82549b2015-05-06 10:55:34 -04001095HConstant* HTypeConversion::TryStaticEvaluation() const {
1096 HGraph* graph = GetBlock()->GetGraph();
1097 if (GetInput()->IsIntConstant()) {
1098 int32_t value = GetInput()->AsIntConstant()->GetValue();
1099 switch (GetResultType()) {
1100 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001101 return graph->GetLongConstant(static_cast<int64_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()->IsLongConstant()) {
1110 int64_t value = GetInput()->AsLongConstant()->GetValue();
1111 switch (GetResultType()) {
1112 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001113 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001114 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001115 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001116 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001117 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001118 default:
1119 return nullptr;
1120 }
1121 } else if (GetInput()->IsFloatConstant()) {
1122 float value = GetInput()->AsFloatConstant()->GetValue();
1123 switch (GetResultType()) {
1124 case Primitive::kPrimInt:
1125 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001126 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001127 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001128 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001129 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001130 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1131 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001132 case Primitive::kPrimLong:
1133 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001134 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001135 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001136 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001137 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001138 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1139 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001140 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001141 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001142 default:
1143 return nullptr;
1144 }
1145 } else if (GetInput()->IsDoubleConstant()) {
1146 double value = GetInput()->AsDoubleConstant()->GetValue();
1147 switch (GetResultType()) {
1148 case Primitive::kPrimInt:
1149 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001150 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001151 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001152 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001153 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001154 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1155 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001156 case Primitive::kPrimLong:
1157 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001158 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001159 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001160 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001161 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001162 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1163 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001164 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001165 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001166 default:
1167 return nullptr;
1168 }
1169 }
1170 return nullptr;
1171}
1172
Roland Levillain9240d6a2014-10-20 16:47:04 +01001173HConstant* HUnaryOperation::TryStaticEvaluation() const {
1174 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001175 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001176 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001177 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001178 } else if (kEnableFloatingPointStaticEvaluation) {
1179 if (GetInput()->IsFloatConstant()) {
1180 return Evaluate(GetInput()->AsFloatConstant());
1181 } else if (GetInput()->IsDoubleConstant()) {
1182 return Evaluate(GetInput()->AsDoubleConstant());
1183 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001184 }
1185 return nullptr;
1186}
1187
1188HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001189 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1190 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001191 } else if (GetLeft()->IsLongConstant()) {
1192 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001193 // The binop(long, int) case is only valid for shifts and rotations.
1194 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001195 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1196 } else if (GetRight()->IsLongConstant()) {
1197 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001198 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001199 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001200 // The binop(null, null) case is only valid for equal and not-equal conditions.
1201 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001202 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001203 } else if (kEnableFloatingPointStaticEvaluation) {
1204 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1205 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1206 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1207 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1208 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001209 }
1210 return nullptr;
1211}
Dave Allison20dfc792014-06-16 20:44:29 -07001212
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001213HConstant* HBinaryOperation::GetConstantRight() const {
1214 if (GetRight()->IsConstant()) {
1215 return GetRight()->AsConstant();
1216 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1217 return GetLeft()->AsConstant();
1218 } else {
1219 return nullptr;
1220 }
1221}
1222
1223// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001224// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001225HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1226 HInstruction* most_constant_right = GetConstantRight();
1227 if (most_constant_right == nullptr) {
1228 return nullptr;
1229 } else if (most_constant_right == GetLeft()) {
1230 return GetRight();
1231 } else {
1232 return GetLeft();
1233 }
1234}
1235
Roland Levillain31dd3d62016-02-16 12:21:02 +00001236std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1237 switch (rhs) {
1238 case ComparisonBias::kNoBias:
1239 return os << "no_bias";
1240 case ComparisonBias::kGtBias:
1241 return os << "gt_bias";
1242 case ComparisonBias::kLtBias:
1243 return os << "lt_bias";
1244 default:
1245 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1246 UNREACHABLE();
1247 }
1248}
1249
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001250bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1251 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001252}
1253
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001254bool HInstruction::Equals(HInstruction* other) const {
1255 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001256 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001257 if (!InstructionDataEquals(other)) return false;
1258 if (GetType() != other->GetType()) return false;
1259 if (InputCount() != other->InputCount()) return false;
1260
1261 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1262 if (InputAt(i) != other->InputAt(i)) return false;
1263 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001264 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001265 return true;
1266}
1267
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001268std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1269#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1270 switch (rhs) {
1271 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1272 default:
1273 os << "Unknown instruction kind " << static_cast<int>(rhs);
1274 break;
1275 }
1276#undef DECLARE_CASE
1277 return os;
1278}
1279
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001280void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001281 next_->previous_ = previous_;
1282 if (previous_ != nullptr) {
1283 previous_->next_ = next_;
1284 }
1285 if (block_->instructions_.first_instruction_ == this) {
1286 block_->instructions_.first_instruction_ = next_;
1287 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001288 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001289
1290 previous_ = cursor->previous_;
1291 if (previous_ != nullptr) {
1292 previous_->next_ = this;
1293 }
1294 next_ = cursor;
1295 cursor->previous_ = this;
1296 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001297
1298 if (block_->instructions_.first_instruction_ == cursor) {
1299 block_->instructions_.first_instruction_ = this;
1300 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001301}
1302
Vladimir Markofb337ea2015-11-25 15:25:10 +00001303void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1304 DCHECK(!CanThrow());
1305 DCHECK(!HasSideEffects());
1306 DCHECK(!HasEnvironmentUses());
1307 DCHECK(HasNonEnvironmentUses());
1308 DCHECK(!IsPhi()); // Makes no sense for Phi.
1309 DCHECK_EQ(InputCount(), 0u);
1310
1311 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001312 auto uses_it = GetUses().begin();
1313 auto uses_end = GetUses().end();
1314 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1315 ++uses_it;
1316 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1317 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001318 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001319 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001320 // This instruction has uses in two or more blocks. Find the common dominator.
1321 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001322 for (; uses_it != uses_end; ++uses_it) {
1323 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001324 }
1325 target_block = finder.Get();
1326 DCHECK(target_block != nullptr);
1327 }
1328 // Move to the first dominator not in a loop.
1329 while (target_block->IsInLoop()) {
1330 target_block = target_block->GetDominator();
1331 DCHECK(target_block != nullptr);
1332 }
1333
1334 // Find insertion position.
1335 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001336 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1337 if (use.GetUser()->GetBlock() == target_block &&
1338 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1339 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001340 }
1341 }
1342 if (insert_pos == nullptr) {
1343 // No user in `target_block`, insert before the control flow instruction.
1344 insert_pos = target_block->GetLastInstruction();
1345 DCHECK(insert_pos->IsControlFlow());
1346 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1347 if (insert_pos->IsIf()) {
1348 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1349 if (if_input == insert_pos->GetPrevious()) {
1350 insert_pos = if_input;
1351 }
1352 }
1353 }
1354 MoveBefore(insert_pos);
1355}
1356
David Brazdilfc6a86a2015-06-26 10:33:45 +00001357HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001358 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001359 DCHECK_EQ(cursor->GetBlock(), this);
1360
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001361 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1362 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001363 new_block->instructions_.first_instruction_ = cursor;
1364 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1365 instructions_.last_instruction_ = cursor->previous_;
1366 if (cursor->previous_ == nullptr) {
1367 instructions_.first_instruction_ = nullptr;
1368 } else {
1369 cursor->previous_->next_ = nullptr;
1370 cursor->previous_ = nullptr;
1371 }
1372
1373 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001374 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001375
Vladimir Marko60584552015-09-03 13:35:12 +00001376 for (HBasicBlock* successor : GetSuccessors()) {
1377 new_block->successors_.push_back(successor);
1378 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001379 }
Vladimir Marko60584552015-09-03 13:35:12 +00001380 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001381 AddSuccessor(new_block);
1382
David Brazdil56e1acc2015-06-30 15:41:36 +01001383 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001384 return new_block;
1385}
1386
David Brazdild7558da2015-09-22 13:04:14 +01001387HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001388 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001389 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1390
1391 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1392
1393 for (HBasicBlock* predecessor : GetPredecessors()) {
1394 new_block->predecessors_.push_back(predecessor);
1395 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1396 }
1397 predecessors_.clear();
1398 AddPredecessor(new_block);
1399
1400 GetGraph()->AddBlock(new_block);
1401 return new_block;
1402}
1403
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001404HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1405 DCHECK_EQ(cursor->GetBlock(), this);
1406
1407 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1408 cursor->GetDexPc());
1409 new_block->instructions_.first_instruction_ = cursor;
1410 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1411 instructions_.last_instruction_ = cursor->previous_;
1412 if (cursor->previous_ == nullptr) {
1413 instructions_.first_instruction_ = nullptr;
1414 } else {
1415 cursor->previous_->next_ = nullptr;
1416 cursor->previous_ = nullptr;
1417 }
1418
1419 new_block->instructions_.SetBlockOfInstructions(new_block);
1420
1421 for (HBasicBlock* successor : GetSuccessors()) {
1422 new_block->successors_.push_back(successor);
1423 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1424 }
1425 successors_.clear();
1426
1427 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1428 dominated->dominator_ = new_block;
1429 new_block->dominated_blocks_.push_back(dominated);
1430 }
1431 dominated_blocks_.clear();
1432 return new_block;
1433}
1434
1435HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001436 DCHECK(!cursor->IsControlFlow());
1437 DCHECK_NE(instructions_.last_instruction_, cursor);
1438 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001439
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001440 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1441 new_block->instructions_.first_instruction_ = cursor->GetNext();
1442 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1443 cursor->next_->previous_ = nullptr;
1444 cursor->next_ = nullptr;
1445 instructions_.last_instruction_ = cursor;
1446
1447 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001448 for (HBasicBlock* successor : GetSuccessors()) {
1449 new_block->successors_.push_back(successor);
1450 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001451 }
Vladimir Marko60584552015-09-03 13:35:12 +00001452 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001453
Vladimir Marko60584552015-09-03 13:35:12 +00001454 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001455 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001456 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001457 }
Vladimir Marko60584552015-09-03 13:35:12 +00001458 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001459 return new_block;
1460}
1461
David Brazdilec16f792015-08-19 15:04:01 +01001462const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001463 if (EndsWithTryBoundary()) {
1464 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1465 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001466 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001467 return try_boundary;
1468 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001469 DCHECK(IsTryBlock());
1470 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001471 return nullptr;
1472 }
David Brazdilec16f792015-08-19 15:04:01 +01001473 } else if (IsTryBlock()) {
1474 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001475 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001476 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001477 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001478}
1479
David Brazdild7558da2015-09-22 13:04:14 +01001480bool HBasicBlock::HasThrowingInstructions() const {
1481 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1482 if (it.Current()->CanThrow()) {
1483 return true;
1484 }
1485 }
1486 return false;
1487}
1488
David Brazdilfc6a86a2015-06-26 10:33:45 +00001489static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1490 return block.GetPhis().IsEmpty()
1491 && !block.GetInstructions().IsEmpty()
1492 && block.GetFirstInstruction() == block.GetLastInstruction();
1493}
1494
David Brazdil46e2a392015-03-16 17:31:52 +00001495bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001496 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1497}
1498
1499bool HBasicBlock::IsSingleTryBoundary() const {
1500 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001501}
1502
David Brazdil8d5b8b22015-03-24 10:51:52 +00001503bool HBasicBlock::EndsWithControlFlowInstruction() const {
1504 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1505}
1506
David Brazdilb2bd1c52015-03-25 11:17:37 +00001507bool HBasicBlock::EndsWithIf() const {
1508 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1509}
1510
David Brazdilffee3d32015-07-06 11:48:53 +01001511bool HBasicBlock::EndsWithTryBoundary() const {
1512 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1513}
1514
David Brazdilb2bd1c52015-03-25 11:17:37 +00001515bool HBasicBlock::HasSinglePhi() const {
1516 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1517}
1518
David Brazdild26a4112015-11-10 11:07:31 +00001519ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1520 if (EndsWithTryBoundary()) {
1521 // The normal-flow successor of HTryBoundary is always stored at index zero.
1522 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1523 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1524 } else {
1525 // All successors of blocks not ending with TryBoundary are normal.
1526 return ArrayRef<HBasicBlock* const>(successors_);
1527 }
1528}
1529
1530ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1531 if (EndsWithTryBoundary()) {
1532 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1533 } else {
1534 // Blocks not ending with TryBoundary do not have exceptional successors.
1535 return ArrayRef<HBasicBlock* const>();
1536 }
1537}
1538
David Brazdilffee3d32015-07-06 11:48:53 +01001539bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001540 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1541 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1542
1543 size_t length = handlers1.size();
1544 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001545 return false;
1546 }
1547
David Brazdilb618ade2015-07-29 10:31:29 +01001548 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001549 for (size_t i = 0; i < length; ++i) {
1550 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001551 return false;
1552 }
1553 }
1554 return true;
1555}
1556
David Brazdil2d7352b2015-04-20 14:52:42 +01001557size_t HInstructionList::CountSize() const {
1558 size_t size = 0;
1559 HInstruction* current = first_instruction_;
1560 for (; current != nullptr; current = current->GetNext()) {
1561 size++;
1562 }
1563 return size;
1564}
1565
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001566void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1567 for (HInstruction* current = first_instruction_;
1568 current != nullptr;
1569 current = current->GetNext()) {
1570 current->SetBlock(block);
1571 }
1572}
1573
1574void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1575 DCHECK(Contains(cursor));
1576 if (!instruction_list.IsEmpty()) {
1577 if (cursor == last_instruction_) {
1578 last_instruction_ = instruction_list.last_instruction_;
1579 } else {
1580 cursor->next_->previous_ = instruction_list.last_instruction_;
1581 }
1582 instruction_list.last_instruction_->next_ = cursor->next_;
1583 cursor->next_ = instruction_list.first_instruction_;
1584 instruction_list.first_instruction_->previous_ = cursor;
1585 }
1586}
1587
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001588void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1589 DCHECK(Contains(cursor));
1590 if (!instruction_list.IsEmpty()) {
1591 if (cursor == first_instruction_) {
1592 first_instruction_ = instruction_list.first_instruction_;
1593 } else {
1594 cursor->previous_->next_ = instruction_list.first_instruction_;
1595 }
1596 instruction_list.last_instruction_->next_ = cursor;
1597 instruction_list.first_instruction_->previous_ = cursor->previous_;
1598 cursor->previous_ = instruction_list.last_instruction_;
1599 }
1600}
1601
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001602void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001603 if (IsEmpty()) {
1604 first_instruction_ = instruction_list.first_instruction_;
1605 last_instruction_ = instruction_list.last_instruction_;
1606 } else {
1607 AddAfter(last_instruction_, instruction_list);
1608 }
1609}
1610
David Brazdil04ff4e82015-12-10 13:54:52 +00001611// Should be called on instructions in a dead block in post order. This method
1612// assumes `insn` has been removed from all users with the exception of catch
1613// phis because of missing exceptional edges in the graph. It removes the
1614// instruction from catch phi uses, together with inputs of other catch phis in
1615// the catch block at the same index, as these must be dead too.
1616static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1617 DCHECK(!insn->HasEnvironmentUses());
1618 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001619 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1620 size_t use_index = use.GetIndex();
1621 HBasicBlock* user_block = use.GetUser()->GetBlock();
1622 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001623 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1624 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1625 }
1626 }
1627}
1628
David Brazdil2d7352b2015-04-20 14:52:42 +01001629void HBasicBlock::DisconnectAndDelete() {
1630 // Dominators must be removed after all the blocks they dominate. This way
1631 // a loop header is removed last, a requirement for correct loop information
1632 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001633 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001634
David Brazdil9eeebf62016-03-24 11:18:15 +00001635 // The following steps gradually remove the block from all its dependants in
1636 // post order (b/27683071).
1637
1638 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1639 // We need to do this before step (4) which destroys the predecessor list.
1640 HBasicBlock* loop_update_start = this;
1641 if (IsLoopHeader()) {
1642 HLoopInformation* loop_info = GetLoopInformation();
1643 // All other blocks in this loop should have been removed because the header
1644 // was their dominator.
1645 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1646 DCHECK(!loop_info->IsIrreducible());
1647 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1648 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1649 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001650 }
1651
David Brazdil9eeebf62016-03-24 11:18:15 +00001652 // (2) Disconnect the block from its successors and update their phis.
1653 for (HBasicBlock* successor : successors_) {
1654 // Delete this block from the list of predecessors.
1655 size_t this_index = successor->GetPredecessorIndexOf(this);
1656 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1657
1658 // Check that `successor` has other predecessors, otherwise `this` is the
1659 // dominator of `successor` which violates the order DCHECKed at the top.
1660 DCHECK(!successor->predecessors_.empty());
1661
1662 // Remove this block's entries in the successor's phis. Skip exceptional
1663 // successors because catch phi inputs do not correspond to predecessor
1664 // blocks but throwing instructions. The inputs of the catch phis will be
1665 // updated in step (3).
1666 if (!successor->IsCatchBlock()) {
1667 if (successor->predecessors_.size() == 1u) {
1668 // The successor has just one predecessor left. Replace phis with the only
1669 // remaining input.
1670 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1671 HPhi* phi = phi_it.Current()->AsPhi();
1672 phi->ReplaceWith(phi->InputAt(1 - this_index));
1673 successor->RemovePhi(phi);
1674 }
1675 } else {
1676 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1677 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1678 }
1679 }
1680 }
1681 }
1682 successors_.clear();
1683
1684 // (3) Remove instructions and phis. Instructions should have no remaining uses
1685 // except in catch phis. If an instruction is used by a catch phi at `index`,
1686 // remove `index`-th input of all phis in the catch block since they are
1687 // guaranteed dead. Note that we may miss dead inputs this way but the
1688 // graph will always remain consistent.
1689 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1690 HInstruction* insn = it.Current();
1691 RemoveUsesOfDeadInstruction(insn);
1692 RemoveInstruction(insn);
1693 }
1694 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1695 HPhi* insn = it.Current()->AsPhi();
1696 RemoveUsesOfDeadInstruction(insn);
1697 RemovePhi(insn);
1698 }
1699
1700 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001701 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001702 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001703 // We should not see any back edges as they would have been removed by step (3).
1704 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1705
David Brazdil2d7352b2015-04-20 14:52:42 +01001706 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001707 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1708 // This block is the only normal-flow successor of the TryBoundary which
1709 // makes `predecessor` dead. Since DCE removes blocks in post order,
1710 // exception handlers of this TryBoundary were already visited and any
1711 // remaining handlers therefore must be live. We remove `predecessor` from
1712 // their list of predecessors.
1713 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1714 while (predecessor->GetSuccessors().size() > 1) {
1715 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1716 DCHECK(handler->IsCatchBlock());
1717 predecessor->RemoveSuccessor(handler);
1718 handler->RemovePredecessor(predecessor);
1719 }
1720 }
1721
David Brazdil2d7352b2015-04-20 14:52:42 +01001722 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001723 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1724 if (num_pred_successors == 1u) {
1725 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001726 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1727 // successor. Replace those with a HGoto.
1728 DCHECK(last_instruction->IsIf() ||
1729 last_instruction->IsPackedSwitch() ||
1730 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001731 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001732 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001733 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001734 // The predecessor has no remaining successors and therefore must be dead.
1735 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001736 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001737 predecessor->RemoveInstruction(last_instruction);
1738 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001739 // There are multiple successors left. The removed block might be a successor
1740 // of a PackedSwitch which will be completely removed (perhaps replaced with
1741 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1742 // case, leave `last_instruction` as is for now.
1743 DCHECK(last_instruction->IsPackedSwitch() ||
1744 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001745 }
David Brazdil46e2a392015-03-16 17:31:52 +00001746 }
Vladimir Marko60584552015-09-03 13:35:12 +00001747 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001748
David Brazdil9eeebf62016-03-24 11:18:15 +00001749 // (5) Remove the block from all loops it is included in. Skip the inner-most
1750 // loop if this is the loop header (see definition of `loop_update_start`)
1751 // because the loop header's predecessor list has been destroyed in step (4).
1752 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1753 HLoopInformation* loop_info = it.Current();
1754 loop_info->Remove(this);
1755 if (loop_info->IsBackEdge(*this)) {
1756 // If this was the last back edge of the loop, we deliberately leave the
1757 // loop in an inconsistent state and will fail GraphChecker unless the
1758 // entire loop is removed during the pass.
1759 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001760 }
1761 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001762
David Brazdil9eeebf62016-03-24 11:18:15 +00001763 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001764 dominator_->RemoveDominatedBlock(this);
1765 SetDominator(nullptr);
1766
David Brazdil9eeebf62016-03-24 11:18:15 +00001767 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001768 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001769 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001770}
1771
1772void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001773 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001774 DCHECK(ContainsElement(dominated_blocks_, other));
1775 DCHECK_EQ(GetSingleSuccessor(), other);
1776 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001777 DCHECK(other->GetPhis().IsEmpty());
1778
David Brazdil2d7352b2015-04-20 14:52:42 +01001779 // Move instructions from `other` to `this`.
1780 DCHECK(EndsWithControlFlowInstruction());
1781 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001782 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001783 other->instructions_.SetBlockOfInstructions(this);
1784 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001785
David Brazdil2d7352b2015-04-20 14:52:42 +01001786 // Remove `other` from the loops it is included in.
1787 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1788 HLoopInformation* loop_info = it.Current();
1789 loop_info->Remove(other);
1790 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001791 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001792 }
1793 }
1794
1795 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001796 successors_.clear();
1797 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001798 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001799 successor->ReplacePredecessor(other, this);
1800 }
1801
David Brazdil2d7352b2015-04-20 14:52:42 +01001802 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001803 RemoveDominatedBlock(other);
1804 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1805 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001806 dominated->SetDominator(this);
1807 }
Vladimir Marko60584552015-09-03 13:35:12 +00001808 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001809 other->dominator_ = nullptr;
1810
1811 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001812 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001813
1814 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001815 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001816 other->SetGraph(nullptr);
1817}
1818
1819void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1820 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001821 DCHECK(GetDominatedBlocks().empty());
1822 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001823 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001824 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001825 DCHECK(other->GetPhis().IsEmpty());
1826 DCHECK(!other->IsInLoop());
1827
1828 // Move instructions from `other` to `this`.
1829 instructions_.Add(other->GetInstructions());
1830 other->instructions_.SetBlockOfInstructions(this);
1831
1832 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001833 successors_.clear();
1834 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001835 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001836 successor->ReplacePredecessor(other, this);
1837 }
1838
1839 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001840 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1841 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001842 dominated->SetDominator(this);
1843 }
Vladimir Marko60584552015-09-03 13:35:12 +00001844 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001845 other->dominator_ = nullptr;
1846 other->graph_ = nullptr;
1847}
1848
1849void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001850 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001851 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001852 predecessor->ReplaceSuccessor(this, other);
1853 }
Vladimir Marko60584552015-09-03 13:35:12 +00001854 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001855 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001856 successor->ReplacePredecessor(this, other);
1857 }
Vladimir Marko60584552015-09-03 13:35:12 +00001858 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1859 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001860 }
1861 GetDominator()->ReplaceDominatedBlock(this, other);
1862 other->SetDominator(GetDominator());
1863 dominator_ = nullptr;
1864 graph_ = nullptr;
1865}
1866
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001867void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001868 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001869 DCHECK(block->GetSuccessors().empty());
1870 DCHECK(block->GetPredecessors().empty());
1871 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001872 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001873 DCHECK(block->GetInstructions().IsEmpty());
1874 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001875
David Brazdilc7af85d2015-05-26 12:05:55 +01001876 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06001877 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01001878 }
1879
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001880 RemoveElement(reverse_post_order_, block);
1881 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00001882 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01001883}
1884
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001885void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
1886 HBasicBlock* reference,
1887 bool replace_if_back_edge) {
1888 if (block->IsLoopHeader()) {
1889 // Clear the information of which blocks are contained in that loop. Since the
1890 // information is stored as a bit vector based on block ids, we have to update
1891 // it, as those block ids were specific to the callee graph and we are now adding
1892 // these blocks to the caller graph.
1893 block->GetLoopInformation()->ClearAllBlocks();
1894 }
1895
1896 // If not already in a loop, update the loop information.
1897 if (!block->IsInLoop()) {
1898 block->SetLoopInformation(reference->GetLoopInformation());
1899 }
1900
1901 // If the block is in a loop, update all its outward loops.
1902 HLoopInformation* loop_info = block->GetLoopInformation();
1903 if (loop_info != nullptr) {
1904 for (HLoopInformationOutwardIterator loop_it(*block);
1905 !loop_it.Done();
1906 loop_it.Advance()) {
1907 loop_it.Current()->Add(block);
1908 }
1909 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
1910 loop_info->ReplaceBackEdge(reference, block);
1911 }
1912 }
1913
1914 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
1915 TryCatchInformation* try_catch_info = reference->IsTryBlock()
1916 ? reference->GetTryCatchInformation()
1917 : nullptr;
1918 block->SetTryCatchInformation(try_catch_info);
1919}
1920
Calin Juravle2e768302015-07-28 14:41:11 +00001921HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001922 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001923 // Update the environments in this graph to have the invoke's environment
1924 // as parent.
1925 {
1926 HReversePostOrderIterator it(*this);
1927 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1928 for (; !it.Done(); it.Advance()) {
1929 HBasicBlock* block = it.Current();
1930 for (HInstructionIterator instr_it(block->GetInstructions());
1931 !instr_it.Done();
1932 instr_it.Advance()) {
1933 HInstruction* current = instr_it.Current();
1934 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00001935 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001936 current->GetEnvironment()->SetAndCopyParentChain(
1937 outer_graph->GetArena(), invoke->GetEnvironment());
1938 }
1939 }
1940 }
1941 }
1942 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1943 if (HasBoundsChecks()) {
1944 outer_graph->SetHasBoundsChecks(true);
1945 }
1946
Calin Juravle2e768302015-07-28 14:41:11 +00001947 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001948 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001949 // Simple case of an entry block, a body block, and an exit block.
1950 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001951 HBasicBlock* body = GetBlocks()[1];
1952 DCHECK(GetBlocks()[0]->IsEntryBlock());
1953 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001954 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001955 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001956 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001957
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001958 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
1959 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001960 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001961
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001962 // Replace the invoke with the return value of the inlined graph.
1963 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001964 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001965 } else {
1966 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001967 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001968
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001969 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001970 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001971 // Need to inline multiple blocks. We split `invoke`'s block
1972 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001973 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001974 // with the second half.
1975 ArenaAllocator* allocator = outer_graph->GetArena();
1976 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001977 // Note that we split before the invoke only to simplify polymorphic inlining.
1978 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001979
Vladimir Markoec7802a2015-10-01 20:57:57 +01001980 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001981 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001982 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001983 exit_block_->ReplaceWith(to);
1984
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001985 // Update the meta information surrounding blocks:
1986 // (1) the graph they are now in,
1987 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001988 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05001989 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001990 // Note that we do not need to update catch phi inputs because they
1991 // correspond to the register file of the outer method which the inlinee
1992 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001993
1994 // We don't add the entry block, the exit block, and the first block, which
1995 // has been merged with `at`.
1996 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1997
1998 // We add the `to` block.
1999 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002000 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002001 + kNumberOfNewBlocksInCaller;
2002
2003 // Find the location of `at` in the outer graph's reverse post order. The new
2004 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002005 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002006 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2007
David Brazdil95177982015-10-30 12:56:58 -05002008 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2009 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002010 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
2011 HBasicBlock* current = it.Current();
2012 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002013 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002014 DCHECK(current->GetGraph() == this);
2015 current->SetGraph(outer_graph);
2016 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002017 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002018 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002019 }
2020 }
2021
David Brazdil95177982015-10-30 12:56:58 -05002022 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002023 to->SetGraph(outer_graph);
2024 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002025 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002026 // Only `to` can become a back edge, as the inlined blocks
2027 // are predecessors of `to`.
2028 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002029
David Brazdil3f523062016-02-29 16:53:33 +00002030 // Update all predecessors of the exit block (now the `to` block)
2031 // to not `HReturn` but `HGoto` instead.
2032 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
2033 if (to->GetPredecessors().size() == 1) {
2034 HBasicBlock* predecessor = to->GetPredecessors()[0];
2035 HInstruction* last = predecessor->GetLastInstruction();
2036 if (!returns_void) {
2037 return_value = last->InputAt(0);
2038 }
2039 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2040 predecessor->RemoveInstruction(last);
2041 } else {
2042 if (!returns_void) {
2043 // There will be multiple returns.
2044 return_value = new (allocator) HPhi(
2045 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2046 to->AddPhi(return_value->AsPhi());
2047 }
2048 for (HBasicBlock* predecessor : to->GetPredecessors()) {
2049 HInstruction* last = predecessor->GetLastInstruction();
2050 if (!returns_void) {
2051 DCHECK(last->IsReturn());
2052 return_value->AsPhi()->AddInput(last->InputAt(0));
2053 }
2054 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2055 predecessor->RemoveInstruction(last);
2056 }
2057 }
2058 }
David Brazdil05144f42015-04-16 15:18:00 +01002059
2060 // Walk over the entry block and:
2061 // - Move constants from the entry block to the outer_graph's entry block,
2062 // - Replace HParameterValue instructions with their real value.
2063 // - Remove suspend checks, that hold an environment.
2064 // We must do this after the other blocks have been inlined, otherwise ids of
2065 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002066 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002067 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2068 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002069 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002070 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002071 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002072 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002073 replacement = outer_graph->GetIntConstant(
2074 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002075 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002076 replacement = outer_graph->GetLongConstant(
2077 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002078 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002079 replacement = outer_graph->GetFloatConstant(
2080 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002081 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002082 replacement = outer_graph->GetDoubleConstant(
2083 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002084 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002085 if (kIsDebugBuild
2086 && invoke->IsInvokeStaticOrDirect()
2087 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2088 // Ensure we do not use the last input of `invoke`, as it
2089 // contains a clinit check which is not an actual argument.
2090 size_t last_input_index = invoke->InputCount() - 1;
2091 DCHECK(parameter_index != last_input_index);
2092 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002093 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002094 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002095 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002096 } else {
2097 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2098 entry_block_->RemoveInstruction(current);
2099 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002100 if (replacement != nullptr) {
2101 current->ReplaceWith(replacement);
2102 // If the current is the return value then we need to update the latter.
2103 if (current == return_value) {
2104 DCHECK_EQ(entry_block_, return_value->GetBlock());
2105 return_value = replacement;
2106 }
2107 }
2108 }
2109
Calin Juravle2e768302015-07-28 14:41:11 +00002110 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002111}
2112
Mingyao Yang3584bce2015-05-19 16:01:59 -07002113/*
2114 * Loop will be transformed to:
2115 * old_pre_header
2116 * |
2117 * if_block
2118 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002119 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002120 * \ /
2121 * new_pre_header
2122 * |
2123 * header
2124 */
2125void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2126 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002127 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002128
Aart Bik3fc7f352015-11-20 22:03:03 -08002129 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002130 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002131 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2132 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002133 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2134 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002135 AddBlock(true_block);
2136 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002137 AddBlock(new_pre_header);
2138
Aart Bik3fc7f352015-11-20 22:03:03 -08002139 header->ReplacePredecessor(old_pre_header, new_pre_header);
2140 old_pre_header->successors_.clear();
2141 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002142
Aart Bik3fc7f352015-11-20 22:03:03 -08002143 old_pre_header->AddSuccessor(if_block);
2144 if_block->AddSuccessor(true_block); // True successor
2145 if_block->AddSuccessor(false_block); // False successor
2146 true_block->AddSuccessor(new_pre_header);
2147 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002148
Aart Bik3fc7f352015-11-20 22:03:03 -08002149 old_pre_header->dominated_blocks_.push_back(if_block);
2150 if_block->SetDominator(old_pre_header);
2151 if_block->dominated_blocks_.push_back(true_block);
2152 true_block->SetDominator(if_block);
2153 if_block->dominated_blocks_.push_back(false_block);
2154 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002155 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002156 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002157 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002158 header->SetDominator(new_pre_header);
2159
Aart Bik3fc7f352015-11-20 22:03:03 -08002160 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002161 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002162 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002163 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002164 reverse_post_order_[index_of_header++] = true_block;
2165 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002166 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002167
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002168 // The pre_header can never be a back edge of a loop.
2169 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2170 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2171 UpdateLoopAndTryInformationOfNewBlock(
2172 if_block, old_pre_header, /* replace_if_back_edge */ false);
2173 UpdateLoopAndTryInformationOfNewBlock(
2174 true_block, old_pre_header, /* replace_if_back_edge */ false);
2175 UpdateLoopAndTryInformationOfNewBlock(
2176 false_block, old_pre_header, /* replace_if_back_edge */ false);
2177 UpdateLoopAndTryInformationOfNewBlock(
2178 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002179}
2180
David Brazdilf5552582015-12-27 13:36:12 +00002181static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2182 SHARED_REQUIRES(Locks::mutator_lock_) {
2183 if (rti.IsValid()) {
2184 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2185 << " upper_bound_rti: " << upper_bound_rti
2186 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002187 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2188 << " upper_bound_rti: " << upper_bound_rti
2189 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002190 }
2191}
2192
Calin Juravle2e768302015-07-28 14:41:11 +00002193void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2194 if (kIsDebugBuild) {
2195 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2196 ScopedObjectAccess soa(Thread::Current());
2197 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2198 if (IsBoundType()) {
2199 // Having the test here spares us from making the method virtual just for
2200 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002201 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002202 }
2203 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002204 reference_type_handle_ = rti.GetTypeHandle();
2205 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002206}
2207
David Brazdilf5552582015-12-27 13:36:12 +00002208void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2209 if (kIsDebugBuild) {
2210 ScopedObjectAccess soa(Thread::Current());
2211 DCHECK(upper_bound.IsValid());
2212 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2213 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2214 }
2215 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002216 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002217}
2218
Vladimir Markoa1de9182016-02-25 11:37:38 +00002219ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002220 if (kIsDebugBuild) {
2221 ScopedObjectAccess soa(Thread::Current());
2222 DCHECK(IsValidHandle(type_handle));
Aart Bik8b3f9b22016-04-06 11:22:12 -07002223 DCHECK(!type_handle->IsErroneous());
Aart Bikf417ff42016-04-25 12:51:37 -07002224 DCHECK(!type_handle->IsArrayClass() || !type_handle->GetComponentType()->IsErroneous());
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002225 if (!is_exact) {
2226 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2227 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2228 }
Calin Juravle2e768302015-07-28 14:41:11 +00002229 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002230 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002231}
2232
Calin Juravleacf735c2015-02-12 15:25:22 +00002233std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2234 ScopedObjectAccess soa(Thread::Current());
2235 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002236 << " is_valid=" << rhs.IsValid()
2237 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002238 << " is_exact=" << rhs.IsExact()
2239 << " ]";
2240 return os;
2241}
2242
Mark Mendellc4701932015-04-10 13:18:51 -04002243bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2244 // For now, assume that instructions in different blocks may use the
2245 // environment.
2246 // TODO: Use the control flow to decide if this is true.
2247 if (GetBlock() != other->GetBlock()) {
2248 return true;
2249 }
2250
2251 // We know that we are in the same block. Walk from 'this' to 'other',
2252 // checking to see if there is any instruction with an environment.
2253 HInstruction* current = this;
2254 for (; current != other && current != nullptr; current = current->GetNext()) {
2255 // This is a conservative check, as the instruction result may not be in
2256 // the referenced environment.
2257 if (current->HasEnvironment()) {
2258 return true;
2259 }
2260 }
2261
2262 // We should have been called with 'this' before 'other' in the block.
2263 // Just confirm this.
2264 DCHECK(current != nullptr);
2265 return false;
2266}
2267
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002268void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002269 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2270 IntrinsicSideEffects side_effects,
2271 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002272 intrinsic_ = intrinsic;
2273 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002274
Aart Bik5d75afe2015-12-14 11:57:01 -08002275 // Adjust method's side effects from intrinsic table.
2276 switch (side_effects) {
2277 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2278 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2279 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2280 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2281 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002282
2283 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2284 opt.SetDoesNotNeedDexCache();
2285 opt.SetDoesNotNeedEnvironment();
2286 } else {
2287 // If we need an environment, that means there will be a call, which can trigger GC.
2288 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2289 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002290 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002291 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002292}
2293
David Brazdil6de19382016-01-08 17:37:10 +00002294bool HNewInstance::IsStringAlloc() const {
2295 ScopedObjectAccess soa(Thread::Current());
2296 return GetReferenceTypeInfo().IsStringClass();
2297}
2298
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002299bool HInvoke::NeedsEnvironment() const {
2300 if (!IsIntrinsic()) {
2301 return true;
2302 }
2303 IntrinsicOptimizations opt(*this);
2304 return !opt.GetDoesNotNeedEnvironment();
2305}
2306
Vladimir Markodc151b22015-10-15 18:02:30 +01002307bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2308 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002309 return false;
2310 }
2311 if (!IsIntrinsic()) {
2312 return true;
2313 }
2314 IntrinsicOptimizations opt(*this);
2315 return !opt.GetDoesNotNeedDexCache();
2316}
2317
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002318void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2319 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2320 input->AddUseAt(this, index);
2321 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2322 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2323 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2324 InputRecordAt(i).GetUseNode()->SetIndex(i);
2325 }
2326}
2327
Vladimir Markob554b5a2015-11-06 12:57:55 +00002328void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2329 RemoveAsUserOfInput(index);
2330 inputs_.erase(inputs_.begin() + index);
2331 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2332 for (size_t i = index, e = InputCount(); i < e; ++i) {
2333 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2334 InputRecordAt(i).GetUseNode()->SetIndex(i);
2335 }
2336}
2337
Vladimir Markof64242a2015-12-01 14:58:23 +00002338std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2339 switch (rhs) {
2340 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2341 return os << "string_init";
2342 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2343 return os << "recursive";
2344 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2345 return os << "direct";
2346 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2347 return os << "direct_fixup";
2348 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2349 return os << "dex_cache_pc_relative";
2350 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2351 return os << "dex_cache_via_method";
2352 default:
2353 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2354 UNREACHABLE();
2355 }
2356}
2357
Vladimir Markofbb184a2015-11-13 14:47:00 +00002358std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2359 switch (rhs) {
2360 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2361 return os << "explicit";
2362 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2363 return os << "implicit";
2364 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2365 return os << "none";
2366 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002367 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2368 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002369 }
2370}
2371
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002372bool HLoadString::InstructionDataEquals(HInstruction* other) const {
2373 HLoadString* other_load_string = other->AsLoadString();
2374 if (string_index_ != other_load_string->string_index_ ||
2375 GetPackedFields() != other_load_string->GetPackedFields()) {
2376 return false;
2377 }
2378 LoadKind load_kind = GetLoadKind();
2379 if (HasAddress(load_kind)) {
2380 return GetAddress() == other_load_string->GetAddress();
2381 } else if (HasStringReference(load_kind)) {
2382 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2383 } else {
2384 DCHECK(HasDexCacheReference(load_kind)) << load_kind;
2385 // If the string indexes and dex files are the same, dex cache element offsets
2386 // must also be the same, so we don't need to compare them.
2387 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
2388 }
2389}
2390
2391void HLoadString::SetLoadKindInternal(LoadKind load_kind) {
2392 // Once sharpened, the load kind should not be changed again.
2393 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2394 SetPackedField<LoadKindField>(load_kind);
2395
2396 if (load_kind != LoadKind::kDexCacheViaMethod) {
2397 RemoveAsUserOfInput(0u);
2398 SetRawInputAt(0u, nullptr);
2399 }
2400 if (!NeedsEnvironment()) {
2401 RemoveEnvironment();
2402 }
2403}
2404
2405std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2406 switch (rhs) {
2407 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2408 return os << "BootImageLinkTimeAddress";
2409 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2410 return os << "BootImageLinkTimePcRelative";
2411 case HLoadString::LoadKind::kBootImageAddress:
2412 return os << "BootImageAddress";
2413 case HLoadString::LoadKind::kDexCacheAddress:
2414 return os << "DexCacheAddress";
2415 case HLoadString::LoadKind::kDexCachePcRelative:
2416 return os << "DexCachePcRelative";
2417 case HLoadString::LoadKind::kDexCacheViaMethod:
2418 return os << "DexCacheViaMethod";
2419 default:
2420 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2421 UNREACHABLE();
2422 }
2423}
2424
Mark Mendellc4701932015-04-10 13:18:51 -04002425void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002426 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2427 HEnvironment* user = use.GetUser();
2428 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002429 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002430 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002431}
2432
Roland Levillainc9b21f82016-03-23 16:36:59 +00002433// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002434HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2435 ArenaAllocator* allocator = GetArena();
2436
2437 if (cond->IsCondition() &&
2438 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2439 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2440 HInstruction* lhs = cond->InputAt(0);
2441 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002442 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002443 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2444 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2445 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2446 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2447 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2448 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2449 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2450 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2451 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2452 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2453 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002454 default:
2455 LOG(FATAL) << "Unexpected condition";
2456 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002457 }
2458 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2459 return replacement;
2460 } else if (cond->IsIntConstant()) {
2461 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002462 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002463 return GetIntConstant(1);
2464 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002465 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002466 return GetIntConstant(0);
2467 }
2468 } else {
2469 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2470 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2471 return replacement;
2472 }
2473}
2474
Roland Levillainc9285912015-12-18 10:38:42 +00002475std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2476 os << "["
2477 << " source=" << rhs.GetSource()
2478 << " destination=" << rhs.GetDestination()
2479 << " type=" << rhs.GetType()
2480 << " instruction=";
2481 if (rhs.GetInstruction() != nullptr) {
2482 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2483 } else {
2484 os << "null";
2485 }
2486 os << " ]";
2487 return os;
2488}
2489
Roland Levillain86503782016-02-11 19:07:30 +00002490std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2491 switch (rhs) {
2492 case TypeCheckKind::kUnresolvedCheck:
2493 return os << "unresolved_check";
2494 case TypeCheckKind::kExactCheck:
2495 return os << "exact_check";
2496 case TypeCheckKind::kClassHierarchyCheck:
2497 return os << "class_hierarchy_check";
2498 case TypeCheckKind::kAbstractClassCheck:
2499 return os << "abstract_class_check";
2500 case TypeCheckKind::kInterfaceCheck:
2501 return os << "interface_check";
2502 case TypeCheckKind::kArrayObjectCheck:
2503 return os << "array_object_check";
2504 case TypeCheckKind::kArrayCheck:
2505 return os << "array_check";
2506 default:
2507 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2508 UNREACHABLE();
2509 }
2510}
2511
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002512} // namespace art