blob: b26ce0aa13413b7c499fcddc367b1e24079288fc [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 Markofa6b93c2015-09-15 10:15:55 +010057 ArenaBitVector visiting(arena_, blocks_.size(), false);
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;
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000130 }
131 }
132}
133
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000134GraphAnalysisResult HGraph::BuildDominatorTree() {
David Brazdilffee3d32015-07-06 11:48:53 +0100135 // (1) Simplify the CFG so that catch blocks have only exceptional incoming
136 // edges. This invariant simplifies building SSA form because Phis cannot
137 // collect both normal- and exceptional-flow values at the same time.
138 SimplifyCatchBlocks();
139
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100140 ArenaBitVector visited(arena_, blocks_.size(), false);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000141
David Brazdilffee3d32015-07-06 11:48:53 +0100142 // (2) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000143 FindBackEdges(&visited);
144
David Brazdilffee3d32015-07-06 11:48:53 +0100145 // (3) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000146 // the initial DFS as users from other instructions, so that
147 // users can be safely removed before uses later.
148 RemoveInstructionsAsUsersFromDeadBlocks(visited);
149
David Brazdilffee3d32015-07-06 11:48:53 +0100150 // (4) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000151 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000152 // predecessors list of live blocks.
153 RemoveDeadBlocks(visited);
154
David Brazdilffee3d32015-07-06 11:48:53 +0100155 // (5) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100156 // dominators and the reverse post order.
157 SimplifyCFG();
158
David Brazdilffee3d32015-07-06 11:48:53 +0100159 // (6) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100160 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000161
162 // (7) Analyze loops discover through back edge analysis, and
163 // set the loop information on each block.
164 GraphAnalysisResult result = AnalyzeLoops();
165 if (result != kAnalysisSuccess) {
166 return result;
167 }
168
169 // (8) Precompute per-block try membership before entering the SSA builder,
170 // which needs the information to build catch block phis from values of
171 // locals at throwing instructions inside try blocks.
172 ComputeTryBlockInformation();
173
174 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100175}
176
177void HGraph::ClearDominanceInformation() {
178 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
179 it.Current()->ClearDominanceInformation();
180 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100181 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100182}
183
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000184void HGraph::ClearLoopInformation() {
185 SetHasIrreducibleLoops(false);
186 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000187 it.Current()->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000188 }
189}
190
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100191void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000192 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100193 dominator_ = nullptr;
194}
195
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000196HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
197 HInstruction* instruction = GetFirstInstruction();
198 while (instruction->IsParallelMove()) {
199 instruction = instruction->GetNext();
200 }
201 return instruction;
202}
203
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100204void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100205 DCHECK(reverse_post_order_.empty());
206 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100207 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100208
209 // Number of visits of a given node, indexed by block id.
210 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter());
211 // Number of successors visited from a given node, indexed by block id.
212 ArenaVector<size_t> successors_visited(blocks_.size(), 0u, arena_->Adapter());
213 // Nodes for which we need to visit successors.
214 ArenaVector<HBasicBlock*> worklist(arena_->Adapter());
215 constexpr size_t kDefaultWorklistSize = 8;
216 worklist.reserve(kDefaultWorklistSize);
217 worklist.push_back(entry_block_);
218
219 while (!worklist.empty()) {
220 HBasicBlock* current = worklist.back();
221 uint32_t current_id = current->GetBlockId();
222 if (successors_visited[current_id] == current->GetSuccessors().size()) {
223 worklist.pop_back();
224 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100225 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
226
227 if (successor->GetDominator() == nullptr) {
228 successor->SetDominator(current);
229 } else {
Vladimir Marko391d01f2015-11-06 11:02:08 +0000230 // The CommonDominator can work for multiple blocks as long as the
231 // domination information doesn't change. However, since we're changing
232 // that information here, we can use the finder only for pairs of blocks.
233 successor->SetDominator(CommonDominator::ForPair(successor->GetDominator(), current));
Vladimir Markod76d1392015-09-23 16:07:14 +0100234 }
235
236 // Once all the forward edges have been visited, we know the immediate
237 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100238 if (++visits[successor->GetBlockId()] ==
239 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100240 reverse_post_order_.push_back(successor);
241 worklist.push_back(successor);
242 }
243 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000244 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000245
246 // Populate `dominated_blocks_` information after computing all dominators.
247 // The potential presence of irreducible loops require to do it after.
248 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
249 HBasicBlock* block = it.Current();
250 if (!block->IsEntryBlock()) {
251 block->GetDominator()->AddDominatedBlock(block);
252 }
253 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000254}
255
David Brazdilfc6a86a2015-06-26 10:33:45 +0000256HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000257 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
258 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000259 // Use `InsertBetween` to ensure the predecessor index and successor index of
260 // `block` and `successor` are preserved.
261 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000262 return new_block;
263}
264
265void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
266 // Insert a new node between `block` and `successor` to split the
267 // critical edge.
268 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600269 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100270 if (successor->IsLoopHeader()) {
271 // If we split at a back edge boundary, make the new block the back edge.
272 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000273 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100274 info->RemoveBackEdge(block);
275 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100276 }
277 }
278}
279
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100280void HGraph::SimplifyLoop(HBasicBlock* header) {
281 HLoopInformation* info = header->GetLoopInformation();
282
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100283 // Make sure the loop has only one pre header. This simplifies SSA building by having
284 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000285 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
286 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000287 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000288 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100289 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100290 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600291 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100292
Vladimir Marko60584552015-09-03 13:35:12 +0000293 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100294 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100295 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100296 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100297 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100298 }
299 }
300 pre_header->AddSuccessor(header);
301 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100302
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100303 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100304 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
305 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000306 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100307 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100308 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000309 header->predecessors_[pred] = to_swap;
310 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100311 break;
312 }
313 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100314 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100315
316 // Place the suspend check at the beginning of the header, so that live registers
317 // will be known when allocating registers. Note that code generation can still
318 // generate the suspend check at the back edge, but needs to be careful with
319 // loop phi spill slots (which are not written to at back edge).
320 HInstruction* first_instruction = header->GetFirstInstruction();
321 if (!first_instruction->IsSuspendCheck()) {
322 HSuspendCheck* check = new (arena_) HSuspendCheck(header->GetDexPc());
323 header->InsertInstructionBefore(check, first_instruction);
324 first_instruction = check;
325 }
326 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100327}
328
David Brazdilffee3d32015-07-06 11:48:53 +0100329static bool CheckIfPredecessorAtIsExceptional(const HBasicBlock& block, size_t pred_idx) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100330 HBasicBlock* predecessor = block.GetPredecessors()[pred_idx];
David Brazdilffee3d32015-07-06 11:48:53 +0100331 if (!predecessor->EndsWithTryBoundary()) {
332 // Only edges from HTryBoundary can be exceptional.
333 return false;
334 }
335 HTryBoundary* try_boundary = predecessor->GetLastInstruction()->AsTryBoundary();
336 if (try_boundary->GetNormalFlowSuccessor() == &block) {
337 // This block is the normal-flow successor of `try_boundary`, but it could
338 // also be one of its exception handlers if catch blocks have not been
339 // simplified yet. Predecessors are unordered, so we will consider the first
340 // occurrence to be the normal edge and a possible second occurrence to be
341 // the exceptional edge.
342 return !block.IsFirstIndexOfPredecessor(predecessor, pred_idx);
343 } else {
344 // This is not the normal-flow successor of `try_boundary`, hence it must be
345 // one of its exception handlers.
346 DCHECK(try_boundary->HasExceptionHandler(block));
347 return true;
348 }
349}
350
351void HGraph::SimplifyCatchBlocks() {
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100352 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
353 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
354 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
355 HBasicBlock* catch_block = blocks_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000356 if (catch_block == nullptr || !catch_block->IsCatchBlock()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100357 continue;
358 }
359
360 bool exceptional_predecessors_only = true;
Vladimir Marko60584552015-09-03 13:35:12 +0000361 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
David Brazdilffee3d32015-07-06 11:48:53 +0100362 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
363 exceptional_predecessors_only = false;
364 break;
365 }
366 }
367
368 if (!exceptional_predecessors_only) {
369 // Catch block has normal-flow predecessors and needs to be simplified.
370 // Splitting the block before its first instruction moves all its
371 // instructions into `normal_block` and links the two blocks with a Goto.
372 // Afterwards, incoming normal-flow edges are re-linked to `normal_block`,
373 // leaving `catch_block` with the exceptional edges only.
David Brazdil9bc43612015-11-05 21:25:24 +0000374 //
David Brazdilffee3d32015-07-06 11:48:53 +0100375 // Note that catch blocks with normal-flow predecessors cannot begin with
David Brazdil9bc43612015-11-05 21:25:24 +0000376 // a move-exception instruction, as guaranteed by the verifier. However,
377 // trivially dead predecessors are ignored by the verifier and such code
378 // has not been removed at this stage. We therefore ignore the assumption
379 // and rely on GraphChecker to enforce it after initial DCE is run (b/25492628).
380 HBasicBlock* normal_block = catch_block->SplitCatchBlockAfterMoveException();
381 if (normal_block == nullptr) {
382 // Catch block is either empty or only contains a move-exception. It must
383 // therefore be dead and will be removed during initial DCE. Do nothing.
384 DCHECK(!catch_block->EndsWithControlFlowInstruction());
385 } else {
386 // Catch block was split. Re-link normal-flow edges to the new block.
387 for (size_t j = 0; j < catch_block->GetPredecessors().size(); ++j) {
388 if (!CheckIfPredecessorAtIsExceptional(*catch_block, j)) {
389 catch_block->GetPredecessors()[j]->ReplaceSuccessor(catch_block, normal_block);
390 --j;
391 }
David Brazdilffee3d32015-07-06 11:48:53 +0100392 }
393 }
394 }
395 }
396}
397
398void HGraph::ComputeTryBlockInformation() {
399 // Iterate in reverse post order to propagate try membership information from
400 // predecessors to their successors.
401 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
402 HBasicBlock* block = it.Current();
403 if (block->IsEntryBlock() || block->IsCatchBlock()) {
404 // Catch blocks after simplification have only exceptional predecessors
405 // and hence are never in tries.
406 continue;
407 }
408
409 // Infer try membership from the first predecessor. Having simplified loops,
410 // the first predecessor can never be a back edge and therefore it must have
411 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100412 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100413 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100414 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000415 if (try_entry != nullptr &&
416 (block->GetTryCatchInformation() == nullptr ||
417 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
418 // We are either setting try block membership for the first time or it
419 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100420 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
421 }
David Brazdilffee3d32015-07-06 11:48:53 +0100422 }
423}
424
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100425void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000426// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100427 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000428 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100429 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
430 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
431 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
432 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100433 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000434 if (block->GetSuccessors().size() > 1) {
435 // Only split normal-flow edges. We cannot split exceptional edges as they
436 // are synthesized (approximate real control flow), and we do not need to
437 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000438 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
439 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
440 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100441 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000442 if (successor == exit_block_) {
443 // Throw->TryBoundary->Exit. Special case which we do not want to split
444 // because Goto->Exit is not allowed.
445 DCHECK(block->IsSingleTryBoundary());
446 DCHECK(block->GetSinglePredecessor()->GetLastInstruction()->IsThrow());
447 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100448 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000449 // SplitCriticalEdge could have invalidated the `normal_successors`
450 // ArrayRef. We must re-acquire it.
451 normal_successors = block->GetNormalSuccessors();
452 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
453 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100454 }
455 }
456 }
457 if (block->IsLoopHeader()) {
458 SimplifyLoop(block);
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000459 } else if (!block->IsEntryBlock() && block->GetFirstInstruction()->IsSuspendCheck()) {
460 // We are being called by the dead code elimiation pass, and what used to be
461 // a loop got dismantled. Just remove the suspend check.
462 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100463 }
464 }
465}
466
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000467GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100468 // Order does not matter.
469 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
470 HBasicBlock* block = it.Current();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100471 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100472 if (block->IsCatchBlock()) {
473 // TODO: Dealing with exceptional back edges could be tricky because
474 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000475 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100476 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000477 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100478 }
479 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000480 return kAnalysisSuccess;
481}
482
483void HLoopInformation::Dump(std::ostream& os) {
484 os << "header: " << header_->GetBlockId() << std::endl;
485 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
486 for (HBasicBlock* block : back_edges_) {
487 os << "back edge: " << block->GetBlockId() << std::endl;
488 }
489 for (HBasicBlock* block : header_->GetPredecessors()) {
490 os << "predecessor: " << block->GetBlockId() << std::endl;
491 }
492 for (uint32_t idx : blocks_.Indexes()) {
493 os << " in loop: " << idx << std::endl;
494 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100495}
496
David Brazdil8d5b8b22015-03-24 10:51:52 +0000497void HGraph::InsertConstant(HConstant* constant) {
498 // New constants are inserted before the final control-flow instruction
499 // of the graph, or at its end if called from the graph builder.
500 if (entry_block_->EndsWithControlFlowInstruction()) {
501 entry_block_->InsertInstructionBefore(constant, entry_block_->GetLastInstruction());
David Brazdil46e2a392015-03-16 17:31:52 +0000502 } else {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000503 entry_block_->AddInstruction(constant);
David Brazdil46e2a392015-03-16 17:31:52 +0000504 }
505}
506
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600507HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100508 // For simplicity, don't bother reviving the cached null constant if it is
509 // not null and not in a block. Otherwise, we need to clear the instruction
510 // id and/or any invariants the graph is assuming when adding new instructions.
511 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600512 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000513 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000514 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000515 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000516 if (kIsDebugBuild) {
517 ScopedObjectAccess soa(Thread::Current());
518 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
519 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000520 return cached_null_constant_;
521}
522
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100523HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100524 // For simplicity, don't bother reviving the cached current method if it is
525 // not null and not in a block. Otherwise, we need to clear the instruction
526 // id and/or any invariants the graph is assuming when adding new instructions.
527 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700528 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600529 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
530 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100531 if (entry_block_->GetFirstInstruction() == nullptr) {
532 entry_block_->AddInstruction(cached_current_method_);
533 } else {
534 entry_block_->InsertInstructionBefore(
535 cached_current_method_, entry_block_->GetFirstInstruction());
536 }
537 }
538 return cached_current_method_;
539}
540
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600541HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000542 switch (type) {
543 case Primitive::Type::kPrimBoolean:
544 DCHECK(IsUint<1>(value));
545 FALLTHROUGH_INTENDED;
546 case Primitive::Type::kPrimByte:
547 case Primitive::Type::kPrimChar:
548 case Primitive::Type::kPrimShort:
549 case Primitive::Type::kPrimInt:
550 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600551 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000552
553 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600554 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000555
556 default:
557 LOG(FATAL) << "Unsupported constant type";
558 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000559 }
David Brazdil46e2a392015-03-16 17:31:52 +0000560}
561
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000562void HGraph::CacheFloatConstant(HFloatConstant* constant) {
563 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
564 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
565 cached_float_constants_.Overwrite(value, constant);
566}
567
568void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
569 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
570 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
571 cached_double_constants_.Overwrite(value, constant);
572}
573
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000574void HLoopInformation::Add(HBasicBlock* block) {
575 blocks_.SetBit(block->GetBlockId());
576}
577
David Brazdil46e2a392015-03-16 17:31:52 +0000578void HLoopInformation::Remove(HBasicBlock* block) {
579 blocks_.ClearBit(block->GetBlockId());
580}
581
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100582void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
583 if (blocks_.IsBitSet(block->GetBlockId())) {
584 return;
585 }
586
587 blocks_.SetBit(block->GetBlockId());
588 block->SetInLoop(this);
Vladimir Marko60584552015-09-03 13:35:12 +0000589 for (HBasicBlock* predecessor : block->GetPredecessors()) {
590 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100591 }
592}
593
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000594void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block) {
595 if (blocks_.IsBitSet(block->GetBlockId())) {
596 return;
597 }
598
599 if (block->IsLoopHeader()) {
600 // If we hit a loop header in an irreducible loop, we first check if the
601 // pre header of that loop belongs to the currently analyzed loop. If it does,
602 // then we visit the back edges.
603 // Note that we cannot use GetPreHeader, as the loop may have not been populated
604 // yet.
605 HBasicBlock* pre_header = block->GetPredecessors()[0];
606 PopulateIrreducibleRecursive(pre_header);
607 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
608 blocks_.SetBit(block->GetBlockId());
609 block->SetInLoop(this);
610 HLoopInformation* info = block->GetLoopInformation();
611 for (HBasicBlock* back_edge : info->GetBackEdges()) {
612 PopulateIrreducibleRecursive(back_edge);
613 }
614 }
615 } else {
616 // Visit all predecessors. If one predecessor is part of the loop, this
617 // block is also part of this loop.
618 for (HBasicBlock* predecessor : block->GetPredecessors()) {
619 PopulateIrreducibleRecursive(predecessor);
620 if (blocks_.IsBitSet(predecessor->GetBlockId())) {
621 blocks_.SetBit(block->GetBlockId());
622 block->SetInLoop(this);
623 }
624 }
625 }
626}
627
628void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100629 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000630 // Populate this loop: starting with the back edge, recursively add predecessors
631 // that are not already part of that loop. Set the header as part of the loop
632 // to end the recursion.
633 // This is a recursive implementation of the algorithm described in
634 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
635 blocks_.SetBit(header_->GetBlockId());
636 header_->SetInLoop(this);
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100637 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100638 DCHECK(back_edge->GetDominator() != nullptr);
639 if (!header_->Dominates(back_edge)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000640 irreducible_ = true;
641 header_->GetGraph()->SetHasIrreducibleLoops(true);
642 PopulateIrreducibleRecursive(back_edge);
643 } else {
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +0000644 if (header_->GetGraph()->IsCompilingOsr()) {
645 irreducible_ = true;
646 header_->GetGraph()->SetHasIrreducibleLoops(true);
647 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000648 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100649 }
David Brazdila4b8c212015-05-07 09:59:30 +0100650 }
651}
652
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100653HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000654 HBasicBlock* block = header_->GetPredecessors()[0];
655 DCHECK(irreducible_ || (block == header_->GetDominator()));
656 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100657}
658
659bool HLoopInformation::Contains(const HBasicBlock& block) const {
660 return blocks_.IsBitSet(block.GetBlockId());
661}
662
663bool HLoopInformation::IsIn(const HLoopInformation& other) const {
664 return other.blocks_.IsBitSet(header_->GetBlockId());
665}
666
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800667bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
668 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700669}
670
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100671size_t HLoopInformation::GetLifetimeEnd() const {
672 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100673 for (HBasicBlock* back_edge : GetBackEdges()) {
674 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100675 }
676 return last_position;
677}
678
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100679bool HBasicBlock::Dominates(HBasicBlock* other) const {
680 // Walk up the dominator tree from `other`, to find out if `this`
681 // is an ancestor.
682 HBasicBlock* current = other;
683 while (current != nullptr) {
684 if (current == this) {
685 return true;
686 }
687 current = current->GetDominator();
688 }
689 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100690}
691
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100692static void UpdateInputsUsers(HInstruction* instruction) {
693 for (size_t i = 0, e = instruction->InputCount(); i < e; ++i) {
694 instruction->InputAt(i)->AddUseAt(instruction, i);
695 }
696 // Environment should be created later.
697 DCHECK(!instruction->HasEnvironment());
698}
699
Roland Levillainccc07a92014-09-16 14:48:16 +0100700void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
701 HInstruction* replacement) {
702 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400703 if (initial->IsControlFlow()) {
704 // We can only replace a control flow instruction with another control flow instruction.
705 DCHECK(replacement->IsControlFlow());
706 DCHECK_EQ(replacement->GetId(), -1);
707 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
708 DCHECK_EQ(initial->GetBlock(), this);
709 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
710 DCHECK(initial->GetUses().IsEmpty());
711 DCHECK(initial->GetEnvUses().IsEmpty());
712 replacement->SetBlock(this);
713 replacement->SetId(GetGraph()->GetNextInstructionId());
714 instructions_.InsertInstructionBefore(replacement, initial);
715 UpdateInputsUsers(replacement);
716 } else {
717 InsertInstructionBefore(replacement, initial);
718 initial->ReplaceWith(replacement);
719 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100720 RemoveInstruction(initial);
721}
722
David Brazdil74eb1b22015-12-14 11:44:01 +0000723void HBasicBlock::MoveInstructionBefore(HInstruction* insn, HInstruction* cursor) {
724 DCHECK(!cursor->IsPhi());
725 DCHECK(!insn->IsPhi());
726 DCHECK(!insn->IsControlFlow());
727 DCHECK(insn->CanBeMoved());
728 DCHECK(!insn->HasSideEffects());
729
730 HBasicBlock* from_block = insn->GetBlock();
731 HBasicBlock* to_block = cursor->GetBlock();
732 DCHECK(from_block != to_block);
733
734 from_block->RemoveInstruction(insn, /* ensure_safety */ false);
735 insn->SetBlock(to_block);
736 to_block->instructions_.InsertInstructionBefore(insn, cursor);
737}
738
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100739static void Add(HInstructionList* instruction_list,
740 HBasicBlock* block,
741 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000742 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000743 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100744 instruction->SetBlock(block);
745 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100746 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100747 instruction_list->AddInstruction(instruction);
748}
749
750void HBasicBlock::AddInstruction(HInstruction* instruction) {
751 Add(&instructions_, this, instruction);
752}
753
754void HBasicBlock::AddPhi(HPhi* phi) {
755 Add(&phis_, this, phi);
756}
757
David Brazdilc3d743f2015-04-22 13:40:50 +0100758void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
759 DCHECK(!cursor->IsPhi());
760 DCHECK(!instruction->IsPhi());
761 DCHECK_EQ(instruction->GetId(), -1);
762 DCHECK_NE(cursor->GetId(), -1);
763 DCHECK_EQ(cursor->GetBlock(), this);
764 DCHECK(!instruction->IsControlFlow());
765 instruction->SetBlock(this);
766 instruction->SetId(GetGraph()->GetNextInstructionId());
767 UpdateInputsUsers(instruction);
768 instructions_.InsertInstructionBefore(instruction, cursor);
769}
770
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100771void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
772 DCHECK(!cursor->IsPhi());
773 DCHECK(!instruction->IsPhi());
774 DCHECK_EQ(instruction->GetId(), -1);
775 DCHECK_NE(cursor->GetId(), -1);
776 DCHECK_EQ(cursor->GetBlock(), this);
777 DCHECK(!instruction->IsControlFlow());
778 DCHECK(!cursor->IsControlFlow());
779 instruction->SetBlock(this);
780 instruction->SetId(GetGraph()->GetNextInstructionId());
781 UpdateInputsUsers(instruction);
782 instructions_.InsertInstructionAfter(instruction, cursor);
783}
784
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100785void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
786 DCHECK_EQ(phi->GetId(), -1);
787 DCHECK_NE(cursor->GetId(), -1);
788 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100789 phi->SetBlock(this);
790 phi->SetId(GetGraph()->GetNextInstructionId());
791 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100792 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100793}
794
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100795static void Remove(HInstructionList* instruction_list,
796 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000797 HInstruction* instruction,
798 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100799 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100800 instruction->SetBlock(nullptr);
801 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000802 if (ensure_safety) {
803 DCHECK(instruction->GetUses().IsEmpty());
804 DCHECK(instruction->GetEnvUses().IsEmpty());
805 RemoveAsUser(instruction);
806 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100807}
808
David Brazdil1abb4192015-02-17 18:33:36 +0000809void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100810 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000811 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100812}
813
David Brazdil1abb4192015-02-17 18:33:36 +0000814void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
815 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100816}
817
David Brazdilc7508e92015-04-27 13:28:57 +0100818void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
819 if (instruction->IsPhi()) {
820 RemovePhi(instruction->AsPhi(), ensure_safety);
821 } else {
822 RemoveInstruction(instruction, ensure_safety);
823 }
824}
825
Vladimir Marko71bf8092015-09-15 15:33:14 +0100826void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
827 for (size_t i = 0; i < locals.size(); i++) {
828 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100829 SetRawEnvAt(i, instruction);
830 if (instruction != nullptr) {
831 instruction->AddEnvUseAt(this, i);
832 }
833 }
834}
835
David Brazdiled596192015-01-23 10:39:45 +0000836void HEnvironment::CopyFrom(HEnvironment* env) {
837 for (size_t i = 0; i < env->Size(); i++) {
838 HInstruction* instruction = env->GetInstructionAt(i);
839 SetRawEnvAt(i, instruction);
840 if (instruction != nullptr) {
841 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100842 }
David Brazdiled596192015-01-23 10:39:45 +0000843 }
844}
845
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700846void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
847 HBasicBlock* loop_header) {
848 DCHECK(loop_header->IsLoopHeader());
849 for (size_t i = 0; i < env->Size(); i++) {
850 HInstruction* instruction = env->GetInstructionAt(i);
851 SetRawEnvAt(i, instruction);
852 if (instruction == nullptr) {
853 continue;
854 }
855 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
856 // At the end of the loop pre-header, the corresponding value for instruction
857 // is the first input of the phi.
858 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700859 SetRawEnvAt(i, initial);
860 initial->AddEnvUseAt(this, i);
861 } else {
862 instruction->AddEnvUseAt(this, i);
863 }
864 }
865}
866
David Brazdil1abb4192015-02-17 18:33:36 +0000867void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100868 const HUserRecord<HEnvironment*>& user_record = vregs_[index];
David Brazdil1abb4192015-02-17 18:33:36 +0000869 user_record.GetInstruction()->RemoveEnvironmentUser(user_record.GetUseNode());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100870}
871
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000872HInstruction::InstructionKind HInstruction::GetKind() const {
873 return GetKindInternal();
874}
875
Calin Juravle77520bc2015-01-12 18:45:46 +0000876HInstruction* HInstruction::GetNextDisregardingMoves() const {
877 HInstruction* next = GetNext();
878 while (next != nullptr && next->IsParallelMove()) {
879 next = next->GetNext();
880 }
881 return next;
882}
883
884HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
885 HInstruction* previous = GetPrevious();
886 while (previous != nullptr && previous->IsParallelMove()) {
887 previous = previous->GetPrevious();
888 }
889 return previous;
890}
891
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100892void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000893 if (first_instruction_ == nullptr) {
894 DCHECK(last_instruction_ == nullptr);
895 first_instruction_ = last_instruction_ = instruction;
896 } else {
897 last_instruction_->next_ = instruction;
898 instruction->previous_ = last_instruction_;
899 last_instruction_ = instruction;
900 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000901}
902
David Brazdilc3d743f2015-04-22 13:40:50 +0100903void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
904 DCHECK(Contains(cursor));
905 if (cursor == first_instruction_) {
906 cursor->previous_ = instruction;
907 instruction->next_ = cursor;
908 first_instruction_ = instruction;
909 } else {
910 instruction->previous_ = cursor->previous_;
911 instruction->next_ = cursor;
912 cursor->previous_ = instruction;
913 instruction->previous_->next_ = instruction;
914 }
915}
916
917void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
918 DCHECK(Contains(cursor));
919 if (cursor == last_instruction_) {
920 cursor->next_ = instruction;
921 instruction->previous_ = cursor;
922 last_instruction_ = instruction;
923 } else {
924 instruction->next_ = cursor->next_;
925 instruction->previous_ = cursor;
926 cursor->next_ = instruction;
927 instruction->next_->previous_ = instruction;
928 }
929}
930
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100931void HInstructionList::RemoveInstruction(HInstruction* instruction) {
932 if (instruction->previous_ != nullptr) {
933 instruction->previous_->next_ = instruction->next_;
934 }
935 if (instruction->next_ != nullptr) {
936 instruction->next_->previous_ = instruction->previous_;
937 }
938 if (instruction == first_instruction_) {
939 first_instruction_ = instruction->next_;
940 }
941 if (instruction == last_instruction_) {
942 last_instruction_ = instruction->previous_;
943 }
944}
945
Roland Levillain6b469232014-09-25 10:10:38 +0100946bool HInstructionList::Contains(HInstruction* instruction) const {
947 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
948 if (it.Current() == instruction) {
949 return true;
950 }
951 }
952 return false;
953}
954
Roland Levillainccc07a92014-09-16 14:48:16 +0100955bool HInstructionList::FoundBefore(const HInstruction* instruction1,
956 const HInstruction* instruction2) const {
957 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
958 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
959 if (it.Current() == instruction1) {
960 return true;
961 }
962 if (it.Current() == instruction2) {
963 return false;
964 }
965 }
966 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
967 return true;
968}
969
Roland Levillain6c82d402014-10-13 16:10:27 +0100970bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
971 if (other_instruction == this) {
972 // An instruction does not strictly dominate itself.
973 return false;
974 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100975 HBasicBlock* block = GetBlock();
976 HBasicBlock* other_block = other_instruction->GetBlock();
977 if (block != other_block) {
978 return GetBlock()->Dominates(other_instruction->GetBlock());
979 } else {
980 // If both instructions are in the same block, ensure this
981 // instruction comes before `other_instruction`.
982 if (IsPhi()) {
983 if (!other_instruction->IsPhi()) {
984 // Phis appear before non phi-instructions so this instruction
985 // dominates `other_instruction`.
986 return true;
987 } else {
988 // There is no order among phis.
989 LOG(FATAL) << "There is no dominance between phis of a same block.";
990 return false;
991 }
992 } else {
993 // `this` is not a phi.
994 if (other_instruction->IsPhi()) {
995 // Phis appear before non phi-instructions so this instruction
996 // does not dominate `other_instruction`.
997 return false;
998 } else {
999 // Check whether this instruction comes before
1000 // `other_instruction` in the instruction list.
1001 return block->GetInstructions().FoundBefore(this, other_instruction);
1002 }
1003 }
1004 }
1005}
1006
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001007void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001008 DCHECK(other != nullptr);
David Brazdiled596192015-01-23 10:39:45 +00001009 for (HUseIterator<HInstruction*> it(GetUses()); !it.Done(); it.Advance()) {
1010 HUseListNode<HInstruction*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001011 HInstruction* user = current->GetUser();
1012 size_t input_index = current->GetIndex();
1013 user->SetRawInputAt(input_index, other);
1014 other->AddUseAt(user, input_index);
1015 }
1016
David Brazdiled596192015-01-23 10:39:45 +00001017 for (HUseIterator<HEnvironment*> it(GetEnvUses()); !it.Done(); it.Advance()) {
1018 HUseListNode<HEnvironment*>* current = it.Current();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001019 HEnvironment* user = current->GetUser();
1020 size_t input_index = current->GetIndex();
1021 user->SetRawEnvAt(input_index, other);
1022 other->AddEnvUseAt(user, input_index);
1023 }
1024
David Brazdiled596192015-01-23 10:39:45 +00001025 uses_.Clear();
1026 env_uses_.Clear();
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001027}
1028
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001029void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
David Brazdil1abb4192015-02-17 18:33:36 +00001030 RemoveAsUserOfInput(index);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001031 SetRawInputAt(index, replacement);
1032 replacement->AddUseAt(this, index);
1033}
1034
Nicolas Geoffray39468442014-09-02 15:17:15 +01001035size_t HInstruction::EnvironmentSize() const {
1036 return HasEnvironment() ? environment_->Size() : 0;
1037}
1038
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001039void HPhi::AddInput(HInstruction* input) {
1040 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001041 inputs_.push_back(HUserRecord<HInstruction*>(input));
1042 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001043}
1044
David Brazdil2d7352b2015-04-20 14:52:42 +01001045void HPhi::RemoveInputAt(size_t index) {
1046 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001047 inputs_.erase(inputs_.begin() + index);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001048 for (size_t i = index, e = InputCount(); i < e; ++i) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001049 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001050 InputRecordAt(i).GetUseNode()->SetIndex(i);
1051 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001052}
1053
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001054#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001055void H##name::Accept(HGraphVisitor* visitor) { \
1056 visitor->Visit##name(this); \
1057}
1058
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001059FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001060
1061#undef DEFINE_ACCEPT
1062
1063void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001064 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1065 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001066 if (block != nullptr) {
1067 VisitBasicBlock(block);
1068 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001069 }
1070}
1071
Roland Levillain633021e2014-10-01 14:12:25 +01001072void HGraphVisitor::VisitReversePostOrder() {
1073 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1074 VisitBasicBlock(it.Current());
1075 }
1076}
1077
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001078void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001079 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001080 it.Current()->Accept(this);
1081 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001082 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001083 it.Current()->Accept(this);
1084 }
1085}
1086
Mark Mendelle82549b2015-05-06 10:55:34 -04001087HConstant* HTypeConversion::TryStaticEvaluation() const {
1088 HGraph* graph = GetBlock()->GetGraph();
1089 if (GetInput()->IsIntConstant()) {
1090 int32_t value = GetInput()->AsIntConstant()->GetValue();
1091 switch (GetResultType()) {
1092 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001093 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001094 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001095 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001096 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001097 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001098 default:
1099 return nullptr;
1100 }
1101 } else if (GetInput()->IsLongConstant()) {
1102 int64_t value = GetInput()->AsLongConstant()->GetValue();
1103 switch (GetResultType()) {
1104 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001105 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001106 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001107 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001108 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001109 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001110 default:
1111 return nullptr;
1112 }
1113 } else if (GetInput()->IsFloatConstant()) {
1114 float value = GetInput()->AsFloatConstant()->GetValue();
1115 switch (GetResultType()) {
1116 case Primitive::kPrimInt:
1117 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001118 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001119 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001120 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001121 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001122 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1123 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001124 case Primitive::kPrimLong:
1125 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001126 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001127 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001128 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001129 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001130 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1131 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001132 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001133 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001134 default:
1135 return nullptr;
1136 }
1137 } else if (GetInput()->IsDoubleConstant()) {
1138 double value = GetInput()->AsDoubleConstant()->GetValue();
1139 switch (GetResultType()) {
1140 case Primitive::kPrimInt:
1141 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001142 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001143 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001144 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001145 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001146 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1147 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001148 case Primitive::kPrimLong:
1149 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001150 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001151 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001152 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001153 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001154 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1155 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001156 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001157 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001158 default:
1159 return nullptr;
1160 }
1161 }
1162 return nullptr;
1163}
1164
Roland Levillain9240d6a2014-10-20 16:47:04 +01001165HConstant* HUnaryOperation::TryStaticEvaluation() const {
1166 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001167 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001168 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001169 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001170 } else if (kEnableFloatingPointStaticEvaluation) {
1171 if (GetInput()->IsFloatConstant()) {
1172 return Evaluate(GetInput()->AsFloatConstant());
1173 } else if (GetInput()->IsDoubleConstant()) {
1174 return Evaluate(GetInput()->AsDoubleConstant());
1175 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001176 }
1177 return nullptr;
1178}
1179
1180HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillain9867bc72015-08-05 10:21:34 +01001181 if (GetLeft()->IsIntConstant()) {
1182 if (GetRight()->IsIntConstant()) {
1183 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
1184 } else if (GetRight()->IsLongConstant()) {
1185 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsLongConstant());
1186 }
1187 } else if (GetLeft()->IsLongConstant()) {
1188 if (GetRight()->IsIntConstant()) {
1189 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1190 } else if (GetRight()->IsLongConstant()) {
1191 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001192 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001193 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
1194 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001195 } else if (kEnableFloatingPointStaticEvaluation) {
1196 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1197 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1198 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1199 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1200 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001201 }
1202 return nullptr;
1203}
Dave Allison20dfc792014-06-16 20:44:29 -07001204
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001205HConstant* HBinaryOperation::GetConstantRight() const {
1206 if (GetRight()->IsConstant()) {
1207 return GetRight()->AsConstant();
1208 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1209 return GetLeft()->AsConstant();
1210 } else {
1211 return nullptr;
1212 }
1213}
1214
1215// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001216// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001217HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1218 HInstruction* most_constant_right = GetConstantRight();
1219 if (most_constant_right == nullptr) {
1220 return nullptr;
1221 } else if (most_constant_right == GetLeft()) {
1222 return GetRight();
1223 } else {
1224 return GetLeft();
1225 }
1226}
1227
Roland Levillain31dd3d62016-02-16 12:21:02 +00001228std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1229 switch (rhs) {
1230 case ComparisonBias::kNoBias:
1231 return os << "no_bias";
1232 case ComparisonBias::kGtBias:
1233 return os << "gt_bias";
1234 case ComparisonBias::kLtBias:
1235 return os << "lt_bias";
1236 default:
1237 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1238 UNREACHABLE();
1239 }
1240}
1241
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001242bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1243 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001244}
1245
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001246bool HInstruction::Equals(HInstruction* other) const {
1247 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001248 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001249 if (!InstructionDataEquals(other)) return false;
1250 if (GetType() != other->GetType()) return false;
1251 if (InputCount() != other->InputCount()) return false;
1252
1253 for (size_t i = 0, e = InputCount(); i < e; ++i) {
1254 if (InputAt(i) != other->InputAt(i)) return false;
1255 }
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001256 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001257 return true;
1258}
1259
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001260std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1261#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1262 switch (rhs) {
1263 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1264 default:
1265 os << "Unknown instruction kind " << static_cast<int>(rhs);
1266 break;
1267 }
1268#undef DECLARE_CASE
1269 return os;
1270}
1271
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001272void HInstruction::MoveBefore(HInstruction* cursor) {
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001273 next_->previous_ = previous_;
1274 if (previous_ != nullptr) {
1275 previous_->next_ = next_;
1276 }
1277 if (block_->instructions_.first_instruction_ == this) {
1278 block_->instructions_.first_instruction_ = next_;
1279 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001280 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001281
1282 previous_ = cursor->previous_;
1283 if (previous_ != nullptr) {
1284 previous_->next_ = this;
1285 }
1286 next_ = cursor;
1287 cursor->previous_ = this;
1288 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001289
1290 if (block_->instructions_.first_instruction_ == cursor) {
1291 block_->instructions_.first_instruction_ = this;
1292 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001293}
1294
Vladimir Markofb337ea2015-11-25 15:25:10 +00001295void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1296 DCHECK(!CanThrow());
1297 DCHECK(!HasSideEffects());
1298 DCHECK(!HasEnvironmentUses());
1299 DCHECK(HasNonEnvironmentUses());
1300 DCHECK(!IsPhi()); // Makes no sense for Phi.
1301 DCHECK_EQ(InputCount(), 0u);
1302
1303 // Find the target block.
1304 HUseIterator<HInstruction*> uses_it(GetUses());
1305 HBasicBlock* target_block = uses_it.Current()->GetUser()->GetBlock();
1306 uses_it.Advance();
1307 while (!uses_it.Done() && uses_it.Current()->GetUser()->GetBlock() == target_block) {
1308 uses_it.Advance();
1309 }
1310 if (!uses_it.Done()) {
1311 // This instruction has uses in two or more blocks. Find the common dominator.
1312 CommonDominator finder(target_block);
1313 for (; !uses_it.Done(); uses_it.Advance()) {
1314 finder.Update(uses_it.Current()->GetUser()->GetBlock());
1315 }
1316 target_block = finder.Get();
1317 DCHECK(target_block != nullptr);
1318 }
1319 // Move to the first dominator not in a loop.
1320 while (target_block->IsInLoop()) {
1321 target_block = target_block->GetDominator();
1322 DCHECK(target_block != nullptr);
1323 }
1324
1325 // Find insertion position.
1326 HInstruction* insert_pos = nullptr;
1327 for (HUseIterator<HInstruction*> uses_it2(GetUses()); !uses_it2.Done(); uses_it2.Advance()) {
1328 if (uses_it2.Current()->GetUser()->GetBlock() == target_block &&
1329 (insert_pos == nullptr || uses_it2.Current()->GetUser()->StrictlyDominates(insert_pos))) {
1330 insert_pos = uses_it2.Current()->GetUser();
1331 }
1332 }
1333 if (insert_pos == nullptr) {
1334 // No user in `target_block`, insert before the control flow instruction.
1335 insert_pos = target_block->GetLastInstruction();
1336 DCHECK(insert_pos->IsControlFlow());
1337 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1338 if (insert_pos->IsIf()) {
1339 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1340 if (if_input == insert_pos->GetPrevious()) {
1341 insert_pos = if_input;
1342 }
1343 }
1344 }
1345 MoveBefore(insert_pos);
1346}
1347
David Brazdilfc6a86a2015-06-26 10:33:45 +00001348HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001349 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001350 DCHECK_EQ(cursor->GetBlock(), this);
1351
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001352 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1353 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001354 new_block->instructions_.first_instruction_ = cursor;
1355 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1356 instructions_.last_instruction_ = cursor->previous_;
1357 if (cursor->previous_ == nullptr) {
1358 instructions_.first_instruction_ = nullptr;
1359 } else {
1360 cursor->previous_->next_ = nullptr;
1361 cursor->previous_ = nullptr;
1362 }
1363
1364 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001365 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001366
Vladimir Marko60584552015-09-03 13:35:12 +00001367 for (HBasicBlock* successor : GetSuccessors()) {
1368 new_block->successors_.push_back(successor);
1369 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001370 }
Vladimir Marko60584552015-09-03 13:35:12 +00001371 successors_.clear();
David Brazdilfc6a86a2015-06-26 10:33:45 +00001372 AddSuccessor(new_block);
1373
David Brazdil56e1acc2015-06-30 15:41:36 +01001374 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001375 return new_block;
1376}
1377
David Brazdild7558da2015-09-22 13:04:14 +01001378HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001379 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001380 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1381
1382 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1383
1384 for (HBasicBlock* predecessor : GetPredecessors()) {
1385 new_block->predecessors_.push_back(predecessor);
1386 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1387 }
1388 predecessors_.clear();
1389 AddPredecessor(new_block);
1390
1391 GetGraph()->AddBlock(new_block);
1392 return new_block;
1393}
1394
David Brazdil9bc43612015-11-05 21:25:24 +00001395HBasicBlock* HBasicBlock::SplitCatchBlockAfterMoveException() {
1396 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
1397 DCHECK(IsCatchBlock()) << "This method is intended for catch blocks only.";
1398
1399 HInstruction* first_insn = GetFirstInstruction();
1400 HInstruction* split_before = nullptr;
1401
1402 if (first_insn != nullptr && first_insn->IsLoadException()) {
1403 // Catch block starts with a LoadException. Split the block after
1404 // the StoreLocal and ClearException which must come after the load.
1405 DCHECK(first_insn->GetNext()->IsStoreLocal());
1406 DCHECK(first_insn->GetNext()->GetNext()->IsClearException());
1407 split_before = first_insn->GetNext()->GetNext()->GetNext();
1408 } else {
1409 // Catch block does not load the exception. Split at the beginning
1410 // to create an empty catch block.
1411 split_before = first_insn;
1412 }
1413
1414 if (split_before == nullptr) {
1415 // Catch block has no instructions after the split point (must be dead).
1416 // Do not split it but rather signal error by returning nullptr.
1417 return nullptr;
1418 } else {
1419 return SplitBefore(split_before);
1420 }
1421}
1422
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001423HBasicBlock* HBasicBlock::SplitAfter(HInstruction* cursor) {
1424 DCHECK(!cursor->IsControlFlow());
1425 DCHECK_NE(instructions_.last_instruction_, cursor);
1426 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001427
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001428 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1429 new_block->instructions_.first_instruction_ = cursor->GetNext();
1430 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1431 cursor->next_->previous_ = nullptr;
1432 cursor->next_ = nullptr;
1433 instructions_.last_instruction_ = cursor;
1434
1435 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001436 for (HBasicBlock* successor : GetSuccessors()) {
1437 new_block->successors_.push_back(successor);
1438 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001439 }
Vladimir Marko60584552015-09-03 13:35:12 +00001440 successors_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001441
Vladimir Marko60584552015-09-03 13:35:12 +00001442 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001443 dominated->dominator_ = new_block;
Vladimir Marko60584552015-09-03 13:35:12 +00001444 new_block->dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001445 }
Vladimir Marko60584552015-09-03 13:35:12 +00001446 dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001447 return new_block;
1448}
1449
David Brazdilec16f792015-08-19 15:04:01 +01001450const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001451 if (EndsWithTryBoundary()) {
1452 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1453 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001454 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001455 return try_boundary;
1456 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001457 DCHECK(IsTryBlock());
1458 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001459 return nullptr;
1460 }
David Brazdilec16f792015-08-19 15:04:01 +01001461 } else if (IsTryBlock()) {
1462 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001463 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001464 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001465 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001466}
1467
David Brazdild7558da2015-09-22 13:04:14 +01001468bool HBasicBlock::HasThrowingInstructions() const {
1469 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1470 if (it.Current()->CanThrow()) {
1471 return true;
1472 }
1473 }
1474 return false;
1475}
1476
David Brazdilfc6a86a2015-06-26 10:33:45 +00001477static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1478 return block.GetPhis().IsEmpty()
1479 && !block.GetInstructions().IsEmpty()
1480 && block.GetFirstInstruction() == block.GetLastInstruction();
1481}
1482
David Brazdil46e2a392015-03-16 17:31:52 +00001483bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001484 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1485}
1486
1487bool HBasicBlock::IsSingleTryBoundary() const {
1488 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001489}
1490
David Brazdil8d5b8b22015-03-24 10:51:52 +00001491bool HBasicBlock::EndsWithControlFlowInstruction() const {
1492 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1493}
1494
David Brazdilb2bd1c52015-03-25 11:17:37 +00001495bool HBasicBlock::EndsWithIf() const {
1496 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1497}
1498
David Brazdilffee3d32015-07-06 11:48:53 +01001499bool HBasicBlock::EndsWithTryBoundary() const {
1500 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1501}
1502
David Brazdilb2bd1c52015-03-25 11:17:37 +00001503bool HBasicBlock::HasSinglePhi() const {
1504 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1505}
1506
David Brazdild26a4112015-11-10 11:07:31 +00001507ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1508 if (EndsWithTryBoundary()) {
1509 // The normal-flow successor of HTryBoundary is always stored at index zero.
1510 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1511 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1512 } else {
1513 // All successors of blocks not ending with TryBoundary are normal.
1514 return ArrayRef<HBasicBlock* const>(successors_);
1515 }
1516}
1517
1518ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1519 if (EndsWithTryBoundary()) {
1520 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1521 } else {
1522 // Blocks not ending with TryBoundary do not have exceptional successors.
1523 return ArrayRef<HBasicBlock* const>();
1524 }
1525}
1526
David Brazdilffee3d32015-07-06 11:48:53 +01001527bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001528 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1529 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1530
1531 size_t length = handlers1.size();
1532 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001533 return false;
1534 }
1535
David Brazdilb618ade2015-07-29 10:31:29 +01001536 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001537 for (size_t i = 0; i < length; ++i) {
1538 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001539 return false;
1540 }
1541 }
1542 return true;
1543}
1544
David Brazdil2d7352b2015-04-20 14:52:42 +01001545size_t HInstructionList::CountSize() const {
1546 size_t size = 0;
1547 HInstruction* current = first_instruction_;
1548 for (; current != nullptr; current = current->GetNext()) {
1549 size++;
1550 }
1551 return size;
1552}
1553
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001554void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1555 for (HInstruction* current = first_instruction_;
1556 current != nullptr;
1557 current = current->GetNext()) {
1558 current->SetBlock(block);
1559 }
1560}
1561
1562void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1563 DCHECK(Contains(cursor));
1564 if (!instruction_list.IsEmpty()) {
1565 if (cursor == last_instruction_) {
1566 last_instruction_ = instruction_list.last_instruction_;
1567 } else {
1568 cursor->next_->previous_ = instruction_list.last_instruction_;
1569 }
1570 instruction_list.last_instruction_->next_ = cursor->next_;
1571 cursor->next_ = instruction_list.first_instruction_;
1572 instruction_list.first_instruction_->previous_ = cursor;
1573 }
1574}
1575
1576void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001577 if (IsEmpty()) {
1578 first_instruction_ = instruction_list.first_instruction_;
1579 last_instruction_ = instruction_list.last_instruction_;
1580 } else {
1581 AddAfter(last_instruction_, instruction_list);
1582 }
1583}
1584
David Brazdil04ff4e82015-12-10 13:54:52 +00001585// Should be called on instructions in a dead block in post order. This method
1586// assumes `insn` has been removed from all users with the exception of catch
1587// phis because of missing exceptional edges in the graph. It removes the
1588// instruction from catch phi uses, together with inputs of other catch phis in
1589// the catch block at the same index, as these must be dead too.
1590static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1591 DCHECK(!insn->HasEnvironmentUses());
1592 while (insn->HasNonEnvironmentUses()) {
1593 HUseListNode<HInstruction*>* use = insn->GetUses().GetFirst();
1594 size_t use_index = use->GetIndex();
1595 HBasicBlock* user_block = use->GetUser()->GetBlock();
1596 DCHECK(use->GetUser()->IsPhi() && user_block->IsCatchBlock());
1597 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1598 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1599 }
1600 }
1601}
1602
David Brazdil2d7352b2015-04-20 14:52:42 +01001603void HBasicBlock::DisconnectAndDelete() {
1604 // Dominators must be removed after all the blocks they dominate. This way
1605 // a loop header is removed last, a requirement for correct loop information
1606 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001607 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001608
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001609 // (1) Remove the block from all loops it is included in.
David Brazdil2d7352b2015-04-20 14:52:42 +01001610 for (HLoopInformationOutwardIterator it(*this); !it.Done(); it.Advance()) {
1611 HLoopInformation* loop_info = it.Current();
1612 loop_info->Remove(this);
1613 if (loop_info->IsBackEdge(*this)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001614 // If this was the last back edge of the loop, we deliberately leave the
David Brazdilbadd8262016-02-02 16:28:56 +00001615 // loop in an inconsistent state and will fail GraphChecker unless the
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001616 // entire loop is removed during the pass.
David Brazdil2d7352b2015-04-20 14:52:42 +01001617 loop_info->RemoveBackEdge(this);
1618 }
1619 }
1620
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001621 // (2) Disconnect the block from its predecessors and update their
1622 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001623 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001624 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001625 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1626 // This block is the only normal-flow successor of the TryBoundary which
1627 // makes `predecessor` dead. Since DCE removes blocks in post order,
1628 // exception handlers of this TryBoundary were already visited and any
1629 // remaining handlers therefore must be live. We remove `predecessor` from
1630 // their list of predecessors.
1631 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1632 while (predecessor->GetSuccessors().size() > 1) {
1633 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1634 DCHECK(handler->IsCatchBlock());
1635 predecessor->RemoveSuccessor(handler);
1636 handler->RemovePredecessor(predecessor);
1637 }
1638 }
1639
David Brazdil2d7352b2015-04-20 14:52:42 +01001640 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001641 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1642 if (num_pred_successors == 1u) {
1643 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001644 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1645 // successor. Replace those with a HGoto.
1646 DCHECK(last_instruction->IsIf() ||
1647 last_instruction->IsPackedSwitch() ||
1648 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001649 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001650 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001651 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001652 // The predecessor has no remaining successors and therefore must be dead.
1653 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001654 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001655 predecessor->RemoveInstruction(last_instruction);
1656 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001657 // There are multiple successors left. The removed block might be a successor
1658 // of a PackedSwitch which will be completely removed (perhaps replaced with
1659 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1660 // case, leave `last_instruction` as is for now.
1661 DCHECK(last_instruction->IsPackedSwitch() ||
1662 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001663 }
David Brazdil46e2a392015-03-16 17:31:52 +00001664 }
Vladimir Marko60584552015-09-03 13:35:12 +00001665 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001666
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001667 // (3) Disconnect the block from its successors and update their phis.
Vladimir Marko60584552015-09-03 13:35:12 +00001668 for (HBasicBlock* successor : successors_) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001669 // Delete this block from the list of predecessors.
1670 size_t this_index = successor->GetPredecessorIndexOf(this);
Vladimir Marko60584552015-09-03 13:35:12 +00001671 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
David Brazdil2d7352b2015-04-20 14:52:42 +01001672
1673 // Check that `successor` has other predecessors, otherwise `this` is the
1674 // dominator of `successor` which violates the order DCHECKed at the top.
Vladimir Marko60584552015-09-03 13:35:12 +00001675 DCHECK(!successor->predecessors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001676
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001677 // Remove this block's entries in the successor's phis. Skip exceptional
1678 // successors because catch phi inputs do not correspond to predecessor
1679 // blocks but throwing instructions. Their inputs will be updated in step (4).
1680 if (!successor->IsCatchBlock()) {
1681 if (successor->predecessors_.size() == 1u) {
1682 // The successor has just one predecessor left. Replace phis with the only
1683 // remaining input.
1684 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1685 HPhi* phi = phi_it.Current()->AsPhi();
1686 phi->ReplaceWith(phi->InputAt(1 - this_index));
1687 successor->RemovePhi(phi);
1688 }
1689 } else {
1690 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1691 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1692 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001693 }
1694 }
1695 }
Vladimir Marko60584552015-09-03 13:35:12 +00001696 successors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001697
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001698 // (4) Remove instructions and phis. Instructions should have no remaining uses
1699 // except in catch phis. If an instruction is used by a catch phi at `index`,
1700 // remove `index`-th input of all phis in the catch block since they are
1701 // guaranteed dead. Note that we may miss dead inputs this way but the
1702 // graph will always remain consistent.
1703 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1704 HInstruction* insn = it.Current();
David Brazdil04ff4e82015-12-10 13:54:52 +00001705 RemoveUsesOfDeadInstruction(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001706 RemoveInstruction(insn);
1707 }
1708 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
David Brazdil04ff4e82015-12-10 13:54:52 +00001709 HPhi* insn = it.Current()->AsPhi();
1710 RemoveUsesOfDeadInstruction(insn);
1711 RemovePhi(insn);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001712 }
1713
David Brazdil2d7352b2015-04-20 14:52:42 +01001714 // Disconnect from the dominator.
1715 dominator_->RemoveDominatedBlock(this);
1716 SetDominator(nullptr);
1717
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001718 // Delete from the graph, update reverse post order.
1719 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001720 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001721}
1722
1723void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001724 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001725 DCHECK(ContainsElement(dominated_blocks_, other));
1726 DCHECK_EQ(GetSingleSuccessor(), other);
1727 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001728 DCHECK(other->GetPhis().IsEmpty());
1729
David Brazdil2d7352b2015-04-20 14:52:42 +01001730 // Move instructions from `other` to `this`.
1731 DCHECK(EndsWithControlFlowInstruction());
1732 RemoveInstruction(GetLastInstruction());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001733 instructions_.Add(other->GetInstructions());
David Brazdil2d7352b2015-04-20 14:52:42 +01001734 other->instructions_.SetBlockOfInstructions(this);
1735 other->instructions_.Clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001736
David Brazdil2d7352b2015-04-20 14:52:42 +01001737 // Remove `other` from the loops it is included in.
1738 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1739 HLoopInformation* loop_info = it.Current();
1740 loop_info->Remove(other);
1741 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001742 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001743 }
1744 }
1745
1746 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001747 successors_.clear();
1748 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001749 HBasicBlock* successor = other->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001750 successor->ReplacePredecessor(other, this);
1751 }
1752
David Brazdil2d7352b2015-04-20 14:52:42 +01001753 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001754 RemoveDominatedBlock(other);
1755 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1756 dominated_blocks_.push_back(dominated);
David Brazdil2d7352b2015-04-20 14:52:42 +01001757 dominated->SetDominator(this);
1758 }
Vladimir Marko60584552015-09-03 13:35:12 +00001759 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001760 other->dominator_ = nullptr;
1761
1762 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001763 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001764
1765 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001766 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001767 other->SetGraph(nullptr);
1768}
1769
1770void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1771 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001772 DCHECK(GetDominatedBlocks().empty());
1773 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001774 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001775 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001776 DCHECK(other->GetPhis().IsEmpty());
1777 DCHECK(!other->IsInLoop());
1778
1779 // Move instructions from `other` to `this`.
1780 instructions_.Add(other->GetInstructions());
1781 other->instructions_.SetBlockOfInstructions(this);
1782
1783 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001784 successors_.clear();
1785 while (!other->successors_.empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001786 HBasicBlock* successor = other->GetSuccessors()[0];
David Brazdil2d7352b2015-04-20 14:52:42 +01001787 successor->ReplacePredecessor(other, this);
1788 }
1789
1790 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001791 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
1792 dominated_blocks_.push_back(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001793 dominated->SetDominator(this);
1794 }
Vladimir Marko60584552015-09-03 13:35:12 +00001795 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001796 other->dominator_ = nullptr;
1797 other->graph_ = nullptr;
1798}
1799
1800void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001801 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001802 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001803 predecessor->ReplaceSuccessor(this, other);
1804 }
Vladimir Marko60584552015-09-03 13:35:12 +00001805 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001806 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001807 successor->ReplacePredecessor(this, other);
1808 }
Vladimir Marko60584552015-09-03 13:35:12 +00001809 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1810 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001811 }
1812 GetDominator()->ReplaceDominatedBlock(this, other);
1813 other->SetDominator(GetDominator());
1814 dominator_ = nullptr;
1815 graph_ = nullptr;
1816}
1817
1818// Create space in `blocks` for adding `number_of_new_blocks` entries
1819// starting at location `at`. Blocks after `at` are moved accordingly.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001820static void MakeRoomFor(ArenaVector<HBasicBlock*>* blocks,
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001821 size_t number_of_new_blocks,
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001822 size_t after) {
1823 DCHECK_LT(after, blocks->size());
1824 size_t old_size = blocks->size();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001825 size_t new_size = old_size + number_of_new_blocks;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001826 blocks->resize(new_size);
1827 std::copy_backward(blocks->begin() + after + 1u, blocks->begin() + old_size, blocks->end());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001828}
1829
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001830void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001831 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001832 DCHECK(block->GetSuccessors().empty());
1833 DCHECK(block->GetPredecessors().empty());
1834 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001835 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001836 DCHECK(block->GetInstructions().IsEmpty());
1837 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001838
David Brazdilc7af85d2015-05-26 12:05:55 +01001839 if (block->IsExitBlock()) {
1840 exit_block_ = nullptr;
1841 }
1842
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001843 RemoveElement(reverse_post_order_, block);
1844 blocks_[block->GetBlockId()] = nullptr;
David Brazdil2d7352b2015-04-20 14:52:42 +01001845}
1846
Calin Juravle2e768302015-07-28 14:41:11 +00001847HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01001848 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01001849 // Update the environments in this graph to have the invoke's environment
1850 // as parent.
1851 {
1852 HReversePostOrderIterator it(*this);
1853 it.Advance(); // Skip the entry block, we do not need to update the entry's suspend check.
1854 for (; !it.Done(); it.Advance()) {
1855 HBasicBlock* block = it.Current();
1856 for (HInstructionIterator instr_it(block->GetInstructions());
1857 !instr_it.Done();
1858 instr_it.Advance()) {
1859 HInstruction* current = instr_it.Current();
1860 if (current->NeedsEnvironment()) {
1861 current->GetEnvironment()->SetAndCopyParentChain(
1862 outer_graph->GetArena(), invoke->GetEnvironment());
1863 }
1864 }
1865 }
1866 }
1867 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
1868 if (HasBoundsChecks()) {
1869 outer_graph->SetHasBoundsChecks(true);
1870 }
1871
Calin Juravle2e768302015-07-28 14:41:11 +00001872 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001873 if (GetBlocks().size() == 3) {
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001874 // Simple case of an entry block, a body block, and an exit block.
1875 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001876 HBasicBlock* body = GetBlocks()[1];
1877 DCHECK(GetBlocks()[0]->IsEntryBlock());
1878 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001879 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001880 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001881 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001882
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001883 invoke->GetBlock()->instructions_.AddAfter(invoke, body->GetInstructions());
1884 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001885
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001886 // Replace the invoke with the return value of the inlined graph.
1887 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00001888 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001889 } else {
1890 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001891 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001892
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001893 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001894 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001895 // Need to inline multiple blocks. We split `invoke`'s block
1896 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00001897 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001898 // with the second half.
1899 ArenaAllocator* allocator = outer_graph->GetArena();
1900 HBasicBlock* at = invoke->GetBlock();
1901 HBasicBlock* to = at->SplitAfter(invoke);
1902
Vladimir Markoec7802a2015-10-01 20:57:57 +01001903 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001904 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01001905 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001906 exit_block_->ReplaceWith(to);
1907
1908 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001909 // to not `HReturn` but `HGoto` instead.
Vladimir Markoec7802a2015-10-01 20:57:57 +01001910 bool returns_void = to->GetPredecessors()[0]->GetLastInstruction()->IsReturnVoid();
Vladimir Marko60584552015-09-03 13:35:12 +00001911 if (to->GetPredecessors().size() == 1) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001912 HBasicBlock* predecessor = to->GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001913 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001914 if (!returns_void) {
1915 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001916 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001917 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001918 predecessor->RemoveInstruction(last);
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001919 } else {
1920 if (!returns_void) {
1921 // There will be multiple returns.
Nicolas Geoffray4f1a3842015-03-12 10:34:11 +00001922 return_value = new (allocator) HPhi(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001923 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001924 to->AddPhi(return_value->AsPhi());
1925 }
Vladimir Marko60584552015-09-03 13:35:12 +00001926 for (HBasicBlock* predecessor : to->GetPredecessors()) {
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001927 HInstruction* last = predecessor->GetLastInstruction();
1928 if (!returns_void) {
1929 return_value->AsPhi()->AddInput(last->InputAt(0));
1930 }
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001931 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
Nicolas Geoffray817bce72015-02-24 13:35:38 +00001932 predecessor->RemoveInstruction(last);
1933 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001934 }
1935
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001936 // Update the meta information surrounding blocks:
1937 // (1) the graph they are now in,
1938 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001939 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05001940 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00001941 // Note that we do not need to update catch phi inputs because they
1942 // correspond to the register file of the outer method which the inlinee
1943 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001944
1945 // We don't add the entry block, the exit block, and the first block, which
1946 // has been merged with `at`.
1947 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
1948
1949 // We add the `to` block.
1950 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001951 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001952 + kNumberOfNewBlocksInCaller;
1953
1954 // Find the location of `at` in the outer graph's reverse post order. The new
1955 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001956 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001957 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
1958
David Brazdil95177982015-10-30 12:56:58 -05001959 HLoopInformation* loop_info = at->GetLoopInformation();
1960 // Copy TryCatchInformation if `at` is a try block, not if it is a catch block.
1961 TryCatchInformation* try_catch_info = at->IsTryBlock() ? at->GetTryCatchInformation() : nullptr;
1962
1963 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
1964 // and (4) to the blocks that apply.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001965 for (HReversePostOrderIterator it(*this); !it.Done(); it.Advance()) {
1966 HBasicBlock* current = it.Current();
1967 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05001968 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001969 DCHECK(current->GetGraph() == this);
1970 current->SetGraph(outer_graph);
1971 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001972 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001973 if (!current->IsInLoop()) {
David Brazdil95177982015-10-30 12:56:58 -05001974 current->SetLoopInformation(loop_info);
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001975 } else if (current->IsLoopHeader()) {
1976 // Clear the information of which blocks are contained in that loop. Since the
1977 // information is stored as a bit vector based on block ids, we have to update
1978 // it, as those block ids were specific to the callee graph and we are now adding
1979 // these blocks to the caller graph.
1980 current->GetLoopInformation()->ClearAllBlocks();
1981 }
1982 if (current->IsInLoop()) {
1983 for (HLoopInformationOutwardIterator loop_it(*current);
1984 !loop_it.Done();
1985 loop_it.Advance()) {
David Brazdil7d275372015-04-21 16:36:35 +01001986 loop_it.Current()->Add(current);
1987 }
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001988 }
David Brazdil95177982015-10-30 12:56:58 -05001989 current->SetTryCatchInformation(try_catch_info);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001990 }
1991 }
1992
David Brazdil95177982015-10-30 12:56:58 -05001993 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001994 to->SetGraph(outer_graph);
1995 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001996 outer_graph->reverse_post_order_[++index_of_at] = to;
David Brazdil95177982015-10-30 12:56:58 -05001997 if (loop_info != nullptr) {
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00001998 if (!to->IsInLoop()) {
1999 to->SetLoopInformation(loop_info);
2000 }
David Brazdil7d275372015-04-21 16:36:35 +01002001 for (HLoopInformationOutwardIterator loop_it(*at); !loop_it.Done(); loop_it.Advance()) {
2002 loop_it.Current()->Add(to);
2003 }
David Brazdil95177982015-10-30 12:56:58 -05002004 if (loop_info->IsBackEdge(*at)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002005 // Only `to` can become a back edge, as the inlined blocks
2006 // are predecessors of `to`.
David Brazdil95177982015-10-30 12:56:58 -05002007 loop_info->ReplaceBackEdge(at, to);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002008 }
2009 }
David Brazdil95177982015-10-30 12:56:58 -05002010 to->SetTryCatchInformation(try_catch_info);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002011 }
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002012
David Brazdil05144f42015-04-16 15:18:00 +01002013 // Update the next instruction id of the outer graph, so that instructions
2014 // added later get bigger ids than those in the inner graph.
2015 outer_graph->SetCurrentInstructionId(GetNextInstructionId());
2016
2017 // Walk over the entry block and:
2018 // - Move constants from the entry block to the outer_graph's entry block,
2019 // - Replace HParameterValue instructions with their real value.
2020 // - Remove suspend checks, that hold an environment.
2021 // We must do this after the other blocks have been inlined, otherwise ids of
2022 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002023 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002024 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2025 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002026 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002027 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002028 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002029 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002030 replacement = outer_graph->GetIntConstant(
2031 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002032 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002033 replacement = outer_graph->GetLongConstant(
2034 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002035 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002036 replacement = outer_graph->GetFloatConstant(
2037 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002038 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002039 replacement = outer_graph->GetDoubleConstant(
2040 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002041 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002042 if (kIsDebugBuild
2043 && invoke->IsInvokeStaticOrDirect()
2044 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2045 // Ensure we do not use the last input of `invoke`, as it
2046 // contains a clinit check which is not an actual argument.
2047 size_t last_input_index = invoke->InputCount() - 1;
2048 DCHECK(parameter_index != last_input_index);
2049 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002050 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002051 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002052 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002053 } else {
2054 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2055 entry_block_->RemoveInstruction(current);
2056 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002057 if (replacement != nullptr) {
2058 current->ReplaceWith(replacement);
2059 // If the current is the return value then we need to update the latter.
2060 if (current == return_value) {
2061 DCHECK_EQ(entry_block_, return_value->GetBlock());
2062 return_value = replacement;
2063 }
2064 }
2065 }
2066
Calin Juravle2e768302015-07-28 14:41:11 +00002067 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002068}
2069
Mingyao Yang3584bce2015-05-19 16:01:59 -07002070/*
2071 * Loop will be transformed to:
2072 * old_pre_header
2073 * |
2074 * if_block
2075 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002076 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002077 * \ /
2078 * new_pre_header
2079 * |
2080 * header
2081 */
2082void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2083 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002084 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002085
Aart Bik3fc7f352015-11-20 22:03:03 -08002086 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002087 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002088 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2089 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002090 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2091 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002092 AddBlock(true_block);
2093 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002094 AddBlock(new_pre_header);
2095
Aart Bik3fc7f352015-11-20 22:03:03 -08002096 header->ReplacePredecessor(old_pre_header, new_pre_header);
2097 old_pre_header->successors_.clear();
2098 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002099
Aart Bik3fc7f352015-11-20 22:03:03 -08002100 old_pre_header->AddSuccessor(if_block);
2101 if_block->AddSuccessor(true_block); // True successor
2102 if_block->AddSuccessor(false_block); // False successor
2103 true_block->AddSuccessor(new_pre_header);
2104 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002105
Aart Bik3fc7f352015-11-20 22:03:03 -08002106 old_pre_header->dominated_blocks_.push_back(if_block);
2107 if_block->SetDominator(old_pre_header);
2108 if_block->dominated_blocks_.push_back(true_block);
2109 true_block->SetDominator(if_block);
2110 if_block->dominated_blocks_.push_back(false_block);
2111 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002112 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002113 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002114 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002115 header->SetDominator(new_pre_header);
2116
Aart Bik3fc7f352015-11-20 22:03:03 -08002117 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002118 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002119 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002120 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002121 reverse_post_order_[index_of_header++] = true_block;
2122 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002123 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002124
Aart Bik3fc7f352015-11-20 22:03:03 -08002125 // Fix loop information.
2126 HLoopInformation* loop_info = old_pre_header->GetLoopInformation();
2127 if (loop_info != nullptr) {
2128 if_block->SetLoopInformation(loop_info);
2129 true_block->SetLoopInformation(loop_info);
2130 false_block->SetLoopInformation(loop_info);
2131 new_pre_header->SetLoopInformation(loop_info);
2132 // Add blocks to all enveloping loops.
2133 for (HLoopInformationOutwardIterator loop_it(*old_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002134 !loop_it.Done();
2135 loop_it.Advance()) {
2136 loop_it.Current()->Add(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002137 loop_it.Current()->Add(true_block);
2138 loop_it.Current()->Add(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002139 loop_it.Current()->Add(new_pre_header);
2140 }
2141 }
Aart Bik3fc7f352015-11-20 22:03:03 -08002142
2143 // Fix try/catch information.
2144 TryCatchInformation* try_catch_info = old_pre_header->IsTryBlock()
2145 ? old_pre_header->GetTryCatchInformation()
2146 : nullptr;
2147 if_block->SetTryCatchInformation(try_catch_info);
2148 true_block->SetTryCatchInformation(try_catch_info);
2149 false_block->SetTryCatchInformation(try_catch_info);
2150 new_pre_header->SetTryCatchInformation(try_catch_info);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002151}
2152
David Brazdilf5552582015-12-27 13:36:12 +00002153static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
2154 SHARED_REQUIRES(Locks::mutator_lock_) {
2155 if (rti.IsValid()) {
2156 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2157 << " upper_bound_rti: " << upper_bound_rti
2158 << " rti: " << rti;
2159 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact());
2160 }
2161}
2162
Calin Juravle2e768302015-07-28 14:41:11 +00002163void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2164 if (kIsDebugBuild) {
2165 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2166 ScopedObjectAccess soa(Thread::Current());
2167 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2168 if (IsBoundType()) {
2169 // Having the test here spares us from making the method virtual just for
2170 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002171 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002172 }
2173 }
2174 reference_type_info_ = rti;
2175}
2176
David Brazdilf5552582015-12-27 13:36:12 +00002177void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2178 if (kIsDebugBuild) {
2179 ScopedObjectAccess soa(Thread::Current());
2180 DCHECK(upper_bound.IsValid());
2181 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2182 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2183 }
2184 upper_bound_ = upper_bound;
2185 upper_can_be_null_ = can_be_null;
2186}
2187
Calin Juravle2e768302015-07-28 14:41:11 +00002188ReferenceTypeInfo::ReferenceTypeInfo() : type_handle_(TypeHandle()), is_exact_(false) {}
2189
2190ReferenceTypeInfo::ReferenceTypeInfo(TypeHandle type_handle, bool is_exact)
2191 : type_handle_(type_handle), is_exact_(is_exact) {
2192 if (kIsDebugBuild) {
2193 ScopedObjectAccess soa(Thread::Current());
2194 DCHECK(IsValidHandle(type_handle));
2195 }
2196}
2197
Calin Juravleacf735c2015-02-12 15:25:22 +00002198std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2199 ScopedObjectAccess soa(Thread::Current());
2200 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002201 << " is_valid=" << rhs.IsValid()
2202 << " type=" << (!rhs.IsValid() ? "?" : PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002203 << " is_exact=" << rhs.IsExact()
2204 << " ]";
2205 return os;
2206}
2207
Mark Mendellc4701932015-04-10 13:18:51 -04002208bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2209 // For now, assume that instructions in different blocks may use the
2210 // environment.
2211 // TODO: Use the control flow to decide if this is true.
2212 if (GetBlock() != other->GetBlock()) {
2213 return true;
2214 }
2215
2216 // We know that we are in the same block. Walk from 'this' to 'other',
2217 // checking to see if there is any instruction with an environment.
2218 HInstruction* current = this;
2219 for (; current != other && current != nullptr; current = current->GetNext()) {
2220 // This is a conservative check, as the instruction result may not be in
2221 // the referenced environment.
2222 if (current->HasEnvironment()) {
2223 return true;
2224 }
2225 }
2226
2227 // We should have been called with 'this' before 'other' in the block.
2228 // Just confirm this.
2229 DCHECK(current != nullptr);
2230 return false;
2231}
2232
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002233void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002234 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2235 IntrinsicSideEffects side_effects,
2236 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002237 intrinsic_ = intrinsic;
2238 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002239
Aart Bik5d75afe2015-12-14 11:57:01 -08002240 // Adjust method's side effects from intrinsic table.
2241 switch (side_effects) {
2242 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2243 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2244 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2245 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2246 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002247
2248 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2249 opt.SetDoesNotNeedDexCache();
2250 opt.SetDoesNotNeedEnvironment();
2251 } else {
2252 // If we need an environment, that means there will be a call, which can trigger GC.
2253 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2254 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002255 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002256 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002257}
2258
David Brazdil6de19382016-01-08 17:37:10 +00002259bool HNewInstance::IsStringAlloc() const {
2260 ScopedObjectAccess soa(Thread::Current());
2261 return GetReferenceTypeInfo().IsStringClass();
2262}
2263
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002264bool HInvoke::NeedsEnvironment() const {
2265 if (!IsIntrinsic()) {
2266 return true;
2267 }
2268 IntrinsicOptimizations opt(*this);
2269 return !opt.GetDoesNotNeedEnvironment();
2270}
2271
Vladimir Markodc151b22015-10-15 18:02:30 +01002272bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2273 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002274 return false;
2275 }
2276 if (!IsIntrinsic()) {
2277 return true;
2278 }
2279 IntrinsicOptimizations opt(*this);
2280 return !opt.GetDoesNotNeedDexCache();
2281}
2282
Vladimir Marko0f7dca42015-11-02 14:36:43 +00002283void HInvokeStaticOrDirect::InsertInputAt(size_t index, HInstruction* input) {
2284 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
2285 input->AddUseAt(this, index);
2286 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
2287 for (size_t i = index + 1u, size = inputs_.size(); i != size; ++i) {
2288 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i - 1u);
2289 InputRecordAt(i).GetUseNode()->SetIndex(i);
2290 }
2291}
2292
Vladimir Markob554b5a2015-11-06 12:57:55 +00002293void HInvokeStaticOrDirect::RemoveInputAt(size_t index) {
2294 RemoveAsUserOfInput(index);
2295 inputs_.erase(inputs_.begin() + index);
2296 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
2297 for (size_t i = index, e = InputCount(); i < e; ++i) {
2298 DCHECK_EQ(InputRecordAt(i).GetUseNode()->GetIndex(), i + 1u);
2299 InputRecordAt(i).GetUseNode()->SetIndex(i);
2300 }
2301}
2302
Vladimir Markof64242a2015-12-01 14:58:23 +00002303std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2304 switch (rhs) {
2305 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2306 return os << "string_init";
2307 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2308 return os << "recursive";
2309 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2310 return os << "direct";
2311 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddressWithFixup:
2312 return os << "direct_fixup";
2313 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2314 return os << "dex_cache_pc_relative";
2315 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2316 return os << "dex_cache_via_method";
2317 default:
2318 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2319 UNREACHABLE();
2320 }
2321}
2322
Vladimir Markofbb184a2015-11-13 14:47:00 +00002323std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2324 switch (rhs) {
2325 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2326 return os << "explicit";
2327 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2328 return os << "implicit";
2329 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2330 return os << "none";
2331 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002332 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2333 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002334 }
2335}
2336
Mark Mendellc4701932015-04-10 13:18:51 -04002337void HInstruction::RemoveEnvironmentUsers() {
2338 for (HUseIterator<HEnvironment*> use_it(GetEnvUses()); !use_it.Done(); use_it.Advance()) {
2339 HUseListNode<HEnvironment*>* user_node = use_it.Current();
2340 HEnvironment* user = user_node->GetUser();
2341 user->SetRawEnvAt(user_node->GetIndex(), nullptr);
2342 }
2343 env_uses_.Clear();
2344}
2345
Mark Mendellf6529172015-11-17 11:16:56 -05002346// Returns an instruction with the opposite boolean value from 'cond'.
2347HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2348 ArenaAllocator* allocator = GetArena();
2349
2350 if (cond->IsCondition() &&
2351 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2352 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2353 HInstruction* lhs = cond->InputAt(0);
2354 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002355 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002356 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2357 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2358 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2359 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2360 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2361 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2362 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2363 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2364 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2365 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2366 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002367 default:
2368 LOG(FATAL) << "Unexpected condition";
2369 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002370 }
2371 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2372 return replacement;
2373 } else if (cond->IsIntConstant()) {
2374 HIntConstant* int_const = cond->AsIntConstant();
2375 if (int_const->IsZero()) {
2376 return GetIntConstant(1);
2377 } else {
2378 DCHECK(int_const->IsOne());
2379 return GetIntConstant(0);
2380 }
2381 } else {
2382 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2383 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2384 return replacement;
2385 }
2386}
2387
Roland Levillainc9285912015-12-18 10:38:42 +00002388std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2389 os << "["
2390 << " source=" << rhs.GetSource()
2391 << " destination=" << rhs.GetDestination()
2392 << " type=" << rhs.GetType()
2393 << " instruction=";
2394 if (rhs.GetInstruction() != nullptr) {
2395 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2396 } else {
2397 os << "null";
2398 }
2399 os << " ]";
2400 return os;
2401}
2402
Roland Levillain86503782016-02-11 19:07:30 +00002403std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2404 switch (rhs) {
2405 case TypeCheckKind::kUnresolvedCheck:
2406 return os << "unresolved_check";
2407 case TypeCheckKind::kExactCheck:
2408 return os << "exact_check";
2409 case TypeCheckKind::kClassHierarchyCheck:
2410 return os << "class_hierarchy_check";
2411 case TypeCheckKind::kAbstractClassCheck:
2412 return os << "abstract_class_check";
2413 case TypeCheckKind::kInterfaceCheck:
2414 return os << "interface_check";
2415 case TypeCheckKind::kArrayObjectCheck:
2416 return os << "array_object_check";
2417 case TypeCheckKind::kArrayCheck:
2418 return os << "array_check";
2419 default:
2420 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2421 UNREACHABLE();
2422 }
2423}
2424
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002425} // namespace art