blob: 1a426d5930df7b5cf3983d9cdae29e6245a15ee0 [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
Roland Levillainfc600dc2014-12-02 17:16:31 +000089static void RemoveAsUser(HInstruction* instruction) {
90 for (size_t i = 0; i < instruction->InputCount(); i++) {
David Brazdil1abb4192015-02-17 18:33:36 +000091 instruction->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000092 }
93
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010094 for (HEnvironment* environment = instruction->GetEnvironment();
95 environment != nullptr;
96 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000097 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000098 if (environment->GetInstructionAt(i) != nullptr) {
99 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000100 }
101 }
102 }
103}
104
105void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100106 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000107 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100108 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000109 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100110 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000111 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
112 RemoveAsUser(it.Current());
113 }
114 }
115 }
116}
117
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100118void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100119 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000120 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100121 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000122 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100123 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000124 for (HBasicBlock* successor : block->GetSuccessors()) {
125 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000126 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100127 // Remove the block from the list of blocks, so that further analyses
128 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100129 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600130 if (block->IsExitBlock()) {
131 SetExitBlock(nullptr);
132 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000133 }
134 }
135}
136
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000137GraphAnalysisResult HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100138 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
139 // edges. This invariant simplifies building SSA form because Phis cannot
140 // collect both normal- and exceptional-flow values at the same time.
141 SimplifyCatchBlocks();
142
Vladimir Markof6a35de2016-03-21 12:01:50 +0000143 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000144
David Brazdilffee3d32015-07-06 11:48:53 +0100145 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000146 FindBackEdges(&visited);
147
David Brazdilffee3d32015-07-06 11:48:53 +0100148 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000149 // the initial DFS as users from other instructions, so that
150 // users can be safely removed before uses later.
151 RemoveInstructionsAsUsersFromDeadBlocks(visited);
152
David Brazdilffee3d32015-07-06 11:48:53 +0100153 // (4) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000154 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000155 // predecessors list of live blocks.
156 RemoveDeadBlocks(visited);
157
David Brazdilffee3d32015-07-06 11:48:53 +0100158 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100159 // dominators and the reverse post order.
160 SimplifyCFG();
161
David Brazdilffee3d32015-07-06 11:48:53 +0100162 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100163 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000164
Roland Levillainc9b21f82016-03-23 16:36:59 +0000165 // (7) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000166 // set the loop information on each block.
167 GraphAnalysisResult result = AnalyzeLoops();
168 if (result != kAnalysisSuccess) {
169 return result;
170 }
171
172 // (8) Precompute per-block try membership before entering the SSA builder,
173 // which needs the information to build catch block phis from values of
174 // locals at throwing instructions inside try blocks.
175 ComputeTryBlockInformation();
176
177 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100178}
179
180void HGraph::ClearDominanceInformation() {
181 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
182 it.Current()->ClearDominanceInformation();
183 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100184 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100185}
186
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000187void HGraph::ClearLoopInformation() {
188 SetHasIrreducibleLoops(false);
189 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000190 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000191 }
192}
193
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100194void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000195 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100196 dominator_ = nullptr;
197}
198
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000199HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
200 HInstruction* instruction = GetFirstInstruction();
201 while (instruction->IsParallelMove()) {
202 instruction = instruction->GetNext();
203 }
204 return instruction;
205}
206
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100207void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100208 DCHECK(reverse_post_order_.empty());
209 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100210 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100211
212 // Number of visits of a given node, indexed by block id.
213 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
214 // Number of successors visited from a given node, indexed by block id.
215 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
216 // Nodes for which we need to visit successors.
217 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
218 constexpr size_t kDefaultWorklistSize = 8;
219 worklist.reserve(kDefaultWorklistSize);
220 worklist.push_back(entry_block_);
221
222 while (!worklist.empty()) {
223 HBasicBlock* current = worklist.back();
224 uint32_t current_id = current->GetBlockId();
225 if (successors_visited[current_id] == current->GetSuccessors().size()) {
226 worklist.pop_back();
227 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100228 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
229
230 if (successor->GetDominator() == nullptr) {
231 successor->SetDominator(current);
232 } else {
Vladimir Marko391d01f2015-11-06 11:02:08 +0000233 // The CommonDominator can work for multiple blocks as long as the
234 // domination information doesn't change. However, since we're changing
235 // that information here, we can use the finder only for pairs of blocks.
236 successor->SetDominator(CommonDominator::ForPair(successor->GetDominator(), current));
Vladimir Markod76d1392015-09-23 16:07:14 +0100237 }
238
239 // Once all the forward edges have been visited, we know the immediate
240 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100241 if (++visits[successor->GetBlockId()] ==
242 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100243 reverse_post_order_.push_back(successor);
244 worklist.push_back(successor);
245 }
246 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000247 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000248
249 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000250 // The potential presence of irreducible loops requires to do it after.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000251 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
252 HBasicBlock* block = it.Current();
253 if (!block->IsEntryBlock()) {
254 block->GetDominator()->AddDominatedBlock(block);
255 }
256 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000257}
258
David Brazdilfc6a86a2015-06-26 10:33:45 +0000259HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000260 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
261 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000262 // Use `InsertBetween` to ensure the predecessor index and successor index of
263 // `block` and `successor` are preserved.
264 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000265 return new_block;
266}
267
268void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
269 // Insert a new node between `block` and `successor` to split the
270 // critical edge.
271 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600272 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100273 if (successor->IsLoopHeader()) {
274 // If we split at a back edge boundary, make the new block the back edge.
275 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000276 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100277 info->RemoveBackEdge(block);
278 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100279 }
280 }
281}
282
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100283void HGraph::SimplifyLoop(HBasicBlock* header) {
284 HLoopInformation* info = header->GetLoopInformation();
285
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100286 // Make sure the loop has only one pre header. This simplifies SSA building by having
287 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000288 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
289 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000290 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000291 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100292 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100293 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600294 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100295
Vladimir Marko60584552015-09-03 13:35:12 +0000296 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100297 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100298 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100299 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100300 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100301 }
302 }
303 pre_header->AddSuccessor(header);
304 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100305
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100306 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100307 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
308 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000309 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100310 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100311 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000312 header->predecessors_[pred] = to_swap;
313 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100314 break;
315 }
316 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100317 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100318
319 // Place the suspend check at the beginning of the header, so that live registers
320 // will be known when allocating registers. Note that code generation can still
321 // generate the suspend check at the back edge, but needs to be careful with
322 // loop phi spill slots (which are not written to at back edge).
323 HInstruction* first_instruction = header->GetFirstInstruction();
324 if (!first_instruction->IsSuspendCheck()) {
325 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
326 header->InsertInstructionBefore(check, first_instruction);
327 first_instruction = check;
328 }
329 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100330}
331
David Brazdilffee3d32015-07-06 11:48:53 +0100332static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100333 HBasicBlock* predecessor = block.GetPredecessors()[pred_idx];
David Brazdilffee3d32015-07-06 11:48:53 +0100334 if (!predecessor->EndsWithTryBoundary()) {
335 // Only edges from HTryBoundary can be exceptional.
336 return false;
337 }
338 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
339 if (try_boundary->GetNormalFlowSuccessor() == &block) {
340 // This block is the normal-flow successor of `try_boundary`, but it could
341 // also be one of its exception handlers if catch blocks have not been
342 // simplified yet. Predecessors are unordered, so we will consider the first
343 // occurrence to be the normal edge and a possible second occurrence to be
344 // the exceptional edge.
345 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
346 } else {
347 // This is not the normal-flow successor of `try_boundary`, hence it must be
348 // one of its exception handlers.
349 DCHECK(try_boundary->HasExceptionHandler(block));
350 return true;
351 }
352}
353
354void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100355 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
356 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
357 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
358 HBasicBlock* catch_block = blocks_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000359 if (catch_block == nullptr || !catch_block->IsCatchBlock()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100360 continue;
361 }
362
363 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000364 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100365 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
366 exceptional_predecessors_only = false;
367 break;
368 }
369 }
370
371 if (!exceptional_predecessors_only) {
372 // Catch block has normal-flow predecessors and needs to be simplified.
373 // Splitting the block before its first instruction moves all its
374 // instructions into `normal_block` and links the two blocks with a Goto.
375 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
376 // leaving `catch_block` with the exceptional edges only.
David Brazdil9bc43612015-11-05 21:25:24 +0000377 //
David Brazdilffee3d32015-07-06 11:48:53 +0100378 // Note that catch blocks with normal-flow predecessors cannot begin with
David Brazdil9bc43612015-11-05 21:25:24 +0000379 // a move-exception instruction, as guaranteed by the verifier. However,
380 // trivially dead predecessors are ignored by the verifier and such code
381 // has not been removed at this stage. We therefore ignore the assumption
382 // and rely on GraphChecker to enforce it after initial DCE is run (b/25492628).
383 HBasicBlock* normal_block = catch_block->SplitCatchBlockAfterMoveException();
384 if (normal_block == nullptr) {
385 // Catch block is either empty or only contains a move-exception. It must
386 // therefore be dead and will be removed during initial DCE. Do nothing.
387 DCHECK(!catch_block->EndsWithControlFlowInstruction());
388 } else {
389 // Catch block was split. Re-link normal-flow edges to the new block.
390 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
391 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
392 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
393 --j;
394 }
David Brazdilffee3d32015-07-06 11:48:53 +0100395 }
396 }
397 }
398 }
399}
400
401void HGraph::ComputeTryBlockInformation() {
402 // Iterate in reverse post order to propagate try membership information from
403 // predecessors to their successors.
404 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
405 HBasicBlock* block = it.Current();
406 if (block->IsEntryBlock() || block->IsCatchBlock()) {
407 // Catch blocks after simplification have only exceptional predecessors
408 // and hence are never in tries.
409 continue;
410 }
411
412 // Infer try membership from the first predecessor. Having simplified loops,
413 // the first predecessor can never be a back edge and therefore it must have
414 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100415 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100416 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100417 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000418 if (try_entry != nullptr &&
419 (block->GetTryCatchInformation() == nullptr ||
420 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
421 // We are either setting try block membership for the first time or it
422 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100423 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
424 }
David Brazdilffee3d32015-07-06 11:48:53 +0100425 }
426}
427
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100428void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000429// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100430 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000431 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100432 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
433 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
434 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
435 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100436 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000437 if (block->GetSuccessors().size() > 1) {
438 // Only split normal-flow edges. We cannot split exceptional edges as they
439 // are synthesized (approximate real control flow), and we do not need to
440 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000441 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
442 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
443 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100444 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000445 if (successor == exit_block_) {
446 // Throw->TryBoundary->Exit. Special case which we do not want to split
447 // because Goto->Exit is not allowed.
448 DCHECK(block->IsSingleTryBoundary());
449 DCHECK(block->GetSinglePredecessor()->GetLastInstruction()->IsThrow());
450 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100451 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000452 // SplitCriticalEdge could have invalidated the `normal_successors`
453 // ArrayRef. We must re-acquire it.
454 normal_successors = block->GetNormalSuccessors();
455 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
456 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100457 }
458 }
459 }
460 if (block->IsLoopHeader()) {
461 SimplifyLoop(block);
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000462 } else if (!block->IsEntryBlock() && block->GetFirstInstruction()->IsSuspendCheck()) {
Roland Levillainc9b21f82016-03-23 16:36:59 +0000463 // We are being called by the dead code elimination pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000464 // a loop got dismantled. Just remove the suspend check.
465 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100466 }
467 }
468}
469
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000470GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100471 // Order does not matter.
472 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
473 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100474 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100475 if (block->IsCatchBlock()) {
476 // TODO: Dealing with exceptional back edges could be tricky because
477 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000478 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100479 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000480 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100481 }
482 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000483 return kAnalysisSuccess;
484}
485
486void HLoopInformation::Dump(std::ostream& os) {
487 os << "header: " << header_->GetBlockId() << std::endl;
488 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
489 for (HBasicBlock* block : back_edges_) {
490 os << "back edge: " << block->GetBlockId() << std::endl;
491 }
492 for (HBasicBlock* block : header_->GetPredecessors()) {
493 os << "predecessor: " << block->GetBlockId() << std::endl;
494 }
495 for (uint32_t idx : blocks_.Indexes()) {
496 os << " in loop: " << idx << std::endl;
497 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100498}
499
David Brazdil8d5b8b22015-03-24 10:51:52 +0000500void HGraph::InsertConstant(HConstant* constant) {
501 // New constants are inserted before the final control-flow instruction
502 // of the graph, or at its end if called from the graph builder.
503 if (entry_block_->EndsWithControlFlowInstruction()) {
504 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000505 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000506 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000507 }
508}
509
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600510HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100511 // For simplicity, don't bother reviving the cached null constant if it is
512 // not null and not in a block. Otherwise, we need to clear the instruction
513 // id and/or any invariants the graph is assuming when adding new instructions.
514 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600515 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000516 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000517 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000518 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000519 if (kIsDebugBuild) {
520 ScopedObjectAccess soa(Thread::Current());
521 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
522 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000523 return cached_null_constant_;
524}
525
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100526HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100527 // For simplicity, don't bother reviving the cached current method if it is
528 // not null and not in a block. Otherwise, we need to clear the instruction
529 // id and/or any invariants the graph is assuming when adding new instructions.
530 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700531 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600532 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
533 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100534 if (entry_block_->GetFirstInstruction() == nullptr) {
535 entry_block_->AddInstruction(cached_current_method_);
536 } else {
537 entry_block_->InsertInstructionBefore(
538 cached_current_method_, entry_block_->GetFirstInstruction());
539 }
540 }
541 return cached_current_method_;
542}
543
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600544HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000545 switch (type) {
546 case Primitive::Type::kPrimBoolean:
547 DCHECK(IsUint<1>(value));
548 FALLTHROUGH_INTENDED;
549 case Primitive::Type::kPrimByte:
550 case Primitive::Type::kPrimChar:
551 case Primitive::Type::kPrimShort:
552 case Primitive::Type::kPrimInt:
553 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600554 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000555
556 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600557 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000558
559 default:
560 LOG(FATAL) << "Unsupported constant type";
561 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000562 }
David Brazdil46e2a392015-03-16 17:31:52 +0000563}
564
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000565void HGraph::CacheFloatConstant(HFloatConstant* constant) {
566 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
567 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
568 cached_float_constants_.Overwrite(value, constant);
569}
570
571void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
572 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
573 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
574 cached_double_constants_.Overwrite(value, constant);
575}
576
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000577void HLoopInformation::Add(HBasicBlock* block) {
578 blocks_.SetBit(block->GetBlockId());
579}
580
David Brazdil46e2a392015-03-16 17:31:52 +0000581void HLoopInformation::Remove(HBasicBlock* block) {
582 blocks_.ClearBit(block->GetBlockId());
583}
584
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100585void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
586 if (blocks_.IsBitSet(block->GetBlockId())) {
587 return;
588 }
589
590 blocks_.SetBit(block->GetBlockId());
591 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000592 for (HBasicBlock* predecessor : block->GetPredecessors()) {
593 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100594 }
595}
596
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000597void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block) {
598 if (blocks_.IsBitSet(block->GetBlockId())) {
599 return;
600 }
601
602 if (block->IsLoopHeader()) {
603 // If we hit a loop header in an irreducible loop, we first check if the
604 // pre header of that loop belongs to the currently analyzed loop. If it does,
605 // then we visit the back edges.
606 // Note that we cannot use GetPreHeader, as the loop may have not been populated
607 // yet.
608 HBasicBlock* pre_header = block->GetPredecessors()[0];
609 PopulateIrreducibleRecursive(pre_header);
610 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
611 blocks_.SetBit(block->GetBlockId());
612 block->SetInLoop(this);
613 HLoopInformation* info = block->GetLoopInformation();
614 for (HBasicBlock* back_edge : info->GetBackEdges()) {
615 PopulateIrreducibleRecursive(back_edge);
616 }
617 }
618 } else {
619 // Visit all predecessors. If one predecessor is part of the loop, this
620 // block is also part of this loop.
621 for (HBasicBlock* predecessor : block->GetPredecessors()) {
622 PopulateIrreducibleRecursive(predecessor);
623 if (blocks_.IsBitSet(predecessor->GetBlockId())) {
624 blocks_.SetBit(block->GetBlockId());
625 block->SetInLoop(this);
626 }
627 }
628 }
629}
630
631void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100632 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000633 // Populate this loop: starting with the back edge, recursively add predecessors
634 // that are not already part of that loop. Set the header as part of the loop
635 // to end the recursion.
636 // This is a recursive implementation of the algorithm described in
637 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
638 blocks_.SetBit(header_->GetBlockId());
639 header_->SetInLoop(this);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100640 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100641 DCHECK(back_edge->GetDominator() != nullptr);
642 if (!header_->Dominates(back_edge)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000643 irreducible_ = true;
644 header_->GetGraph()->SetHasIrreducibleLoops(true);
645 PopulateIrreducibleRecursive(back_edge);
646 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000647 if (header_->GetGraph()->IsCompilingOsr()) {
648 irreducible_ = true;
649 header_->GetGraph()->SetHasIrreducibleLoops(true);
650 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000651 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100652 }
David Brazdila4b8c212015-05-07 09:59:30 +0100653 }
654}
655
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100656HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000657 HBasicBlock* block = header_->GetPredecessors()[0];
658 DCHECK(irreducible_ || (block == header_->GetDominator()));
659 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100660}
661
662bool HLoopInformation::Contains(const HBasicBlock& block) const {
663 return blocks_.IsBitSet(block.GetBlockId());
664}
665
666bool HLoopInformation::IsIn(const HLoopInformation& other) const {
667 return other.blocks_.IsBitSet(header_->GetBlockId());
668}
669
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800670bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
671 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700672}
673
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100674size_t HLoopInformation::GetLifetimeEnd() const {
675 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100676 for (HBasicBlock* back_edge : GetBackEdges()) {
677 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100678 }
679 return last_position;
680}
681
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100682bool HBasicBlock::Dominates(HBasicBlock* other) const {
683 // Walk up the dominator tree from `other`, to find out if `this`
684 // is an ancestor.
685 HBasicBlock* current = other;
686 while (current != nullptr) {
687 if (current == this) {
688 return true;
689 }
690 current = current->GetDominator();
691 }
692 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100693}
694
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100695static void UpdateInputsUsers(HInstruction* instruction) {
696 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
697 instruction->InputAt(i)->AddUseAt(instruction, i);
698 }
699 // Environment should be created later.
700 DCHECK(!instruction->HasEnvironment());
701}
702
Roland Levillainccc07a92014-09-16 14:48:16 +0100703void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
704 HInstruction* replacement) {
705 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400706 if (initial->IsControlFlow()) {
707 // We can only replace a control flow instruction with another control flow instruction.
708 DCHECK(replacement->IsControlFlow());
709 DCHECK_EQ(replacement->GetId(), -1);
710 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
711 DCHECK_EQ(initial->GetBlock(), this);
712 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
713 DCHECK(initial->GetUses().IsEmpty());
714 DCHECK(initial->GetEnvUses().IsEmpty());
715 replacement->SetBlock(this);
716 replacement->SetId(GetGraph()->GetNextInstructionId());
717 instructions_.InsertInstructionBefore(replacement, initial);
718 UpdateInputsUsers(replacement);
719 } else {
720 InsertInstructionBefore(replacement, initial);
721 initial->ReplaceWith(replacement);
722 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100723 RemoveInstruction(initial);
724}
725
David Brazdil74eb1b22015-12-14 11:44:01 +0000726void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
727 DCHECK(!cursor->IsPhi());
728 DCHECK(!insn->IsPhi());
729 DCHECK(!insn->IsControlFlow());
730 DCHECK(insn->CanBeMoved());
731 DCHECK(!insn->HasSideEffects());
732
733 HBasicBlock* from_block = insn->GetBlock();
734 HBasicBlock* to_block = cursor->GetBlock();
735 DCHECK(from_block != to_block);
736
737 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
738 insn->SetBlock(to_block);
739 to_block->instructions_.InsertInstructionBefore(insn, cursor);
740}
741
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100742static void Add(HInstructionList* instruction_list,
743 HBasicBlock* block,
744 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000745 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000746 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100747 instruction->SetBlock(block);
748 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100749 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100750 instruction_list->AddInstruction(instruction);
751}
752
753void HBasicBlock::AddInstruction(HInstruction* instruction) {
754 Add(&instructions_, this, instruction);
755}
756
757void HBasicBlock::AddPhi(HPhi* phi) {
758 Add(&phis_, this, phi);
759}
760
David Brazdilc3d743f2015-04-22 13:40:50 +0100761void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
762 DCHECK(!cursor->IsPhi());
763 DCHECK(!instruction->IsPhi());
764 DCHECK_EQ(instruction->GetId(), -1);
765 DCHECK_NE(cursor->GetId(), -1);
766 DCHECK_EQ(cursor->GetBlock(), this);
767 DCHECK(!instruction->IsControlFlow());
768 instruction->SetBlock(this);
769 instruction->SetId(GetGraph()->GetNextInstructionId());
770 UpdateInputsUsers(instruction);
771 instructions_.InsertInstructionBefore(instruction, cursor);
772}
773
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100774void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
775 DCHECK(!cursor->IsPhi());
776 DCHECK(!instruction->IsPhi());
777 DCHECK_EQ(instruction->GetId(), -1);
778 DCHECK_NE(cursor->GetId(), -1);
779 DCHECK_EQ(cursor->GetBlock(), this);
780 DCHECK(!instruction->IsControlFlow());
781 DCHECK(!cursor->IsControlFlow());
782 instruction->SetBlock(this);
783 instruction->SetId(GetGraph()->GetNextInstructionId());
784 UpdateInputsUsers(instruction);
785 instructions_.InsertInstructionAfter(instruction, cursor);
786}
787
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100788void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
789 DCHECK_EQ(phi->GetId(), -1);
790 DCHECK_NE(cursor->GetId(), -1);
791 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100792 phi->SetBlock(this);
793 phi->SetId(GetGraph()->GetNextInstructionId());
794 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100795 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100796}
797
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100798static void Remove(HInstructionList* instruction_list,
799 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000800 HInstruction* instruction,
801 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100802 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100803 instruction->SetBlock(nullptr);
804 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000805 if (ensure_safety) {
806 DCHECK(instruction->GetUses().IsEmpty());
807 DCHECK(instruction->GetEnvUses().IsEmpty());
808 RemoveAsUser(instruction);
809 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100810}
811
David Brazdil1abb4192015-02-17 18:33:36 +0000812void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100813 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000814 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100815}
816
David Brazdil1abb4192015-02-17 18:33:36 +0000817void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
818 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100819}
820
David Brazdilc7508e92015-04-27 13:28:57 +0100821void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
822 if (instruction->IsPhi()) {
823 RemovePhi(instruction->AsPhi(), ensure_safety);
824 } else {
825 RemoveInstruction(instruction, ensure_safety);
826 }
827}
828
Vladimir Marko71bf8092015-09-15 15:33:14 +0100829void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
830 for (size_t i = 0; i < locals.size(); i++) {
831 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100832 SetRawEnvAt(i, instruction);
833 if (instruction != nullptr) {
834 instruction->AddEnvUseAt(this, i);
835 }
836 }
837}
838
David Brazdiled596192015-01-23 10:39:45 +0000839void HEnvironment::CopyFrom(HEnvironment* env) {
840 for (size_t i = 0; i < env->Size(); i++) {
841 HInstruction* instruction = env->GetInstructionAt(i);
842 SetRawEnvAt(i, instruction);
843 if (instruction != nullptr) {
844 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100845 }
David Brazdiled596192015-01-23 10:39:45 +0000846 }
847}
848
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700849void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
850 HBasicBlock* loop_header) {
851 DCHECK(loop_header->IsLoopHeader());
852 for (size_t i = 0; i < env->Size(); i++) {
853 HInstruction* instruction = env->GetInstructionAt(i);
854 SetRawEnvAt(i, instruction);
855 if (instruction == nullptr) {
856 continue;
857 }
858 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
859 // At the end of the loop pre-header, the corresponding value for instruction
860 // is the first input of the phi.
861 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700862 SetRawEnvAt(i, initial);
863 initial->AddEnvUseAt(this, i);
864 } else {
865 instruction->AddEnvUseAt(this, i);
866 }
867 }
868}
869
David Brazdil1abb4192015-02-17 18:33:36 +0000870void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100871 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000872 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100873}
874
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000875HInstruction::InstructionKind HInstruction::GetKind() const {
876 return GetKindInternal();
877}
878
Calin Juravle77520bc2015-01-12 18:45:46 +0000879HInstruction* HInstruction::GetNextDisregardingMoves() const {
880 HInstruction* next = GetNext();
881 while (next != nullptr && next->IsParallelMove()) {
882 next = next->GetNext();
883 }
884 return next;
885}
886
887HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
888 HInstruction* previous = GetPrevious();
889 while (previous != nullptr && previous->IsParallelMove()) {
890 previous = previous->GetPrevious();
891 }
892 return previous;
893}
894
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100895void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000896 if (first_instruction_ == nullptr) {
897 DCHECK(last_instruction_ == nullptr);
898 first_instruction_ = last_instruction_ = instruction;
899 } else {
900 last_instruction_->next_ = instruction;
901 instruction->previous_ = last_instruction_;
902 last_instruction_ = instruction;
903 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000904}
905
David Brazdilc3d743f2015-04-22 13:40:50 +0100906void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
907 DCHECK(Contains(cursor));
908 if (cursor == first_instruction_) {
909 cursor->previous_ = instruction;
910 instruction->next_ = cursor;
911 first_instruction_ = instruction;
912 } else {
913 instruction->previous_ = cursor->previous_;
914 instruction->next_ = cursor;
915 cursor->previous_ = instruction;
916 instruction->previous_->next_ = instruction;
917 }
918}
919
920void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
921 DCHECK(Contains(cursor));
922 if (cursor == last_instruction_) {
923 cursor->next_ = instruction;
924 instruction->previous_ = cursor;
925 last_instruction_ = instruction;
926 } else {
927 instruction->next_ = cursor->next_;
928 instruction->previous_ = cursor;
929 cursor->next_ = instruction;
930 instruction->next_->previous_ = instruction;
931 }
932}
933
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100934void HInstructionList::RemoveInstruction(HInstruction* instruction) {
935 if (instruction->previous_ != nullptr) {
936 instruction->previous_->next_ = instruction->next_;
937 }
938 if (instruction->next_ != nullptr) {
939 instruction->next_->previous_ = instruction->previous_;
940 }
941 if (instruction == first_instruction_) {
942 first_instruction_ = instruction->next_;
943 }
944 if (instruction == last_instruction_) {
945 last_instruction_ = instruction->previous_;
946 }
947}
948
Roland Levillain6b469232014-09-25 10:10:38 +0100949bool HInstructionList::Contains(HInstruction* instruction) const {
950 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
951 if (it.Current() == instruction) {
952 return true;
953 }
954 }
955 return false;
956}
957
Roland Levillainccc07a92014-09-16 14:48:16 +0100958bool HInstructionList::FoundBefore(const HInstruction* instruction1,
959 const HInstruction* instruction2) const {
960 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
961 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
962 if (it.Current() == instruction1) {
963 return true;
964 }
965 if (it.Current() == instruction2) {
966 return false;
967 }
968 }
969 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
970 return true;
971}
972
Roland Levillain6c82d402014-10-13 16:10:27 +0100973bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
974 if (other_instruction == this) {
975 // An instruction does not strictly dominate itself.
976 return false;
977 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100978 HBasicBlock* block = GetBlock();
979 HBasicBlock* other_block = other_instruction->GetBlock();
980 if (block != other_block) {
981 return GetBlock()->Dominates(other_instruction->GetBlock());
982 } else {
983 // If both instructions are in the same block, ensure this
984 // instruction comes before `other_instruction`.
985 if (IsPhi()) {
986 if (!other_instruction->IsPhi()) {
987 // Phis appear before non phi-instructions so this instruction
988 // dominates `other_instruction`.
989 return true;
990 } else {
991 // There is no order among phis.
992 LOG(FATAL) << "There is no dominance between phis of a same block.";
993 return false;
994 }
995 } else {
996 // `this` is not a phi.
997 if (other_instruction->IsPhi()) {
998 // Phis appear before non phi-instructions so this instruction
999 // does not dominate `other_instruction`.
1000 return false;
1001 } else {
1002 // Check whether this instruction comes before
1003 // `other_instruction` in the instruction list.
1004 return block->GetInstructions().FoundBefore(this, other_instruction);
1005 }
1006 }
1007 }
1008}
1009
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001010void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001011 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +00001012 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
1013 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001014 HInstruction* user = current->GetUser();
1015 size_t input_index = current->GetIndex();
1016 user->SetRawInputAt(input_index, other);
1017 other->AddUseAt(user, input_index);
1018 }
1019
David Brazdiled596192015-01-23 10:39:45 +00001020 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
1021 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001022 HEnvironment* user = current->GetUser();
1023 size_t input_index = current->GetIndex();
1024 user->SetRawEnvAt(input_index, other);
1025 other->AddEnvUseAt(user, input_index);
1026 }
1027
David Brazdiled596192015-01-23 10:39:45 +00001028 uses_.Clear();
1029 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001030}
1031
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001032void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +00001033 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001034 SetRawInputAt(index, replacement);
1035 replacement->AddUseAt(this, index);
1036}
1037
Nicolas Geoffray39468442014-09-02 15:17:15 +01001038size_t HInstruction::EnvironmentSize() const {
1039 return HasEnvironment() ? environment_->Size() : 0;
1040}
1041
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001042void HPhi::AddInput(HInstruction* input) {
1043 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001044 inputs_.push_back(HUserRecord<HInstruction*>(input));
1045 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001046}
1047
David Brazdil2d7352b2015-04-20 14:52:42 +01001048void HPhi::RemoveInputAt(size_t index) {
1049 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001050 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001051 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001052 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001053 InputRecordAt(i).GetUseNode()->SetIndex(i);
1054 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001055}
1056
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001057#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001058void H##name::Accept(HGraphVisitor* visitor) { \
1059 visitor->Visit##name(this); \
1060}
1061
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001062FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001063
1064#undef DEFINE_ACCEPT
1065
1066void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001067 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1068 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001069 if (block != nullptr) {
1070 VisitBasicBlock(block);
1071 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001072 }
1073}
1074
Roland Levillain633021e2014-10-01 14:12:25 +01001075void HGraphVisitor::VisitReversePostOrder() {
1076 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1077 VisitBasicBlock(it.Current());
1078 }
1079}
1080
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001081void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001082 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001083 it.Current()->Accept(this);
1084 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001085 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001086 it.Current()->Accept(this);
1087 }
1088}
1089
Mark Mendelle82549b2015-05-06 10:55:34 -04001090HConstant* HTypeConversion::TryStaticEvaluation() const {
1091 HGraph* graph = GetBlock()->GetGraph();
1092 if (GetInput()->IsIntConstant()) {
1093 int32_t value = GetInput()->AsIntConstant()->GetValue();
1094 switch (GetResultType()) {
1095 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001096 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001097 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001098 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001099 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001100 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001101 default:
1102 return nullptr;
1103 }
1104 } else if (GetInput()->IsLongConstant()) {
1105 int64_t value = GetInput()->AsLongConstant()->GetValue();
1106 switch (GetResultType()) {
1107 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001108 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001109 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001110 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001111 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001112 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001113 default:
1114 return nullptr;
1115 }
1116 } else if (GetInput()->IsFloatConstant()) {
1117 float value = GetInput()->AsFloatConstant()->GetValue();
1118 switch (GetResultType()) {
1119 case Primitive::kPrimInt:
1120 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001121 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001122 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001123 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001124 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001125 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1126 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001127 case Primitive::kPrimLong:
1128 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001129 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001130 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001131 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001132 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001133 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1134 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001135 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001136 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001137 default:
1138 return nullptr;
1139 }
1140 } else if (GetInput()->IsDoubleConstant()) {
1141 double value = GetInput()->AsDoubleConstant()->GetValue();
1142 switch (GetResultType()) {
1143 case Primitive::kPrimInt:
1144 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001145 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001146 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001147 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001148 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001149 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1150 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001151 case Primitive::kPrimLong:
1152 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001153 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001154 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001155 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001156 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001157 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1158 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001159 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001160 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001161 default:
1162 return nullptr;
1163 }
1164 }
1165 return nullptr;
1166}
1167
Roland Levillain9240d6a2014-10-20 16:47:04 +01001168HConstant* HUnaryOperation::TryStaticEvaluation() const {
1169 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001170 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001171 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001172 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001173 } else if (kEnableFloatingPointStaticEvaluation) {
1174 if (GetInput()->IsFloatConstant()) {
1175 return Evaluate(GetInput()->AsFloatConstant());
1176 } else if (GetInput()->IsDoubleConstant()) {
1177 return Evaluate(GetInput()->AsDoubleConstant());
1178 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001179 }
1180 return nullptr;
1181}
1182
1183HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001184 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1185 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001186 } else if (GetLeft()->IsLongConstant()) {
1187 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001188 // The binop(long, int) case is only valid for shifts and rotations.
1189 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001190 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1191 } else if (GetRight()->IsLongConstant()) {
1192 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001193 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001194 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001195 // The binop(null, null) case is only valid for equal and not-equal conditions.
1196 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001197 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001198 } else if (kEnableFloatingPointStaticEvaluation) {
1199 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1200 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1201 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1202 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1203 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001204 }
1205 return nullptr;
1206}
Dave Allison20dfc792014-06-16 20:44:29 -07001207
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001208HConstant* HBinaryOperation::GetConstantRight() const {
1209 if (GetRight()->IsConstant()) {
1210 return GetRight()->AsConstant();
1211 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1212 return GetLeft()->AsConstant();
1213 } else {
1214 return nullptr;
1215 }
1216}
1217
1218// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001219// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001220HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1221 HInstruction* most_constant_right = GetConstantRight();
1222 if (most_constant_right == nullptr) {
1223 return nullptr;
1224 } else if (most_constant_right == GetLeft()) {
1225 return GetRight();
1226 } else {
1227 return GetLeft();
1228 }
1229}
1230
Roland Levillain31dd3d62016-02-16 12:21:02 +00001231std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1232 switch (rhs) {
1233 case ComparisonBias::kNoBias:
1234 return os << "no_bias";
1235 case ComparisonBias::kGtBias:
1236 return os << "gt_bias";
1237 case ComparisonBias::kLtBias:
1238 return os << "lt_bias";
1239 default:
1240 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1241 UNREACHABLE();
1242 }
1243}
1244
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001245bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1246 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001247}
1248
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001249bool HInstruction::Equals(HInstruction* other) const {
1250 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001251 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001252 if (!InstructionDataEquals(other)) return false;
1253 if (GetType() != other->GetType()) return false;
1254 if (InputCount() != other->InputCount()) return false;
1255
1256 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1257 if (InputAt(i) != other->InputAt(i)) return false;
1258 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001259 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001260 return true;
1261}
1262
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001263std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1264#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1265 switch (rhs) {
1266 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1267 default:
1268 os << "Unknown instruction kind " << static_cast<int>(rhs);
1269 break;
1270 }
1271#undef DECLARE_CASE
1272 return os;
1273}
1274
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001275void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001276 next_->previous_ = previous_;
1277 if (previous_ != nullptr) {
1278 previous_->next_ = next_;
1279 }
1280 if (block_->instructions_.first_instruction_ == this) {
1281 block_->instructions_.first_instruction_ = next_;
1282 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001283 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001284
1285 previous_ = cursor->previous_;
1286 if (previous_ != nullptr) {
1287 previous_->next_ = this;
1288 }
1289 next_ = cursor;
1290 cursor->previous_ = this;
1291 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001292
1293 if (block_->instructions_.first_instruction_ == cursor) {
1294 block_->instructions_.first_instruction_ = this;
1295 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001296}
1297
Vladimir Markofb337ea2015-11-25 15:25:10 +00001298void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1299 DCHECK(!CanThrow());
1300 DCHECK(!HasSideEffects());
1301 DCHECK(!HasEnvironmentUses());
1302 DCHECK(HasNonEnvironmentUses());
1303 DCHECK(!IsPhi()); // Makes no sense for Phi.
1304 DCHECK_EQ(InputCount(), 0u);
1305
1306 // Find the target block.
1307 HUseIterator<HInstruction*> uses_it(GetUses());
1308 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1309 uses_it.Advance();
1310 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1311 uses_it.Advance();
1312 }
1313 if (!uses_it.Done()) {
1314 // This instruction has uses in two or more blocks. Find the common dominator.
1315 CommonDominator finder(target_block);
1316 for (; !uses_it.Done(); uses_it.Advance()) {
1317 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1318 }
1319 target_block = finder.Get();
1320 DCHECK(target_block != nullptr);
1321 }
1322 // Move to the first dominator not in a loop.
1323 while (target_block->IsInLoop()) {
1324 target_block = target_block->GetDominator();
1325 DCHECK(target_block != nullptr);
1326 }
1327
1328 // Find insertion position.
1329 HInstruction* insert_pos = nullptr;
1330 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1331 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1332 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1333 insert_pos = uses_it2.Current()->GetUser();
1334 }
1335 }
1336 if (insert_pos == nullptr) {
1337 // No user in `target_block`, insert before the control flow instruction.
1338 insert_pos = target_block->GetLastInstruction();
1339 DCHECK(insert_pos->IsControlFlow());
1340 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1341 if (insert_pos->IsIf()) {
1342 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1343 if (if_input == insert_pos->GetPrevious()) {
1344 insert_pos = if_input;
1345 }
1346 }
1347 }
1348 MoveBefore(insert_pos);
1349}
1350
David Brazdilfc6a86a2015-06-26 10:33:45 +00001351HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001352 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001353 DCHECK_EQ(cursor->GetBlock(), this);
1354
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001355 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1356 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001357 new_block->instructions_.first_instruction_ = cursor;
1358 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1359 instructions_.last_instruction_ = cursor->previous_;
1360 if (cursor->previous_ == nullptr) {
1361 instructions_.first_instruction_ = nullptr;
1362 } else {
1363 cursor->previous_->next_ = nullptr;
1364 cursor->previous_ = nullptr;
1365 }
1366
1367 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001368 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001369
Vladimir Marko60584552015-09-03 13:35:12 +00001370 for (HBasicBlock* successor : GetSuccessors()) {
1371 new_block->successors_.push_back(successor);
1372 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001373 }
Vladimir Marko60584552015-09-03 13:35:12 +00001374 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001375 AddSuccessor(new_block);
1376
David Brazdil56e1acc2015-06-30 15:41:36 +01001377 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001378 return new_block;
1379}
1380
David Brazdild7558da2015-09-22 13:04:14 +01001381HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001382 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001383 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1384
1385 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1386
1387 for (HBasicBlock* predecessor : GetPredecessors()) {
1388 new_block->predecessors_.push_back(predecessor);
1389 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1390 }
1391 predecessors_.clear();
1392 AddPredecessor(new_block);
1393
1394 GetGraph()->AddBlock(new_block);
1395 return new_block;
1396}
1397
David Brazdil9bc43612015-11-05 21:25:24 +00001398HBasicBlock* HBasicBlock::SplitCatchBlockAfterMoveException() {
1399 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
1400 DCHECK(IsCatchBlock()) << "This method is intended for catch blocks only.";
1401
1402 HInstruction* first_insn = GetFirstInstruction();
1403 HInstruction* split_before = nullptr;
1404
1405 if (first_insn != nullptr && first_insn->IsLoadException()) {
1406 // Catch block starts with a LoadException. Split the block after
1407 // the StoreLocal and ClearException which must come after the load.
1408 DCHECK(first_insn->GetNext()->IsStoreLocal());
1409 DCHECK(first_insn->GetNext()->GetNext()->IsClearException());
1410 split_before = first_insn->GetNext()->GetNext()->GetNext();
1411 } else {
1412 // Catch block does not load the exception. Split at the beginning
1413 // to create an empty catch block.
1414 split_before = first_insn;
1415 }
1416
1417 if (split_before == nullptr) {
1418 // Catch block has no instructions after the split point (must be dead).
1419 // Do not split it but rather signal error by returning nullptr.
1420 return nullptr;
1421 } else {
1422 return SplitBefore(split_before);
1423 }
1424}
1425
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001426HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1427 DCHECK_EQ(cursor->GetBlock(), this);
1428
1429 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1430 cursor->GetDexPc());
1431 new_block->instructions_.first_instruction_ = cursor;
1432 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1433 instructions_.last_instruction_ = cursor->previous_;
1434 if (cursor->previous_ == nullptr) {
1435 instructions_.first_instruction_ = nullptr;
1436 } else {
1437 cursor->previous_->next_ = nullptr;
1438 cursor->previous_ = nullptr;
1439 }
1440
1441 new_block->instructions_.SetBlockOfInstructions(new_block);
1442
1443 for (HBasicBlock* successor : GetSuccessors()) {
1444 new_block->successors_.push_back(successor);
1445 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1446 }
1447 successors_.clear();
1448
1449 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1450 dominated->dominator_ = new_block;
1451 new_block->dominated_blocks_.push_back(dominated);
1452 }
1453 dominated_blocks_.clear();
1454 return new_block;
1455}
1456
1457HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001458 DCHECK(!cursor->IsControlFlow());
1459 DCHECK_NE(instructions_.last_instruction_, cursor);
1460 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001461
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001462 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1463 new_block->instructions_.first_instruction_ = cursor->GetNext();
1464 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1465 cursor->next_->previous_ = nullptr;
1466 cursor->next_ = nullptr;
1467 instructions_.last_instruction_ = cursor;
1468
1469 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001470 for (HBasicBlock* successor : GetSuccessors()) {
1471 new_block->successors_.push_back(successor);
1472 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001473 }
Vladimir Marko60584552015-09-03 13:35:12 +00001474 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001475
Vladimir Marko60584552015-09-03 13:35:12 +00001476 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001477 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001478 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001479 }
Vladimir Marko60584552015-09-03 13:35:12 +00001480 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001481 return new_block;
1482}
1483
David Brazdilec16f792015-08-19 15:04:01 +01001484const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001485 if (EndsWithTryBoundary()) {
1486 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1487 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001488 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001489 return try_boundary;
1490 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001491 DCHECK(IsTryBlock());
1492 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001493 return nullptr;
1494 }
David Brazdilec16f792015-08-19 15:04:01 +01001495 } else if (IsTryBlock()) {
1496 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001497 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001498 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001499 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001500}
1501
David Brazdild7558da2015-09-22 13:04:14 +01001502bool HBasicBlock::HasThrowingInstructions() const {
1503 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1504 if (it.Current()->CanThrow()) {
1505 return true;
1506 }
1507 }
1508 return false;
1509}
1510
David Brazdilfc6a86a2015-06-26 10:33:45 +00001511static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1512 return block.GetPhis().IsEmpty()
1513 && !block.GetInstructions().IsEmpty()
1514 && block.GetFirstInstruction() == block.GetLastInstruction();
1515}
1516
David Brazdil46e2a392015-03-16 17:31:52 +00001517bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001518 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1519}
1520
1521bool HBasicBlock::IsSingleTryBoundary() const {
1522 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001523}
1524
David Brazdil8d5b8b22015-03-24 10:51:52 +00001525bool HBasicBlock::EndsWithControlFlowInstruction() const {
1526 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1527}
1528
David Brazdilb2bd1c52015-03-25 11:17:37 +00001529bool HBasicBlock::EndsWithIf() const {
1530 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1531}
1532
David Brazdilffee3d32015-07-06 11:48:53 +01001533bool HBasicBlock::EndsWithTryBoundary() const {
1534 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1535}
1536
David Brazdilb2bd1c52015-03-25 11:17:37 +00001537bool HBasicBlock::HasSinglePhi() const {
1538 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1539}
1540
David Brazdild26a4112015-11-10 11:07:31 +00001541ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1542 if (EndsWithTryBoundary()) {
1543 // The normal-flow successor of HTryBoundary is always stored at index zero.
1544 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1545 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1546 } else {
1547 // All successors of blocks not ending with TryBoundary are normal.
1548 return ArrayRef<HBasicBlock* const>(successors_);
1549 }
1550}
1551
1552ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1553 if (EndsWithTryBoundary()) {
1554 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1555 } else {
1556 // Blocks not ending with TryBoundary do not have exceptional successors.
1557 return ArrayRef<HBasicBlock* const>();
1558 }
1559}
1560
David Brazdilffee3d32015-07-06 11:48:53 +01001561bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001562 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1563 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1564
1565 size_t length = handlers1.size();
1566 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001567 return false;
1568 }
1569
David Brazdilb618ade2015-07-29 10:31:29 +01001570 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001571 for (size_t i = 0; i < length; ++i) {
1572 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001573 return false;
1574 }
1575 }
1576 return true;
1577}
1578
David Brazdil2d7352b2015-04-20 14:52:42 +01001579size_t HInstructionList::CountSize() const {
1580 size_t size = 0;
1581 HInstruction* current = first_instruction_;
1582 for (; current != nullptr; current = current->GetNext()) {
1583 size++;
1584 }
1585 return size;
1586}
1587
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001588void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1589 for (HInstruction* current = first_instruction_;
1590 current != nullptr;
1591 current = current->GetNext()) {
1592 current->SetBlock(block);
1593 }
1594}
1595
1596void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1597 DCHECK(Contains(cursor));
1598 if (!instruction_list.IsEmpty()) {
1599 if (cursor == last_instruction_) {
1600 last_instruction_ = instruction_list.last_instruction_;
1601 } else {
1602 cursor->next_->previous_ = instruction_list.last_instruction_;
1603 }
1604 instruction_list.last_instruction_->next_ = cursor->next_;
1605 cursor->next_ = instruction_list.first_instruction_;
1606 instruction_list.first_instruction_->previous_ = cursor;
1607 }
1608}
1609
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001610void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1611 DCHECK(Contains(cursor));
1612 if (!instruction_list.IsEmpty()) {
1613 if (cursor == first_instruction_) {
1614 first_instruction_ = instruction_list.first_instruction_;
1615 } else {
1616 cursor->previous_->next_ = instruction_list.first_instruction_;
1617 }
1618 instruction_list.last_instruction_->next_ = cursor;
1619 instruction_list.first_instruction_->previous_ = cursor->previous_;
1620 cursor->previous_ = instruction_list.last_instruction_;
1621 }
1622}
1623
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001624void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001625 if (IsEmpty()) {
1626 first_instruction_ = instruction_list.first_instruction_;
1627 last_instruction_ = instruction_list.last_instruction_;
1628 } else {
1629 AddAfter(last_instruction_, instruction_list);
1630 }
1631}
1632
David Brazdil04ff4e82015-12-10 13:54:52 +00001633// Should be called on instructions in a dead block in post order. This method
1634// assumes `insn` has been removed from all users with the exception of catch
1635// phis because of missing exceptional edges in the graph. It removes the
1636// instruction from catch phi uses, together with inputs of other catch phis in
1637// the catch block at the same index, as these must be dead too.
1638static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1639 DCHECK(!insn->HasEnvironmentUses());
1640 while (insn->HasNonEnvironmentUses()) {
1641 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1642 size_t use_index = use->GetIndex();
1643 HBasicBlock* user_block = use->GetUser()->GetBlock();
1644 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1645 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1646 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1647 }
1648 }
1649}
1650
David Brazdil2d7352b2015-04-20 14:52:42 +01001651void HBasicBlock::DisconnectAndDelete() {
1652 // Dominators must be removed after all the blocks they dominate. This way
1653 // a loop header is removed last, a requirement for correct loop information
1654 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001655 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001656
David Brazdil9eeebf62016-03-24 11:18:15 +00001657 // The following steps gradually remove the block from all its dependants in
1658 // post order (b/27683071).
1659
1660 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1661 // We need to do this before step (4) which destroys the predecessor list.
1662 HBasicBlock* loop_update_start = this;
1663 if (IsLoopHeader()) {
1664 HLoopInformation* loop_info = GetLoopInformation();
1665 // All other blocks in this loop should have been removed because the header
1666 // was their dominator.
1667 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1668 DCHECK(!loop_info->IsIrreducible());
1669 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1670 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1671 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001672 }
1673
David Brazdil9eeebf62016-03-24 11:18:15 +00001674 // (2) Disconnect the block from its successors and update their phis.
1675 for (HBasicBlock* successor : successors_) {
1676 // Delete this block from the list of predecessors.
1677 size_t this_index = successor->GetPredecessorIndexOf(this);
1678 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1679
1680 // Check that `successor` has other predecessors, otherwise `this` is the
1681 // dominator of `successor` which violates the order DCHECKed at the top.
1682 DCHECK(!successor->predecessors_.empty());
1683
1684 // Remove this block's entries in the successor's phis. Skip exceptional
1685 // successors because catch phi inputs do not correspond to predecessor
1686 // blocks but throwing instructions. The inputs of the catch phis will be
1687 // updated in step (3).
1688 if (!successor->IsCatchBlock()) {
1689 if (successor->predecessors_.size() == 1u) {
1690 // The successor has just one predecessor left. Replace phis with the only
1691 // remaining input.
1692 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1693 HPhi* phi = phi_it.Current()->AsPhi();
1694 phi->ReplaceWith(phi->InputAt(1 - this_index));
1695 successor->RemovePhi(phi);
1696 }
1697 } else {
1698 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1699 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1700 }
1701 }
1702 }
1703 }
1704 successors_.clear();
1705
1706 // (3) Remove instructions and phis. Instructions should have no remaining uses
1707 // except in catch phis. If an instruction is used by a catch phi at `index`,
1708 // remove `index`-th input of all phis in the catch block since they are
1709 // guaranteed dead. Note that we may miss dead inputs this way but the
1710 // graph will always remain consistent.
1711 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1712 HInstruction* insn = it.Current();
1713 RemoveUsesOfDeadInstruction(insn);
1714 RemoveInstruction(insn);
1715 }
1716 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1717 HPhi* insn = it.Current()->AsPhi();
1718 RemoveUsesOfDeadInstruction(insn);
1719 RemovePhi(insn);
1720 }
1721
1722 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001723 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001724 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001725 // We should not see any back edges as they would have been removed by step (3).
1726 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1727
David Brazdil2d7352b2015-04-20 14:52:42 +01001728 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001729 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1730 // This block is the only normal-flow successor of the TryBoundary which
1731 // makes `predecessor` dead. Since DCE removes blocks in post order,
1732 // exception handlers of this TryBoundary were already visited and any
1733 // remaining handlers therefore must be live. We remove `predecessor` from
1734 // their list of predecessors.
1735 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1736 while (predecessor->GetSuccessors().size() > 1) {
1737 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1738 DCHECK(handler->IsCatchBlock());
1739 predecessor->RemoveSuccessor(handler);
1740 handler->RemovePredecessor(predecessor);
1741 }
1742 }
1743
David Brazdil2d7352b2015-04-20 14:52:42 +01001744 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001745 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1746 if (num_pred_successors == 1u) {
1747 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001748 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1749 // successor. Replace those with a HGoto.
1750 DCHECK(last_instruction->IsIf() ||
1751 last_instruction->IsPackedSwitch() ||
1752 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001753 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001754 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001755 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001756 // The predecessor has no remaining successors and therefore must be dead.
1757 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001758 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001759 predecessor->RemoveInstruction(last_instruction);
1760 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001761 // There are multiple successors left. The removed block might be a successor
1762 // of a PackedSwitch which will be completely removed (perhaps replaced with
1763 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1764 // case, leave `last_instruction` as is for now.
1765 DCHECK(last_instruction->IsPackedSwitch() ||
1766 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001767 }
David Brazdil46e2a392015-03-16 17:31:52 +00001768 }
Vladimir Marko60584552015-09-03 13:35:12 +00001769 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001770
David Brazdil9eeebf62016-03-24 11:18:15 +00001771 // (5) Remove the block from all loops it is included in. Skip the inner-most
1772 // loop if this is the loop header (see definition of `loop_update_start`)
1773 // because the loop header's predecessor list has been destroyed in step (4).
1774 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1775 HLoopInformation* loop_info = it.Current();
1776 loop_info->Remove(this);
1777 if (loop_info->IsBackEdge(*this)) {
1778 // If this was the last back edge of the loop, we deliberately leave the
1779 // loop in an inconsistent state and will fail GraphChecker unless the
1780 // entire loop is removed during the pass.
1781 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001782 }
1783 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001784
David Brazdil9eeebf62016-03-24 11:18:15 +00001785 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001786 dominator_->RemoveDominatedBlock(this);
1787 SetDominator(nullptr);
1788
David Brazdil9eeebf62016-03-24 11:18:15 +00001789 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001790 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001791 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001792}
1793
1794void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001795 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001796 DCHECK(ContainsElement(dominated_blocks_, other));
1797 DCHECK_EQ(GetSingleSuccessor(), other);
1798 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001799 DCHECK(other->GetPhis().IsEmpty());
1800
David Brazdil2d7352b2015-04-20 14:52:42 +01001801 // Move instructions from `other` to `this`.
1802 DCHECK(EndsWithControlFlowInstruction());
1803 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001804 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001805 other->instructions_.SetBlockOfInstructions(this);
1806 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001807
David Brazdil2d7352b2015-04-20 14:52:42 +01001808 // Remove `other` from the loops it is included in.
1809 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1810 HLoopInformation* loop_info = it.Current();
1811 loop_info->Remove(other);
1812 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001813 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001814 }
1815 }
1816
1817 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001818 successors_.clear();
1819 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001820 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001821 successor->ReplacePredecessor(other, this);
1822 }
1823
David Brazdil2d7352b2015-04-20 14:52:42 +01001824 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001825 RemoveDominatedBlock(other);
1826 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1827 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001828 dominated->SetDominator(this);
1829 }
Vladimir Marko60584552015-09-03 13:35:12 +00001830 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001831 other->dominator_ = nullptr;
1832
1833 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001834 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001835
1836 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001837 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001838 other->SetGraph(nullptr);
1839}
1840
1841void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1842 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001843 DCHECK(GetDominatedBlocks().empty());
1844 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001845 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001846 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001847 DCHECK(other->GetPhis().IsEmpty());
1848 DCHECK(!other->IsInLoop());
1849
1850 // Move instructions from `other` to `this`.
1851 instructions_.Add(other->GetInstructions());
1852 other->instructions_.SetBlockOfInstructions(this);
1853
1854 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001855 successors_.clear();
1856 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001857 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001858 successor->ReplacePredecessor(other, this);
1859 }
1860
1861 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001862 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1863 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001864 dominated->SetDominator(this);
1865 }
Vladimir Marko60584552015-09-03 13:35:12 +00001866 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001867 other->dominator_ = nullptr;
1868 other->graph_ = nullptr;
1869}
1870
1871void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001872 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001873 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001874 predecessor->ReplaceSuccessor(this, other);
1875 }
Vladimir Marko60584552015-09-03 13:35:12 +00001876 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001877 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001878 successor->ReplacePredecessor(this, other);
1879 }
Vladimir Marko60584552015-09-03 13:35:12 +00001880 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1881 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001882 }
1883 GetDominator()->ReplaceDominatedBlock(this, other);
1884 other->SetDominator(GetDominator());
1885 dominator_ = nullptr;
1886 graph_ = nullptr;
1887}
1888
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001889void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001890 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001891 DCHECK(block->GetSuccessors().empty());
1892 DCHECK(block->GetPredecessors().empty());
1893 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001894 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001895 DCHECK(block->GetInstructions().IsEmpty());
1896 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001897
David Brazdilc7af85d2015-05-26 12:05:55 +01001898 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06001899 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01001900 }
1901
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001902 RemoveElement(reverse_post_order_, block);
1903 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001904}
1905
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00001906void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
1907 HBasicBlock* reference,
1908 bool replace_if_back_edge) {
1909 if (block->IsLoopHeader()) {
1910 // Clear the information of which blocks are contained in that loop. Since the
1911 // information is stored as a bit vector based on block ids, we have to update
1912 // it, as those block ids were specific to the callee graph and we are now adding
1913 // these blocks to the caller graph.
1914 block->GetLoopInformation()->ClearAllBlocks();
1915 }
1916
1917 // If not already in a loop, update the loop information.
1918 if (!block->IsInLoop()) {
1919 block->SetLoopInformation(reference->GetLoopInformation());
1920 }
1921
1922 // If the block is in a loop, update all its outward loops.
1923 HLoopInformation* loop_info = block->GetLoopInformation();
1924 if (loop_info != nullptr) {
1925 for (HLoopInformationOutwardIterator loop_it(*block);
1926 !loop_it.Done();
1927 loop_it.Advance()) {
1928 loop_it.Current()->Add(block);
1929 }
1930 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
1931 loop_info->ReplaceBackEdge(reference, block);
1932 }
1933 }
1934
1935 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
1936 TryCatchInformation* try_catch_info = reference->IsTryBlock()
1937 ? reference->GetTryCatchInformation()
1938 : nullptr;
1939 block->SetTryCatchInformation(try_catch_info);
1940}
1941
Calin Juravle2e768302015-07-28 14:41:11 +00001942HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001943 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001944 // Update the environments in this graph to have the invoke's environment
1945 // as parent.
1946 {
1947 HReversePostOrderIterator it(*this);
1948 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1949 for (; !it.Done(); it.Advance()) {
1950 HBasicBlock* block = it.Current();
1951 for (HInstructionIterator instr_it(block->GetInstructions());
1952 !instr_it.Done();
1953 instr_it.Advance()) {
1954 HInstruction* current = instr_it.Current();
1955 if (current->NeedsEnvironment()) {
1956 current->GetEnvironment()->SetAndCopyParentChain(
1957 outer_graph->GetArena(), invoke->GetEnvironment());
1958 }
1959 }
1960 }
1961 }
1962 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1963 if (HasBoundsChecks()) {
1964 outer_graph->SetHasBoundsChecks(true);
1965 }
1966
Calin Juravle2e768302015-07-28 14:41:11 +00001967 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001968 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001969 // Simple case of an entry block, a body block, and an exit block.
1970 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001971 HBasicBlock* body = GetBlocks()[1];
1972 DCHECK(GetBlocks()[0]->IsEntryBlock());
1973 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001974 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001975 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001976 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001977
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001978 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
1979 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001980 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001981
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001982 // Replace the invoke with the return value of the inlined graph.
1983 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001984 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001985 } else {
1986 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001987 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001988
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001989 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001990 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001991 // Need to inline multiple blocks. We split `invoke`'s block
1992 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001993 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001994 // with the second half.
1995 ArenaAllocator* allocator = outer_graph->GetArena();
1996 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001997 // Note that we split before the invoke only to simplify polymorphic inlining.
1998 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001999
Vladimir Markoec7802a2015-10-01 20:57:57 +01002000 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002001 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002002 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002003 exit_block_->ReplaceWith(to);
2004
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002005 // Update the meta information surrounding blocks:
2006 // (1) the graph they are now in,
2007 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002008 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002009 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002010 // Note that we do not need to update catch phi inputs because they
2011 // correspond to the register file of the outer method which the inlinee
2012 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002013
2014 // We don't add the entry block, the exit block, and the first block, which
2015 // has been merged with `at`.
2016 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2017
2018 // We add the `to` block.
2019 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002020 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002021 + kNumberOfNewBlocksInCaller;
2022
2023 // Find the location of `at` in the outer graph's reverse post order. The new
2024 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002025 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002026 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2027
David Brazdil95177982015-10-30 12:56:58 -05002028 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2029 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002030 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
2031 HBasicBlock* current = it.Current();
2032 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002033 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002034 DCHECK(current->GetGraph() == this);
2035 current->SetGraph(outer_graph);
2036 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002037 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002038 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002039 }
2040 }
2041
David Brazdil95177982015-10-30 12:56:58 -05002042 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002043 to->SetGraph(outer_graph);
2044 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002045 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002046 // Only `to` can become a back edge, as the inlined blocks
2047 // are predecessors of `to`.
2048 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002049
David Brazdil3f523062016-02-29 16:53:33 +00002050 // Update all predecessors of the exit block (now the `to` block)
2051 // to not `HReturn` but `HGoto` instead.
2052 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
2053 if (to->GetPredecessors().size() == 1) {
2054 HBasicBlock* predecessor = to->GetPredecessors()[0];
2055 HInstruction* last = predecessor->GetLastInstruction();
2056 if (!returns_void) {
2057 return_value = last->InputAt(0);
2058 }
2059 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2060 predecessor->RemoveInstruction(last);
2061 } else {
2062 if (!returns_void) {
2063 // There will be multiple returns.
2064 return_value = new (allocator) HPhi(
2065 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2066 to->AddPhi(return_value->AsPhi());
2067 }
2068 for (HBasicBlock* predecessor : to->GetPredecessors()) {
2069 HInstruction* last = predecessor->GetLastInstruction();
2070 if (!returns_void) {
2071 DCHECK(last->IsReturn());
2072 return_value->AsPhi()->AddInput(last->InputAt(0));
2073 }
2074 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2075 predecessor->RemoveInstruction(last);
2076 }
2077 }
2078 }
David Brazdil05144f42015-04-16 15:18:00 +01002079
2080 // Walk over the entry block and:
2081 // - Move constants from the entry block to the outer_graph's entry block,
2082 // - Replace HParameterValue instructions with their real value.
2083 // - Remove suspend checks, that hold an environment.
2084 // We must do this after the other blocks have been inlined, otherwise ids of
2085 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002086 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002087 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2088 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002089 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002090 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002091 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002092 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002093 replacement = outer_graph->GetIntConstant(
2094 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002095 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002096 replacement = outer_graph->GetLongConstant(
2097 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002098 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002099 replacement = outer_graph->GetFloatConstant(
2100 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002101 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002102 replacement = outer_graph->GetDoubleConstant(
2103 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002104 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002105 if (kIsDebugBuild
2106 && invoke->IsInvokeStaticOrDirect()
2107 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2108 // Ensure we do not use the last input of `invoke`, as it
2109 // contains a clinit check which is not an actual argument.
2110 size_t last_input_index = invoke->InputCount() - 1;
2111 DCHECK(parameter_index != last_input_index);
2112 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002113 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002114 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002115 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002116 } else {
2117 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2118 entry_block_->RemoveInstruction(current);
2119 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002120 if (replacement != nullptr) {
2121 current->ReplaceWith(replacement);
2122 // If the current is the return value then we need to update the latter.
2123 if (current == return_value) {
2124 DCHECK_EQ(entry_block_, return_value->GetBlock());
2125 return_value = replacement;
2126 }
2127 }
2128 }
2129
Calin Juravle2e768302015-07-28 14:41:11 +00002130 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002131}
2132
Mingyao Yang3584bce2015-05-19 16:01:59 -07002133/*
2134 * Loop will be transformed to:
2135 * old_pre_header
2136 * |
2137 * if_block
2138 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002139 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002140 * \ /
2141 * new_pre_header
2142 * |
2143 * header
2144 */
2145void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2146 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002147 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002148
Aart Bik3fc7f352015-11-20 22:03:03 -08002149 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002150 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002151 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2152 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002153 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2154 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002155 AddBlock(true_block);
2156 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002157 AddBlock(new_pre_header);
2158
Aart Bik3fc7f352015-11-20 22:03:03 -08002159 header->ReplacePredecessor(old_pre_header, new_pre_header);
2160 old_pre_header->successors_.clear();
2161 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002162
Aart Bik3fc7f352015-11-20 22:03:03 -08002163 old_pre_header->AddSuccessor(if_block);
2164 if_block->AddSuccessor(true_block); // True successor
2165 if_block->AddSuccessor(false_block); // False successor
2166 true_block->AddSuccessor(new_pre_header);
2167 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002168
Aart Bik3fc7f352015-11-20 22:03:03 -08002169 old_pre_header->dominated_blocks_.push_back(if_block);
2170 if_block->SetDominator(old_pre_header);
2171 if_block->dominated_blocks_.push_back(true_block);
2172 true_block->SetDominator(if_block);
2173 if_block->dominated_blocks_.push_back(false_block);
2174 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002175 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002176 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002177 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002178 header->SetDominator(new_pre_header);
2179
Aart Bik3fc7f352015-11-20 22:03:03 -08002180 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002181 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002182 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002183 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002184 reverse_post_order_[index_of_header++] = true_block;
2185 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002186 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002187
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002188 // The pre_header can never be a back edge of a loop.
2189 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2190 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2191 UpdateLoopAndTryInformationOfNewBlock(
2192 if_block, old_pre_header, /* replace_if_back_edge */ false);
2193 UpdateLoopAndTryInformationOfNewBlock(
2194 true_block, old_pre_header, /* replace_if_back_edge */ false);
2195 UpdateLoopAndTryInformationOfNewBlock(
2196 false_block, old_pre_header, /* replace_if_back_edge */ false);
2197 UpdateLoopAndTryInformationOfNewBlock(
2198 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002199}
2200
David Brazdilf5552582015-12-27 13:36:12 +00002201static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2202 SHARED_REQUIRES(Locks::mutator_lock_) {
2203 if (rti.IsValid()) {
2204 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2205 << " upper_bound_rti: " << upper_bound_rti
2206 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002207 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2208 << " upper_bound_rti: " << upper_bound_rti
2209 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002210 }
2211}
2212
Calin Juravle2e768302015-07-28 14:41:11 +00002213void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2214 if (kIsDebugBuild) {
2215 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2216 ScopedObjectAccess soa(Thread::Current());
2217 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2218 if (IsBoundType()) {
2219 // Having the test here spares us from making the method virtual just for
2220 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002221 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002222 }
2223 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002224 reference_type_handle_ = rti.GetTypeHandle();
2225 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002226}
2227
David Brazdilf5552582015-12-27 13:36:12 +00002228void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2229 if (kIsDebugBuild) {
2230 ScopedObjectAccess soa(Thread::Current());
2231 DCHECK(upper_bound.IsValid());
2232 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2233 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2234 }
2235 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002236 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002237}
2238
Vladimir Markoa1de9182016-02-25 11:37:38 +00002239ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002240 if (kIsDebugBuild) {
2241 ScopedObjectAccess soa(Thread::Current());
2242 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002243 if (!is_exact) {
2244 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2245 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2246 }
Calin Juravle2e768302015-07-28 14:41:11 +00002247 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002248 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002249}
2250
Calin Juravleacf735c2015-02-12 15:25:22 +00002251std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2252 ScopedObjectAccess soa(Thread::Current());
2253 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002254 << " is_valid=" << rhs.IsValid()
2255 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002256 << " is_exact=" << rhs.IsExact()
2257 << " ]";
2258 return os;
2259}
2260
Mark Mendellc4701932015-04-10 13:18:51 -04002261bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2262 // For now, assume that instructions in different blocks may use the
2263 // environment.
2264 // TODO: Use the control flow to decide if this is true.
2265 if (GetBlock() != other->GetBlock()) {
2266 return true;
2267 }
2268
2269 // We know that we are in the same block. Walk from 'this' to 'other',
2270 // checking to see if there is any instruction with an environment.
2271 HInstruction* current = this;
2272 for (; current != other && current != nullptr; current = current->GetNext()) {
2273 // This is a conservative check, as the instruction result may not be in
2274 // the referenced environment.
2275 if (current->HasEnvironment()) {
2276 return true;
2277 }
2278 }
2279
2280 // We should have been called with 'this' before 'other' in the block.
2281 // Just confirm this.
2282 DCHECK(current != nullptr);
2283 return false;
2284}
2285
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002286void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002287 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2288 IntrinsicSideEffects side_effects,
2289 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002290 intrinsic_ = intrinsic;
2291 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002292
Aart Bik5d75afe2015-12-14 11:57:01 -08002293 // Adjust method's side effects from intrinsic table.
2294 switch (side_effects) {
2295 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2296 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2297 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2298 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2299 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002300
2301 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2302 opt.SetDoesNotNeedDexCache();
2303 opt.SetDoesNotNeedEnvironment();
2304 } else {
2305 // If we need an environment, that means there will be a call, which can trigger GC.
2306 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2307 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002308 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002309 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002310}
2311
David Brazdil6de19382016-01-08 17:37:10 +00002312bool HNewInstance::IsStringAlloc() const {
2313 ScopedObjectAccess soa(Thread::Current());
2314 return GetReferenceTypeInfo().IsStringClass();
2315}
2316
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002317bool HInvoke::NeedsEnvironment() const {
2318 if (!IsIntrinsic()) {
2319 return true;
2320 }
2321 IntrinsicOptimizations opt(*this);
2322 return !opt.GetDoesNotNeedEnvironment();
2323}
2324
Vladimir Markodc151b22015-10-15 18:02:30 +01002325bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2326 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002327 return false;
2328 }
2329 if (!IsIntrinsic()) {
2330 return true;
2331 }
2332 IntrinsicOptimizations opt(*this);
2333 return !opt.GetDoesNotNeedDexCache();
2334}
2335
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002336void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2337 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2338 input->AddUseAt(this, index);
2339 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2340 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2341 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2342 InputRecordAt(i).GetUseNode()->SetIndex(i);
2343 }
2344}
2345
Vladimir Markob554b5a2015-11-06 12:57:55 +00002346void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2347 RemoveAsUserOfInput(index);
2348 inputs_.erase(inputs_.begin() + index);
2349 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2350 for (size_t i = index, e = InputCount(); i < e; ++i) {
2351 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2352 InputRecordAt(i).GetUseNode()->SetIndex(i);
2353 }
2354}
2355
Vladimir Markof64242a2015-12-01 14:58:23 +00002356std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2357 switch (rhs) {
2358 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2359 return os << "string_init";
2360 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2361 return os << "recursive";
2362 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2363 return os << "direct";
2364 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2365 return os << "direct_fixup";
2366 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2367 return os << "dex_cache_pc_relative";
2368 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2369 return os << "dex_cache_via_method";
2370 default:
2371 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2372 UNREACHABLE();
2373 }
2374}
2375
Vladimir Markofbb184a2015-11-13 14:47:00 +00002376std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2377 switch (rhs) {
2378 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2379 return os << "explicit";
2380 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2381 return os << "implicit";
2382 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2383 return os << "none";
2384 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002385 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2386 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002387 }
2388}
2389
Mark Mendellc4701932015-04-10 13:18:51 -04002390void HInstruction::RemoveEnvironmentUsers() {
2391 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2392 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2393 HEnvironment* user = user_node->GetUser();
2394 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2395 }
2396 env_uses_.Clear();
2397}
2398
Roland Levillainc9b21f82016-03-23 16:36:59 +00002399// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002400HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2401 ArenaAllocator* allocator = GetArena();
2402
2403 if (cond->IsCondition() &&
2404 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2405 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2406 HInstruction* lhs = cond->InputAt(0);
2407 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002408 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002409 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2410 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2411 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2412 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2413 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2414 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2415 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2416 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2417 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2418 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2419 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002420 default:
2421 LOG(FATAL) << "Unexpected condition";
2422 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002423 }
2424 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2425 return replacement;
2426 } else if (cond->IsIntConstant()) {
2427 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002428 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002429 return GetIntConstant(1);
2430 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002431 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002432 return GetIntConstant(0);
2433 }
2434 } else {
2435 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2436 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2437 return replacement;
2438 }
2439}
2440
Roland Levillainc9285912015-12-18 10:38:42 +00002441std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2442 os << "["
2443 << " source=" << rhs.GetSource()
2444 << " destination=" << rhs.GetDestination()
2445 << " type=" << rhs.GetType()
2446 << " instruction=";
2447 if (rhs.GetInstruction() != nullptr) {
2448 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2449 } else {
2450 os << "null";
2451 }
2452 os << " ]";
2453 return os;
2454}
2455
Roland Levillain86503782016-02-11 19:07:30 +00002456std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2457 switch (rhs) {
2458 case TypeCheckKind::kUnresolvedCheck:
2459 return os << "unresolved_check";
2460 case TypeCheckKind::kExactCheck:
2461 return os << "exact_check";
2462 case TypeCheckKind::kClassHierarchyCheck:
2463 return os << "class_hierarchy_check";
2464 case TypeCheckKind::kAbstractClassCheck:
2465 return os << "abstract_class_check";
2466 case TypeCheckKind::kInterfaceCheck:
2467 return os << "interface_check";
2468 case TypeCheckKind::kArrayObjectCheck:
2469 return os << "array_object_check";
2470 case TypeCheckKind::kArrayCheck:
2471 return os << "array_check";
2472 default:
2473 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2474 UNREACHABLE();
2475 }
2476}
2477
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002478} // namespace art