blob: ca953a1a7e16c994855af61d89e90ffaf2df3f89 [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
Andreas Gampec6ea7d02017-02-01 16:46:28 -080020#include "art_method-inl.h"
21#include "class_linker-inl.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040022#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000023#include "common_dominator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010024#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010025#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010026#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010027#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010028#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010029#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070030#include "scoped_thread_state_change-inl.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000031
32namespace art {
33
Roland Levillain31dd3d62016-02-16 12:21:02 +000034// Enable floating-point static evaluation during constant folding
35// only if all floating-point operations and constants evaluate in the
36// range and precision of the type used (i.e., 32-bit float, 64-bit
37// double).
38static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
39
Mathieu Chartiere8a3c572016-10-11 16:52:17 -070040void HGraph::InitializeInexactObjectRTI(VariableSizedHandleScope* handles) {
David Brazdilbadd8262016-02-02 16:28:56 +000041 ScopedObjectAccess soa(Thread::Current());
42 // Create the inexact Object reference type and store it in the HGraph.
43 ClassLinker* linker = Runtime::Current()->GetClassLinker();
44 inexact_object_rti_ = ReferenceTypeInfo::Create(
45 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
46 /* is_exact */ false);
47}
48
Nicolas Geoffray818f2102014-02-18 16:43:35 +000049void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010050 block->SetBlockId(blocks_.size());
51 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000052}
53
Nicolas Geoffray804d0932014-05-02 08:46:00 +010054void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010055 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
56 DCHECK_EQ(visited->GetHighestBitSet(), -1);
57
58 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markof6a35de2016-03-21 12:01:50 +000059 ArenaBitVector visiting(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010060 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +010061 ArenaVector<size_t> successors_visited(blocks_.size(),
62 0u,
63 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko3ea5a972016-05-09 20:23:34 +010065 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010066 constexpr size_t kDefaultWorklistSize = 8;
67 worklist.reserve(kDefaultWorklistSize);
68 visited->SetBit(entry_block_->GetBlockId());
69 visiting.SetBit(entry_block_->GetBlockId());
70 worklist.push_back(entry_block_);
71
72 while (!worklist.empty()) {
73 HBasicBlock* current = worklist.back();
74 uint32_t current_id = current->GetBlockId();
75 if (successors_visited[current_id] == current->GetSuccessors().size()) {
76 visiting.ClearBit(current_id);
77 worklist.pop_back();
78 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010079 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
80 uint32_t successor_id = successor->GetBlockId();
81 if (visiting.IsBitSet(successor_id)) {
82 DCHECK(ContainsElement(worklist, successor));
83 successor->AddBackEdge(current);
84 } else if (!visited->IsBitSet(successor_id)) {
85 visited->SetBit(successor_id);
86 visiting.SetBit(successor_id);
87 worklist.push_back(successor);
88 }
89 }
90 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000091}
92
Vladimir Markocac5a7e2016-02-22 10:39:50 +000093static void RemoveEnvironmentUses(HInstruction* instruction) {
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
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000105static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100106 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000107 RemoveEnvironmentUses(instruction);
108}
109
Roland Levillainfc600dc2014-12-02 17:16:31 +0000110void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100111 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000112 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100113 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000114 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100115 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000116 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
117 RemoveAsUser(it.Current());
118 }
119 }
120 }
121}
122
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100123void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100124 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000125 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100126 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000127 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100128 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000129 for (HBasicBlock* successor : block->GetSuccessors()) {
130 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000131 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100132 // Remove the block from the list of blocks, so that further analyses
133 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100134 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600135 if (block->IsExitBlock()) {
136 SetExitBlock(nullptr);
137 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000138 // Mark the block as removed. This is used by the HGraphBuilder to discard
139 // the block as a branch target.
140 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000141 }
142 }
143}
144
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000145GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000146 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000147
David Brazdil86ea7ee2016-02-16 09:26:07 +0000148 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000149 FindBackEdges(&visited);
150
David Brazdil86ea7ee2016-02-16 09:26:07 +0000151 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000152 // the initial DFS as users from other instructions, so that
153 // users can be safely removed before uses later.
154 RemoveInstructionsAsUsersFromDeadBlocks(visited);
155
David Brazdil86ea7ee2016-02-16 09:26:07 +0000156 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000157 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000158 // predecessors list of live blocks.
159 RemoveDeadBlocks(visited);
160
David Brazdil86ea7ee2016-02-16 09:26:07 +0000161 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100162 // dominators and the reverse post order.
163 SimplifyCFG();
164
David Brazdil86ea7ee2016-02-16 09:26:07 +0000165 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100166 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000167
David Brazdil86ea7ee2016-02-16 09:26:07 +0000168 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000169 // set the loop information on each block.
170 GraphAnalysisResult result = AnalyzeLoops();
171 if (result != kAnalysisSuccess) {
172 return result;
173 }
174
David Brazdil86ea7ee2016-02-16 09:26:07 +0000175 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000176 // which needs the information to build catch block phis from values of
177 // locals at throwing instructions inside try blocks.
178 ComputeTryBlockInformation();
179
180 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100181}
182
183void HGraph::ClearDominanceInformation() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100184 for (HBasicBlock* block : GetReversePostOrder()) {
185 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100186 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100187 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100188}
189
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000190void HGraph::ClearLoopInformation() {
191 SetHasIrreducibleLoops(false);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100192 for (HBasicBlock* block : GetReversePostOrder()) {
193 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000194 }
195}
196
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100197void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000198 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100199 dominator_ = nullptr;
200}
201
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000202HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
203 HInstruction* instruction = GetFirstInstruction();
204 while (instruction->IsParallelMove()) {
205 instruction = instruction->GetNext();
206 }
207 return instruction;
208}
209
David Brazdil3f4a5222016-05-06 12:46:21 +0100210static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
211 DCHECK(ContainsElement(block->GetSuccessors(), successor));
212
213 HBasicBlock* old_dominator = successor->GetDominator();
214 HBasicBlock* new_dominator =
215 (old_dominator == nullptr) ? block
216 : CommonDominator::ForPair(old_dominator, block);
217
218 if (old_dominator == new_dominator) {
219 return false;
220 } else {
221 successor->SetDominator(new_dominator);
222 return true;
223 }
224}
225
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100226void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100227 DCHECK(reverse_post_order_.empty());
228 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100229 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100230
231 // Number of visits of a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100232 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100233 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100234 ArenaVector<size_t> successors_visited(blocks_.size(),
235 0u,
236 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100237 // Nodes for which we need to visit successors.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100238 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100239 constexpr size_t kDefaultWorklistSize = 8;
240 worklist.reserve(kDefaultWorklistSize);
241 worklist.push_back(entry_block_);
242
243 while (!worklist.empty()) {
244 HBasicBlock* current = worklist.back();
245 uint32_t current_id = current->GetBlockId();
246 if (successors_visited[current_id] == current->GetSuccessors().size()) {
247 worklist.pop_back();
248 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100249 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100250 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100251
252 // Once all the forward edges have been visited, we know the immediate
253 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100254 if (++visits[successor->GetBlockId()] ==
255 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100256 reverse_post_order_.push_back(successor);
257 worklist.push_back(successor);
258 }
259 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000260 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000261
David Brazdil3f4a5222016-05-06 12:46:21 +0100262 // Check if the graph has back edges not dominated by their respective headers.
263 // If so, we need to update the dominators of those headers and recursively of
264 // their successors. We do that with a fix-point iteration over all blocks.
265 // The algorithm is guaranteed to terminate because it loops only if the sum
266 // of all dominator chains has decreased in the current iteration.
267 bool must_run_fix_point = false;
268 for (HBasicBlock* block : blocks_) {
269 if (block != nullptr &&
270 block->IsLoopHeader() &&
271 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
272 must_run_fix_point = true;
273 break;
274 }
275 }
276 if (must_run_fix_point) {
277 bool update_occurred = true;
278 while (update_occurred) {
279 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100280 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100281 for (HBasicBlock* successor : block->GetSuccessors()) {
282 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
283 }
284 }
285 }
286 }
287
288 // Make sure that there are no remaining blocks whose dominator information
289 // needs to be updated.
290 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100291 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100292 for (HBasicBlock* successor : block->GetSuccessors()) {
293 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
294 }
295 }
296 }
297
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000298 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000299 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100300 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000301 if (!block->IsEntryBlock()) {
302 block->GetDominator()->AddDominatedBlock(block);
303 }
304 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000305}
306
David Brazdilfc6a86a2015-06-26 10:33:45 +0000307HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000308 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
309 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000310 // Use `InsertBetween` to ensure the predecessor index and successor index of
311 // `block` and `successor` are preserved.
312 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000313 return new_block;
314}
315
316void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
317 // Insert a new node between `block` and `successor` to split the
318 // critical edge.
319 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600320 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100321 if (successor->IsLoopHeader()) {
322 // If we split at a back edge boundary, make the new block the back edge.
323 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000324 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100325 info->RemoveBackEdge(block);
326 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100327 }
328 }
329}
330
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100331void HGraph::SimplifyLoop(HBasicBlock* header) {
332 HLoopInformation* info = header->GetLoopInformation();
333
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100334 // Make sure the loop has only one pre header. This simplifies SSA building by having
335 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000336 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
337 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000338 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000339 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100340 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100341 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600342 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100343
Vladimir Marko60584552015-09-03 13:35:12 +0000344 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100345 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100346 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100347 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100348 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100349 }
350 }
351 pre_header->AddSuccessor(header);
352 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100353
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100354 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100355 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
356 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000357 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100358 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100359 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000360 header->predecessors_[pred] = to_swap;
361 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100362 break;
363 }
364 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100365 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100366
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100367 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000368 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
369 // Called from DeadBlockElimination. Update SuspendCheck pointer.
370 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100371 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100372}
373
David Brazdilffee3d32015-07-06 11:48:53 +0100374void HGraph::ComputeTryBlockInformation() {
375 // Iterate in reverse post order to propagate try membership information from
376 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100377 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100378 if (block->IsEntryBlock() || block->IsCatchBlock()) {
379 // Catch blocks after simplification have only exceptional predecessors
380 // and hence are never in tries.
381 continue;
382 }
383
384 // Infer try membership from the first predecessor. Having simplified loops,
385 // the first predecessor can never be a back edge and therefore it must have
386 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100387 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100388 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100389 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000390 if (try_entry != nullptr &&
391 (block->GetTryCatchInformation() == nullptr ||
392 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
393 // We are either setting try block membership for the first time or it
394 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100395 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
396 }
David Brazdilffee3d32015-07-06 11:48:53 +0100397 }
398}
399
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100400void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000401// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100402 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000403 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100404 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
405 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
406 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
407 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100408 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000409 if (block->GetSuccessors().size() > 1) {
410 // Only split normal-flow edges. We cannot split exceptional edges as they
411 // are synthesized (approximate real control flow), and we do not need to
412 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000413 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
414 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
415 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100416 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000417 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000418 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
419 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000420 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000421 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100422 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000423 // SplitCriticalEdge could have invalidated the `normal_successors`
424 // ArrayRef. We must re-acquire it.
425 normal_successors = block->GetNormalSuccessors();
426 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
427 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100428 }
429 }
430 }
431 if (block->IsLoopHeader()) {
432 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000433 } else if (!block->IsEntryBlock() &&
434 block->GetFirstInstruction() != nullptr &&
435 block->GetFirstInstruction()->IsSuspendCheck()) {
436 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000437 // a loop got dismantled. Just remove the suspend check.
438 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100439 }
440 }
441}
442
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000443GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100444 // We iterate post order to ensure we visit inner loops before outer loops.
445 // `PopulateRecursive` needs this guarantee to know whether a natural loop
446 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100447 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100448 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100449 if (block->IsCatchBlock()) {
450 // TODO: Dealing with exceptional back edges could be tricky because
451 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000452 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100453 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000454 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100455 }
456 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000457 return kAnalysisSuccess;
458}
459
460void HLoopInformation::Dump(std::ostream& os) {
461 os << "header: " << header_->GetBlockId() << std::endl;
462 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
463 for (HBasicBlock* block : back_edges_) {
464 os << "back edge: " << block->GetBlockId() << std::endl;
465 }
466 for (HBasicBlock* block : header_->GetPredecessors()) {
467 os << "predecessor: " << block->GetBlockId() << std::endl;
468 }
469 for (uint32_t idx : blocks_.Indexes()) {
470 os << " in loop: " << idx << std::endl;
471 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100472}
473
David Brazdil8d5b8b22015-03-24 10:51:52 +0000474void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000475 // New constants are inserted before the SuspendCheck at the bottom of the
476 // entry block. Note that this method can be called from the graph builder and
477 // the entry block therefore may not end with SuspendCheck->Goto yet.
478 HInstruction* insert_before = nullptr;
479
480 HInstruction* gota = entry_block_->GetLastInstruction();
481 if (gota != nullptr && gota->IsGoto()) {
482 HInstruction* suspend_check = gota->GetPrevious();
483 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
484 insert_before = suspend_check;
485 } else {
486 insert_before = gota;
487 }
488 }
489
490 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000491 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000492 } else {
493 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000494 }
495}
496
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600497HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100498 // For simplicity, don't bother reviving the cached null constant if it is
499 // not null and not in a block. Otherwise, we need to clear the instruction
500 // id and/or any invariants the graph is assuming when adding new instructions.
501 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600502 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000503 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000504 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000505 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000506 if (kIsDebugBuild) {
507 ScopedObjectAccess soa(Thread::Current());
508 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
509 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000510 return cached_null_constant_;
511}
512
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100513HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100514 // For simplicity, don't bother reviving the cached current method if it is
515 // not null and not in a block. Otherwise, we need to clear the instruction
516 // id and/or any invariants the graph is assuming when adding new instructions.
517 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700518 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600519 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
520 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100521 if (entry_block_->GetFirstInstruction() == nullptr) {
522 entry_block_->AddInstruction(cached_current_method_);
523 } else {
524 entry_block_->InsertInstructionBefore(
525 cached_current_method_, entry_block_->GetFirstInstruction());
526 }
527 }
528 return cached_current_method_;
529}
530
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600531HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000532 switch (type) {
533 case Primitive::Type::kPrimBoolean:
534 DCHECK(IsUint<1>(value));
535 FALLTHROUGH_INTENDED;
536 case Primitive::Type::kPrimByte:
537 case Primitive::Type::kPrimChar:
538 case Primitive::Type::kPrimShort:
539 case Primitive::Type::kPrimInt:
540 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600541 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000542
543 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600544 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000545
546 default:
547 LOG(FATAL) << "Unsupported constant type";
548 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000549 }
David Brazdil46e2a392015-03-16 17:31:52 +0000550}
551
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000552void HGraph::CacheFloatConstant(HFloatConstant* constant) {
553 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
554 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
555 cached_float_constants_.Overwrite(value, constant);
556}
557
558void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
559 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
560 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
561 cached_double_constants_.Overwrite(value, constant);
562}
563
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000564void HLoopInformation::Add(HBasicBlock* block) {
565 blocks_.SetBit(block->GetBlockId());
566}
567
David Brazdil46e2a392015-03-16 17:31:52 +0000568void HLoopInformation::Remove(HBasicBlock* block) {
569 blocks_.ClearBit(block->GetBlockId());
570}
571
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100572void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
573 if (blocks_.IsBitSet(block->GetBlockId())) {
574 return;
575 }
576
577 blocks_.SetBit(block->GetBlockId());
578 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100579 if (block->IsLoopHeader()) {
580 // We're visiting loops in post-order, so inner loops must have been
581 // populated already.
582 DCHECK(block->GetLoopInformation()->IsPopulated());
583 if (block->GetLoopInformation()->IsIrreducible()) {
584 contains_irreducible_loop_ = true;
585 }
586 }
Vladimir Marko60584552015-09-03 13:35:12 +0000587 for (HBasicBlock* predecessor : block->GetPredecessors()) {
588 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100589 }
590}
591
David Brazdilc2e8af92016-04-05 17:15:19 +0100592void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
593 size_t block_id = block->GetBlockId();
594
595 // If `block` is in `finalized`, we know its membership in the loop has been
596 // decided and it does not need to be revisited.
597 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000598 return;
599 }
600
David Brazdilc2e8af92016-04-05 17:15:19 +0100601 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000602 if (block->IsLoopHeader()) {
603 // If we hit a loop header in an irreducible loop, we first check if the
604 // pre header of that loop belongs to the currently analyzed loop. If it does,
605 // then we visit the back edges.
606 // Note that we cannot use GetPreHeader, as the loop may have not been populated
607 // yet.
608 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100609 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000610 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000611 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100612 blocks_.SetBit(block_id);
613 finalized->SetBit(block_id);
614 is_finalized = true;
615
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000616 HLoopInformation* info = block->GetLoopInformation();
617 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100618 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000619 }
620 }
621 } else {
622 // Visit all predecessors. If one predecessor is part of the loop, this
623 // block is also part of this loop.
624 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100625 PopulateIrreducibleRecursive(predecessor, finalized);
626 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000627 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100628 blocks_.SetBit(block_id);
629 finalized->SetBit(block_id);
630 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000631 }
632 }
633 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100634
635 // All predecessors have been recursively visited. Mark finalized if not marked yet.
636 if (!is_finalized) {
637 finalized->SetBit(block_id);
638 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000639}
640
641void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100642 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000643 // Populate this loop: starting with the back edge, recursively add predecessors
644 // that are not already part of that loop. Set the header as part of the loop
645 // to end the recursion.
646 // This is a recursive implementation of the algorithm described in
647 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100648 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000649 blocks_.SetBit(header_->GetBlockId());
650 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100651
David Brazdil3f4a5222016-05-06 12:46:21 +0100652 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100653
654 if (is_irreducible_loop) {
655 ArenaBitVector visited(graph->GetArena(),
656 graph->GetBlocks().size(),
657 /* expandable */ false,
658 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100659 // Stop marking blocks at the loop header.
660 visited.SetBit(header_->GetBlockId());
661
David Brazdilc2e8af92016-04-05 17:15:19 +0100662 for (HBasicBlock* back_edge : GetBackEdges()) {
663 PopulateIrreducibleRecursive(back_edge, &visited);
664 }
665 } else {
666 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000667 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100668 }
David Brazdila4b8c212015-05-07 09:59:30 +0100669 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100670
Vladimir Markofd66c502016-04-18 15:37:01 +0100671 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
672 // When compiling in OSR mode, all loops in the compiled method may be entered
673 // from the interpreter. We treat this OSR entry point just like an extra entry
674 // to an irreducible loop, so we need to mark the method's loops as irreducible.
675 // This does not apply to inlined loops which do not act as OSR entry points.
676 if (suspend_check_ == nullptr) {
677 // Just building the graph in OSR mode, this loop is not inlined. We never build an
678 // inner graph in OSR mode as we can do OSR transition only from the outer method.
679 is_irreducible_loop = true;
680 } else {
681 // Look at the suspend check's environment to determine if the loop was inlined.
682 DCHECK(suspend_check_->HasEnvironment());
683 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
684 is_irreducible_loop = true;
685 }
686 }
687 }
688 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100689 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100690 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100691 graph->SetHasIrreducibleLoops(true);
692 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800693 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +0100694}
695
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100696HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000697 HBasicBlock* block = header_->GetPredecessors()[0];
698 DCHECK(irreducible_ || (block == header_->GetDominator()));
699 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100700}
701
702bool HLoopInformation::Contains(const HBasicBlock& block) const {
703 return blocks_.IsBitSet(block.GetBlockId());
704}
705
706bool HLoopInformation::IsIn(const HLoopInformation& other) const {
707 return other.blocks_.IsBitSet(header_->GetBlockId());
708}
709
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800710bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
711 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700712}
713
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100714size_t HLoopInformation::GetLifetimeEnd() const {
715 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100716 for (HBasicBlock* back_edge : GetBackEdges()) {
717 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100718 }
719 return last_position;
720}
721
David Brazdil3f4a5222016-05-06 12:46:21 +0100722bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
723 for (HBasicBlock* back_edge : GetBackEdges()) {
724 DCHECK(back_edge->GetDominator() != nullptr);
725 if (!header_->Dominates(back_edge)) {
726 return true;
727 }
728 }
729 return false;
730}
731
Anton Shaminf89381f2016-05-16 16:44:13 +0600732bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
733 for (HBasicBlock* back_edge : GetBackEdges()) {
734 if (!block->Dominates(back_edge)) {
735 return false;
736 }
737 }
738 return true;
739}
740
David Sehrc757dec2016-11-04 15:48:34 -0700741
742bool HLoopInformation::HasExitEdge() const {
743 // Determine if this loop has at least one exit edge.
744 HBlocksInLoopReversePostOrderIterator it_loop(*this);
745 for (; !it_loop.Done(); it_loop.Advance()) {
746 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
747 if (!Contains(*successor)) {
748 return true;
749 }
750 }
751 }
752 return false;
753}
754
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100755bool HBasicBlock::Dominates(HBasicBlock* other) const {
756 // Walk up the dominator tree from `other`, to find out if `this`
757 // is an ancestor.
758 HBasicBlock* current = other;
759 while (current != nullptr) {
760 if (current == this) {
761 return true;
762 }
763 current = current->GetDominator();
764 }
765 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100766}
767
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100768static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100769 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100770 for (size_t i = 0; i < inputs.size(); ++i) {
771 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100772 }
773 // Environment should be created later.
774 DCHECK(!instruction->HasEnvironment());
775}
776
Roland Levillainccc07a92014-09-16 14:48:16 +0100777void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
778 HInstruction* replacement) {
779 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400780 if (initial->IsControlFlow()) {
781 // We can only replace a control flow instruction with another control flow instruction.
782 DCHECK(replacement->IsControlFlow());
783 DCHECK_EQ(replacement->GetId(), -1);
784 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
785 DCHECK_EQ(initial->GetBlock(), this);
786 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100787 DCHECK(initial->GetUses().empty());
788 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400789 replacement->SetBlock(this);
790 replacement->SetId(GetGraph()->GetNextInstructionId());
791 instructions_.InsertInstructionBefore(replacement, initial);
792 UpdateInputsUsers(replacement);
793 } else {
794 InsertInstructionBefore(replacement, initial);
795 initial->ReplaceWith(replacement);
796 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100797 RemoveInstruction(initial);
798}
799
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100800static void Add(HInstructionList* instruction_list,
801 HBasicBlock* block,
802 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000803 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000804 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100805 instruction->SetBlock(block);
806 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100807 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100808 instruction_list->AddInstruction(instruction);
809}
810
811void HBasicBlock::AddInstruction(HInstruction* instruction) {
812 Add(&instructions_, this, instruction);
813}
814
815void HBasicBlock::AddPhi(HPhi* phi) {
816 Add(&phis_, this, phi);
817}
818
David Brazdilc3d743f2015-04-22 13:40:50 +0100819void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
820 DCHECK(!cursor->IsPhi());
821 DCHECK(!instruction->IsPhi());
822 DCHECK_EQ(instruction->GetId(), -1);
823 DCHECK_NE(cursor->GetId(), -1);
824 DCHECK_EQ(cursor->GetBlock(), this);
825 DCHECK(!instruction->IsControlFlow());
826 instruction->SetBlock(this);
827 instruction->SetId(GetGraph()->GetNextInstructionId());
828 UpdateInputsUsers(instruction);
829 instructions_.InsertInstructionBefore(instruction, cursor);
830}
831
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100832void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
833 DCHECK(!cursor->IsPhi());
834 DCHECK(!instruction->IsPhi());
835 DCHECK_EQ(instruction->GetId(), -1);
836 DCHECK_NE(cursor->GetId(), -1);
837 DCHECK_EQ(cursor->GetBlock(), this);
838 DCHECK(!instruction->IsControlFlow());
839 DCHECK(!cursor->IsControlFlow());
840 instruction->SetBlock(this);
841 instruction->SetId(GetGraph()->GetNextInstructionId());
842 UpdateInputsUsers(instruction);
843 instructions_.InsertInstructionAfter(instruction, cursor);
844}
845
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100846void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
847 DCHECK_EQ(phi->GetId(), -1);
848 DCHECK_NE(cursor->GetId(), -1);
849 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100850 phi->SetBlock(this);
851 phi->SetId(GetGraph()->GetNextInstructionId());
852 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100853 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100854}
855
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100856static void Remove(HInstructionList* instruction_list,
857 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000858 HInstruction* instruction,
859 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100860 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100861 instruction->SetBlock(nullptr);
862 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000863 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100864 DCHECK(instruction->GetUses().empty());
865 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000866 RemoveAsUser(instruction);
867 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100868}
869
David Brazdil1abb4192015-02-17 18:33:36 +0000870void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100871 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000872 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100873}
874
David Brazdil1abb4192015-02-17 18:33:36 +0000875void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
876 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100877}
878
David Brazdilc7508e92015-04-27 13:28:57 +0100879void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
880 if (instruction->IsPhi()) {
881 RemovePhi(instruction->AsPhi(), ensure_safety);
882 } else {
883 RemoveInstruction(instruction, ensure_safety);
884 }
885}
886
Vladimir Marko71bf8092015-09-15 15:33:14 +0100887void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
888 for (size_t i = 0; i < locals.size(); i++) {
889 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100890 SetRawEnvAt(i, instruction);
891 if (instruction != nullptr) {
892 instruction->AddEnvUseAt(this, i);
893 }
894 }
895}
896
David Brazdiled596192015-01-23 10:39:45 +0000897void HEnvironment::CopyFrom(HEnvironment* env) {
898 for (size_t i = 0; i < env->Size(); i++) {
899 HInstruction* instruction = env->GetInstructionAt(i);
900 SetRawEnvAt(i, instruction);
901 if (instruction != nullptr) {
902 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100903 }
David Brazdiled596192015-01-23 10:39:45 +0000904 }
905}
906
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700907void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
908 HBasicBlock* loop_header) {
909 DCHECK(loop_header->IsLoopHeader());
910 for (size_t i = 0; i < env->Size(); i++) {
911 HInstruction* instruction = env->GetInstructionAt(i);
912 SetRawEnvAt(i, instruction);
913 if (instruction == nullptr) {
914 continue;
915 }
916 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
917 // At the end of the loop pre-header, the corresponding value for instruction
918 // is the first input of the phi.
919 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700920 SetRawEnvAt(i, initial);
921 initial->AddEnvUseAt(this, i);
922 } else {
923 instruction->AddEnvUseAt(this, i);
924 }
925 }
926}
927
David Brazdil1abb4192015-02-17 18:33:36 +0000928void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100929 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
930 HInstruction* user = env_use.GetInstruction();
931 auto before_env_use_node = env_use.GetBeforeUseNode();
932 user->env_uses_.erase_after(before_env_use_node);
933 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100934}
935
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000936HInstruction::InstructionKind HInstruction::GetKind() const {
937 return GetKindInternal();
938}
939
Calin Juravle77520bc2015-01-12 18:45:46 +0000940HInstruction* HInstruction::GetNextDisregardingMoves() const {
941 HInstruction* next = GetNext();
942 while (next != nullptr && next->IsParallelMove()) {
943 next = next->GetNext();
944 }
945 return next;
946}
947
948HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
949 HInstruction* previous = GetPrevious();
950 while (previous != nullptr && previous->IsParallelMove()) {
951 previous = previous->GetPrevious();
952 }
953 return previous;
954}
955
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100956void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000957 if (first_instruction_ == nullptr) {
958 DCHECK(last_instruction_ == nullptr);
959 first_instruction_ = last_instruction_ = instruction;
960 } else {
961 last_instruction_->next_ = instruction;
962 instruction->previous_ = last_instruction_;
963 last_instruction_ = instruction;
964 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000965}
966
David Brazdilc3d743f2015-04-22 13:40:50 +0100967void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
968 DCHECK(Contains(cursor));
969 if (cursor == first_instruction_) {
970 cursor->previous_ = instruction;
971 instruction->next_ = cursor;
972 first_instruction_ = instruction;
973 } else {
974 instruction->previous_ = cursor->previous_;
975 instruction->next_ = cursor;
976 cursor->previous_ = instruction;
977 instruction->previous_->next_ = instruction;
978 }
979}
980
981void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
982 DCHECK(Contains(cursor));
983 if (cursor == last_instruction_) {
984 cursor->next_ = instruction;
985 instruction->previous_ = cursor;
986 last_instruction_ = instruction;
987 } else {
988 instruction->next_ = cursor->next_;
989 instruction->previous_ = cursor;
990 cursor->next_ = instruction;
991 instruction->next_->previous_ = instruction;
992 }
993}
994
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100995void HInstructionList::RemoveInstruction(HInstruction* instruction) {
996 if (instruction->previous_ != nullptr) {
997 instruction->previous_->next_ = instruction->next_;
998 }
999 if (instruction->next_ != nullptr) {
1000 instruction->next_->previous_ = instruction->previous_;
1001 }
1002 if (instruction == first_instruction_) {
1003 first_instruction_ = instruction->next_;
1004 }
1005 if (instruction == last_instruction_) {
1006 last_instruction_ = instruction->previous_;
1007 }
1008}
1009
Roland Levillain6b469232014-09-25 10:10:38 +01001010bool HInstructionList::Contains(HInstruction* instruction) const {
1011 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1012 if (it.Current() == instruction) {
1013 return true;
1014 }
1015 }
1016 return false;
1017}
1018
Roland Levillainccc07a92014-09-16 14:48:16 +01001019bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1020 const HInstruction* instruction2) const {
1021 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1022 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1023 if (it.Current() == instruction1) {
1024 return true;
1025 }
1026 if (it.Current() == instruction2) {
1027 return false;
1028 }
1029 }
1030 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1031 return true;
1032}
1033
Roland Levillain6c82d402014-10-13 16:10:27 +01001034bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1035 if (other_instruction == this) {
1036 // An instruction does not strictly dominate itself.
1037 return false;
1038 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001039 HBasicBlock* block = GetBlock();
1040 HBasicBlock* other_block = other_instruction->GetBlock();
1041 if (block != other_block) {
1042 return GetBlock()->Dominates(other_instruction->GetBlock());
1043 } else {
1044 // If both instructions are in the same block, ensure this
1045 // instruction comes before `other_instruction`.
1046 if (IsPhi()) {
1047 if (!other_instruction->IsPhi()) {
1048 // Phis appear before non phi-instructions so this instruction
1049 // dominates `other_instruction`.
1050 return true;
1051 } else {
1052 // There is no order among phis.
1053 LOG(FATAL) << "There is no dominance between phis of a same block.";
1054 return false;
1055 }
1056 } else {
1057 // `this` is not a phi.
1058 if (other_instruction->IsPhi()) {
1059 // Phis appear before non phi-instructions so this instruction
1060 // does not dominate `other_instruction`.
1061 return false;
1062 } else {
1063 // Check whether this instruction comes before
1064 // `other_instruction` in the instruction list.
1065 return block->GetInstructions().FoundBefore(this, other_instruction);
1066 }
1067 }
1068 }
1069}
1070
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001071void HInstruction::RemoveEnvironment() {
1072 RemoveEnvironmentUses(this);
1073 environment_ = nullptr;
1074}
1075
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001076void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001077 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001078 // Note: fixup_end remains valid across splice_after().
1079 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1080 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1081 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001082
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001083 // Note: env_fixup_end remains valid across splice_after().
1084 auto env_fixup_end =
1085 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1086 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1087 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001088
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001089 DCHECK(uses_.empty());
1090 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001091}
1092
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001093void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1094 const HUseList<HInstruction*>& uses = GetUses();
1095 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1096 HInstruction* user = it->GetUser();
1097 size_t index = it->GetIndex();
1098 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1099 ++it;
1100 if (dominator->StrictlyDominates(user)) {
1101 user->ReplaceInput(replacement, index);
1102 }
1103 }
1104}
1105
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001106void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001107 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001108 if (input_use.GetInstruction() == replacement) {
1109 // Nothing to do.
1110 return;
1111 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001112 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001113 // Note: fixup_end remains valid across splice_after().
1114 auto fixup_end =
1115 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1116 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1117 input_use.GetInstruction()->uses_,
1118 before_use_node);
1119 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1120 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001121}
1122
Nicolas Geoffray39468442014-09-02 15:17:15 +01001123size_t HInstruction::EnvironmentSize() const {
1124 return HasEnvironment() ? environment_->Size() : 0;
1125}
1126
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001127void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001128 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001129 inputs_.push_back(HUserRecord<HInstruction*>(input));
1130 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001131}
1132
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001133void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1134 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1135 input->AddUseAt(this, index);
1136 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1137 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1138 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1139 inputs_[i].GetUseNode()->SetIndex(i);
1140 }
1141}
1142
1143void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001144 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001145 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001146 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1147 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1148 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1149 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001150 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001151}
1152
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001153#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001154void H##name::Accept(HGraphVisitor* visitor) { \
1155 visitor->Visit##name(this); \
1156}
1157
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001158FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001159
1160#undef DEFINE_ACCEPT
1161
1162void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001163 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1164 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001165 if (block != nullptr) {
1166 VisitBasicBlock(block);
1167 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001168 }
1169}
1170
Roland Levillain633021e2014-10-01 14:12:25 +01001171void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001172 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1173 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001174 }
1175}
1176
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001177void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001178 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001179 it.Current()->Accept(this);
1180 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001181 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001182 it.Current()->Accept(this);
1183 }
1184}
1185
Mark Mendelle82549b2015-05-06 10:55:34 -04001186HConstant* HTypeConversion::TryStaticEvaluation() const {
1187 HGraph* graph = GetBlock()->GetGraph();
1188 if (GetInput()->IsIntConstant()) {
1189 int32_t value = GetInput()->AsIntConstant()->GetValue();
1190 switch (GetResultType()) {
1191 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001192 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001193 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001194 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001195 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001196 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001197 default:
1198 return nullptr;
1199 }
1200 } else if (GetInput()->IsLongConstant()) {
1201 int64_t value = GetInput()->AsLongConstant()->GetValue();
1202 switch (GetResultType()) {
1203 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001204 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001205 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001206 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001207 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001208 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001209 default:
1210 return nullptr;
1211 }
1212 } else if (GetInput()->IsFloatConstant()) {
1213 float value = GetInput()->AsFloatConstant()->GetValue();
1214 switch (GetResultType()) {
1215 case Primitive::kPrimInt:
1216 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001217 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001218 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001219 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001220 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001221 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1222 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001223 case Primitive::kPrimLong:
1224 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001225 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001226 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001227 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001228 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001229 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1230 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001231 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001232 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001233 default:
1234 return nullptr;
1235 }
1236 } else if (GetInput()->IsDoubleConstant()) {
1237 double value = GetInput()->AsDoubleConstant()->GetValue();
1238 switch (GetResultType()) {
1239 case Primitive::kPrimInt:
1240 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001241 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001242 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001243 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001244 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001245 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1246 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001247 case Primitive::kPrimLong:
1248 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001249 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001250 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001251 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001252 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001253 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1254 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001255 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001256 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001257 default:
1258 return nullptr;
1259 }
1260 }
1261 return nullptr;
1262}
1263
Roland Levillain9240d6a2014-10-20 16:47:04 +01001264HConstant* HUnaryOperation::TryStaticEvaluation() const {
1265 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001266 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001267 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001268 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001269 } else if (kEnableFloatingPointStaticEvaluation) {
1270 if (GetInput()->IsFloatConstant()) {
1271 return Evaluate(GetInput()->AsFloatConstant());
1272 } else if (GetInput()->IsDoubleConstant()) {
1273 return Evaluate(GetInput()->AsDoubleConstant());
1274 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001275 }
1276 return nullptr;
1277}
1278
1279HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001280 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1281 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001282 } else if (GetLeft()->IsLongConstant()) {
1283 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001284 // The binop(long, int) case is only valid for shifts and rotations.
1285 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001286 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1287 } else if (GetRight()->IsLongConstant()) {
1288 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001289 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001290 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001291 // The binop(null, null) case is only valid for equal and not-equal conditions.
1292 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001293 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001294 } else if (kEnableFloatingPointStaticEvaluation) {
1295 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1296 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1297 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1298 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1299 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001300 }
1301 return nullptr;
1302}
Dave Allison20dfc792014-06-16 20:44:29 -07001303
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001304HConstant* HBinaryOperation::GetConstantRight() const {
1305 if (GetRight()->IsConstant()) {
1306 return GetRight()->AsConstant();
1307 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1308 return GetLeft()->AsConstant();
1309 } else {
1310 return nullptr;
1311 }
1312}
1313
1314// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001315// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001316HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1317 HInstruction* most_constant_right = GetConstantRight();
1318 if (most_constant_right == nullptr) {
1319 return nullptr;
1320 } else if (most_constant_right == GetLeft()) {
1321 return GetRight();
1322 } else {
1323 return GetLeft();
1324 }
1325}
1326
Roland Levillain31dd3d62016-02-16 12:21:02 +00001327std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1328 switch (rhs) {
1329 case ComparisonBias::kNoBias:
1330 return os << "no_bias";
1331 case ComparisonBias::kGtBias:
1332 return os << "gt_bias";
1333 case ComparisonBias::kLtBias:
1334 return os << "lt_bias";
1335 default:
1336 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1337 UNREACHABLE();
1338 }
1339}
1340
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001341std::ostream& operator<<(std::ostream& os, const HDeoptimize::Kind& rhs) {
1342 switch (rhs) {
1343 case HDeoptimize::Kind::kBCE:
1344 return os << "bce";
1345 case HDeoptimize::Kind::kInline:
1346 return os << "inline";
1347 default:
1348 LOG(FATAL) << "Unknown Deoptimization kind: " << static_cast<int>(rhs);
1349 UNREACHABLE();
1350 }
1351}
1352
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001353bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1354 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001355}
1356
Vladimir Marko372f10e2016-05-17 16:30:10 +01001357bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001358 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001359 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001360 if (!InstructionDataEquals(other)) return false;
1361 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001362 HConstInputsRef inputs = GetInputs();
1363 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001364 if (inputs.size() != other_inputs.size()) return false;
1365 for (size_t i = 0; i != inputs.size(); ++i) {
1366 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001367 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001368
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001369 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001370 return true;
1371}
1372
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001373std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1374#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1375 switch (rhs) {
1376 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1377 default:
1378 os << "Unknown instruction kind " << static_cast<int>(rhs);
1379 break;
1380 }
1381#undef DECLARE_CASE
1382 return os;
1383}
1384
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001385void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1386 if (do_checks) {
1387 DCHECK(!IsPhi());
1388 DCHECK(!IsControlFlow());
1389 DCHECK(CanBeMoved() ||
1390 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1391 IsShouldDeoptimizeFlag());
1392 DCHECK(!cursor->IsPhi());
1393 }
David Brazdild6c205e2016-06-07 14:20:52 +01001394
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001395 next_->previous_ = previous_;
1396 if (previous_ != nullptr) {
1397 previous_->next_ = next_;
1398 }
1399 if (block_->instructions_.first_instruction_ == this) {
1400 block_->instructions_.first_instruction_ = next_;
1401 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001402 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001403
1404 previous_ = cursor->previous_;
1405 if (previous_ != nullptr) {
1406 previous_->next_ = this;
1407 }
1408 next_ = cursor;
1409 cursor->previous_ = this;
1410 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001411
1412 if (block_->instructions_.first_instruction_ == cursor) {
1413 block_->instructions_.first_instruction_ = this;
1414 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001415}
1416
Vladimir Markofb337ea2015-11-25 15:25:10 +00001417void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1418 DCHECK(!CanThrow());
1419 DCHECK(!HasSideEffects());
1420 DCHECK(!HasEnvironmentUses());
1421 DCHECK(HasNonEnvironmentUses());
1422 DCHECK(!IsPhi()); // Makes no sense for Phi.
1423 DCHECK_EQ(InputCount(), 0u);
1424
1425 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001426 auto uses_it = GetUses().begin();
1427 auto uses_end = GetUses().end();
1428 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1429 ++uses_it;
1430 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1431 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001432 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001433 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001434 // This instruction has uses in two or more blocks. Find the common dominator.
1435 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001436 for (; uses_it != uses_end; ++uses_it) {
1437 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001438 }
1439 target_block = finder.Get();
1440 DCHECK(target_block != nullptr);
1441 }
1442 // Move to the first dominator not in a loop.
1443 while (target_block->IsInLoop()) {
1444 target_block = target_block->GetDominator();
1445 DCHECK(target_block != nullptr);
1446 }
1447
1448 // Find insertion position.
1449 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001450 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1451 if (use.GetUser()->GetBlock() == target_block &&
1452 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1453 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001454 }
1455 }
1456 if (insert_pos == nullptr) {
1457 // No user in `target_block`, insert before the control flow instruction.
1458 insert_pos = target_block->GetLastInstruction();
1459 DCHECK(insert_pos->IsControlFlow());
1460 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1461 if (insert_pos->IsIf()) {
1462 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1463 if (if_input == insert_pos->GetPrevious()) {
1464 insert_pos = if_input;
1465 }
1466 }
1467 }
1468 MoveBefore(insert_pos);
1469}
1470
David Brazdilfc6a86a2015-06-26 10:33:45 +00001471HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001472 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001473 DCHECK_EQ(cursor->GetBlock(), this);
1474
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001475 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1476 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001477 new_block->instructions_.first_instruction_ = cursor;
1478 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1479 instructions_.last_instruction_ = cursor->previous_;
1480 if (cursor->previous_ == nullptr) {
1481 instructions_.first_instruction_ = nullptr;
1482 } else {
1483 cursor->previous_->next_ = nullptr;
1484 cursor->previous_ = nullptr;
1485 }
1486
1487 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001488 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001489
Vladimir Marko60584552015-09-03 13:35:12 +00001490 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001491 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001492 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001493 new_block->successors_.swap(successors_);
1494 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001495 AddSuccessor(new_block);
1496
David Brazdil56e1acc2015-06-30 15:41:36 +01001497 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001498 return new_block;
1499}
1500
David Brazdild7558da2015-09-22 13:04:14 +01001501HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001502 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001503 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1504
1505 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1506
1507 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001508 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1509 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001510 new_block->predecessors_.swap(predecessors_);
1511 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001512 AddPredecessor(new_block);
1513
1514 GetGraph()->AddBlock(new_block);
1515 return new_block;
1516}
1517
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001518HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1519 DCHECK_EQ(cursor->GetBlock(), this);
1520
1521 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1522 cursor->GetDexPc());
1523 new_block->instructions_.first_instruction_ = cursor;
1524 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1525 instructions_.last_instruction_ = cursor->previous_;
1526 if (cursor->previous_ == nullptr) {
1527 instructions_.first_instruction_ = nullptr;
1528 } else {
1529 cursor->previous_->next_ = nullptr;
1530 cursor->previous_ = nullptr;
1531 }
1532
1533 new_block->instructions_.SetBlockOfInstructions(new_block);
1534
1535 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001536 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1537 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001538 new_block->successors_.swap(successors_);
1539 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001540
1541 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1542 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001543 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001544 new_block->dominated_blocks_.swap(dominated_blocks_);
1545 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001546 return new_block;
1547}
1548
1549HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001550 DCHECK(!cursor->IsControlFlow());
1551 DCHECK_NE(instructions_.last_instruction_, cursor);
1552 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001553
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001554 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1555 new_block->instructions_.first_instruction_ = cursor->GetNext();
1556 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1557 cursor->next_->previous_ = nullptr;
1558 cursor->next_ = nullptr;
1559 instructions_.last_instruction_ = cursor;
1560
1561 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001562 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001563 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001564 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001565 new_block->successors_.swap(successors_);
1566 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001567
Vladimir Marko60584552015-09-03 13:35:12 +00001568 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001569 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001570 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001571 new_block->dominated_blocks_.swap(dominated_blocks_);
1572 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001573 return new_block;
1574}
1575
David Brazdilec16f792015-08-19 15:04:01 +01001576const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001577 if (EndsWithTryBoundary()) {
1578 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1579 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001580 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001581 return try_boundary;
1582 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001583 DCHECK(IsTryBlock());
1584 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001585 return nullptr;
1586 }
David Brazdilec16f792015-08-19 15:04:01 +01001587 } else if (IsTryBlock()) {
1588 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001589 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001590 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001591 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001592}
1593
David Brazdild7558da2015-09-22 13:04:14 +01001594bool HBasicBlock::HasThrowingInstructions() const {
1595 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1596 if (it.Current()->CanThrow()) {
1597 return true;
1598 }
1599 }
1600 return false;
1601}
1602
David Brazdilfc6a86a2015-06-26 10:33:45 +00001603static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1604 return block.GetPhis().IsEmpty()
1605 && !block.GetInstructions().IsEmpty()
1606 && block.GetFirstInstruction() == block.GetLastInstruction();
1607}
1608
David Brazdil46e2a392015-03-16 17:31:52 +00001609bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001610 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1611}
1612
1613bool HBasicBlock::IsSingleTryBoundary() const {
1614 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001615}
1616
David Brazdil8d5b8b22015-03-24 10:51:52 +00001617bool HBasicBlock::EndsWithControlFlowInstruction() const {
1618 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1619}
1620
David Brazdilb2bd1c52015-03-25 11:17:37 +00001621bool HBasicBlock::EndsWithIf() const {
1622 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1623}
1624
David Brazdilffee3d32015-07-06 11:48:53 +01001625bool HBasicBlock::EndsWithTryBoundary() const {
1626 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1627}
1628
David Brazdilb2bd1c52015-03-25 11:17:37 +00001629bool HBasicBlock::HasSinglePhi() const {
1630 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1631}
1632
David Brazdild26a4112015-11-10 11:07:31 +00001633ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1634 if (EndsWithTryBoundary()) {
1635 // The normal-flow successor of HTryBoundary is always stored at index zero.
1636 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1637 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1638 } else {
1639 // All successors of blocks not ending with TryBoundary are normal.
1640 return ArrayRef<HBasicBlock* const>(successors_);
1641 }
1642}
1643
1644ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1645 if (EndsWithTryBoundary()) {
1646 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1647 } else {
1648 // Blocks not ending with TryBoundary do not have exceptional successors.
1649 return ArrayRef<HBasicBlock* const>();
1650 }
1651}
1652
David Brazdilffee3d32015-07-06 11:48:53 +01001653bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001654 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1655 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1656
1657 size_t length = handlers1.size();
1658 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001659 return false;
1660 }
1661
David Brazdilb618ade2015-07-29 10:31:29 +01001662 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001663 for (size_t i = 0; i < length; ++i) {
1664 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001665 return false;
1666 }
1667 }
1668 return true;
1669}
1670
David Brazdil2d7352b2015-04-20 14:52:42 +01001671size_t HInstructionList::CountSize() const {
1672 size_t size = 0;
1673 HInstruction* current = first_instruction_;
1674 for (; current != nullptr; current = current->GetNext()) {
1675 size++;
1676 }
1677 return size;
1678}
1679
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001680void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1681 for (HInstruction* current = first_instruction_;
1682 current != nullptr;
1683 current = current->GetNext()) {
1684 current->SetBlock(block);
1685 }
1686}
1687
1688void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1689 DCHECK(Contains(cursor));
1690 if (!instruction_list.IsEmpty()) {
1691 if (cursor == last_instruction_) {
1692 last_instruction_ = instruction_list.last_instruction_;
1693 } else {
1694 cursor->next_->previous_ = instruction_list.last_instruction_;
1695 }
1696 instruction_list.last_instruction_->next_ = cursor->next_;
1697 cursor->next_ = instruction_list.first_instruction_;
1698 instruction_list.first_instruction_->previous_ = cursor;
1699 }
1700}
1701
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001702void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1703 DCHECK(Contains(cursor));
1704 if (!instruction_list.IsEmpty()) {
1705 if (cursor == first_instruction_) {
1706 first_instruction_ = instruction_list.first_instruction_;
1707 } else {
1708 cursor->previous_->next_ = instruction_list.first_instruction_;
1709 }
1710 instruction_list.last_instruction_->next_ = cursor;
1711 instruction_list.first_instruction_->previous_ = cursor->previous_;
1712 cursor->previous_ = instruction_list.last_instruction_;
1713 }
1714}
1715
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001716void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001717 if (IsEmpty()) {
1718 first_instruction_ = instruction_list.first_instruction_;
1719 last_instruction_ = instruction_list.last_instruction_;
1720 } else {
1721 AddAfter(last_instruction_, instruction_list);
1722 }
1723}
1724
David Brazdil04ff4e82015-12-10 13:54:52 +00001725// Should be called on instructions in a dead block in post order. This method
1726// assumes `insn` has been removed from all users with the exception of catch
1727// phis because of missing exceptional edges in the graph. It removes the
1728// instruction from catch phi uses, together with inputs of other catch phis in
1729// the catch block at the same index, as these must be dead too.
1730static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1731 DCHECK(!insn->HasEnvironmentUses());
1732 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001733 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1734 size_t use_index = use.GetIndex();
1735 HBasicBlock* user_block = use.GetUser()->GetBlock();
1736 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001737 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1738 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1739 }
1740 }
1741}
1742
David Brazdil2d7352b2015-04-20 14:52:42 +01001743void HBasicBlock::DisconnectAndDelete() {
1744 // Dominators must be removed after all the blocks they dominate. This way
1745 // a loop header is removed last, a requirement for correct loop information
1746 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001747 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001748
David Brazdil9eeebf62016-03-24 11:18:15 +00001749 // The following steps gradually remove the block from all its dependants in
1750 // post order (b/27683071).
1751
1752 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1753 // We need to do this before step (4) which destroys the predecessor list.
1754 HBasicBlock* loop_update_start = this;
1755 if (IsLoopHeader()) {
1756 HLoopInformation* loop_info = GetLoopInformation();
1757 // All other blocks in this loop should have been removed because the header
1758 // was their dominator.
1759 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1760 DCHECK(!loop_info->IsIrreducible());
1761 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1762 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1763 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001764 }
1765
David Brazdil9eeebf62016-03-24 11:18:15 +00001766 // (2) Disconnect the block from its successors and update their phis.
1767 for (HBasicBlock* successor : successors_) {
1768 // Delete this block from the list of predecessors.
1769 size_t this_index = successor->GetPredecessorIndexOf(this);
1770 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1771
1772 // Check that `successor` has other predecessors, otherwise `this` is the
1773 // dominator of `successor` which violates the order DCHECKed at the top.
1774 DCHECK(!successor->predecessors_.empty());
1775
1776 // Remove this block's entries in the successor's phis. Skip exceptional
1777 // successors because catch phi inputs do not correspond to predecessor
1778 // blocks but throwing instructions. The inputs of the catch phis will be
1779 // updated in step (3).
1780 if (!successor->IsCatchBlock()) {
1781 if (successor->predecessors_.size() == 1u) {
1782 // The successor has just one predecessor left. Replace phis with the only
1783 // remaining input.
1784 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1785 HPhi* phi = phi_it.Current()->AsPhi();
1786 phi->ReplaceWith(phi->InputAt(1 - this_index));
1787 successor->RemovePhi(phi);
1788 }
1789 } else {
1790 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1791 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1792 }
1793 }
1794 }
1795 }
1796 successors_.clear();
1797
1798 // (3) Remove instructions and phis. Instructions should have no remaining uses
1799 // except in catch phis. If an instruction is used by a catch phi at `index`,
1800 // remove `index`-th input of all phis in the catch block since they are
1801 // guaranteed dead. Note that we may miss dead inputs this way but the
1802 // graph will always remain consistent.
1803 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1804 HInstruction* insn = it.Current();
1805 RemoveUsesOfDeadInstruction(insn);
1806 RemoveInstruction(insn);
1807 }
1808 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1809 HPhi* insn = it.Current()->AsPhi();
1810 RemoveUsesOfDeadInstruction(insn);
1811 RemovePhi(insn);
1812 }
1813
1814 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001815 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001816 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001817 // We should not see any back edges as they would have been removed by step (3).
1818 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1819
David Brazdil2d7352b2015-04-20 14:52:42 +01001820 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001821 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1822 // This block is the only normal-flow successor of the TryBoundary which
1823 // makes `predecessor` dead. Since DCE removes blocks in post order,
1824 // exception handlers of this TryBoundary were already visited and any
1825 // remaining handlers therefore must be live. We remove `predecessor` from
1826 // their list of predecessors.
1827 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1828 while (predecessor->GetSuccessors().size() > 1) {
1829 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1830 DCHECK(handler->IsCatchBlock());
1831 predecessor->RemoveSuccessor(handler);
1832 handler->RemovePredecessor(predecessor);
1833 }
1834 }
1835
David Brazdil2d7352b2015-04-20 14:52:42 +01001836 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001837 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1838 if (num_pred_successors == 1u) {
1839 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001840 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1841 // successor. Replace those with a HGoto.
1842 DCHECK(last_instruction->IsIf() ||
1843 last_instruction->IsPackedSwitch() ||
1844 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001845 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001846 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001847 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001848 // The predecessor has no remaining successors and therefore must be dead.
1849 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001850 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001851 predecessor->RemoveInstruction(last_instruction);
1852 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001853 // There are multiple successors left. The removed block might be a successor
1854 // of a PackedSwitch which will be completely removed (perhaps replaced with
1855 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1856 // case, leave `last_instruction` as is for now.
1857 DCHECK(last_instruction->IsPackedSwitch() ||
1858 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001859 }
David Brazdil46e2a392015-03-16 17:31:52 +00001860 }
Vladimir Marko60584552015-09-03 13:35:12 +00001861 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001862
David Brazdil9eeebf62016-03-24 11:18:15 +00001863 // (5) Remove the block from all loops it is included in. Skip the inner-most
1864 // loop if this is the loop header (see definition of `loop_update_start`)
1865 // because the loop header's predecessor list has been destroyed in step (4).
1866 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1867 HLoopInformation* loop_info = it.Current();
1868 loop_info->Remove(this);
1869 if (loop_info->IsBackEdge(*this)) {
1870 // If this was the last back edge of the loop, we deliberately leave the
1871 // loop in an inconsistent state and will fail GraphChecker unless the
1872 // entire loop is removed during the pass.
1873 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001874 }
1875 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001876
David Brazdil9eeebf62016-03-24 11:18:15 +00001877 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001878 dominator_->RemoveDominatedBlock(this);
1879 SetDominator(nullptr);
1880
David Brazdil9eeebf62016-03-24 11:18:15 +00001881 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001882 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001883 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001884}
1885
Aart Bik6b69e0a2017-01-11 10:20:43 -08001886void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
1887 DCHECK(EndsWithControlFlowInstruction());
1888 RemoveInstruction(GetLastInstruction());
1889 instructions_.Add(other->GetInstructions());
1890 other->instructions_.SetBlockOfInstructions(this);
1891 other->instructions_.Clear();
1892}
1893
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001894void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001895 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001896 DCHECK(ContainsElement(dominated_blocks_, other));
1897 DCHECK_EQ(GetSingleSuccessor(), other);
1898 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001899 DCHECK(other->GetPhis().IsEmpty());
1900
David Brazdil2d7352b2015-04-20 14:52:42 +01001901 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08001902 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001903
David Brazdil2d7352b2015-04-20 14:52:42 +01001904 // Remove `other` from the loops it is included in.
1905 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1906 HLoopInformation* loop_info = it.Current();
1907 loop_info->Remove(other);
1908 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001909 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001910 }
1911 }
1912
1913 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001914 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00001915 for (HBasicBlock* successor : other->GetSuccessors()) {
1916 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001917 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001918 successors_.swap(other->successors_);
1919 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001920
David Brazdil2d7352b2015-04-20 14:52:42 +01001921 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001922 RemoveDominatedBlock(other);
1923 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001924 dominated->SetDominator(this);
1925 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001926 dominated_blocks_.insert(
1927 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00001928 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001929 other->dominator_ = nullptr;
1930
1931 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001932 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001933
1934 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001935 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001936 other->SetGraph(nullptr);
1937}
1938
1939void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1940 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001941 DCHECK(GetDominatedBlocks().empty());
1942 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001943 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001944 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001945 DCHECK(other->GetPhis().IsEmpty());
1946 DCHECK(!other->IsInLoop());
1947
1948 // Move instructions from `other` to `this`.
1949 instructions_.Add(other->GetInstructions());
1950 other->instructions_.SetBlockOfInstructions(this);
1951
1952 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001953 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00001954 for (HBasicBlock* successor : other->GetSuccessors()) {
1955 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01001956 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001957 successors_.swap(other->successors_);
1958 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001959
1960 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001961 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001962 dominated->SetDominator(this);
1963 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001964 dominated_blocks_.insert(
1965 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00001966 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001967 other->dominator_ = nullptr;
1968 other->graph_ = nullptr;
1969}
1970
1971void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001972 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001973 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001974 predecessor->ReplaceSuccessor(this, other);
1975 }
Vladimir Marko60584552015-09-03 13:35:12 +00001976 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001977 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001978 successor->ReplacePredecessor(this, other);
1979 }
Vladimir Marko60584552015-09-03 13:35:12 +00001980 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1981 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001982 }
1983 GetDominator()->ReplaceDominatedBlock(this, other);
1984 other->SetDominator(GetDominator());
1985 dominator_ = nullptr;
1986 graph_ = nullptr;
1987}
1988
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001989void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001990 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001991 DCHECK(block->GetSuccessors().empty());
1992 DCHECK(block->GetPredecessors().empty());
1993 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001994 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001995 DCHECK(block->GetInstructions().IsEmpty());
1996 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001997
David Brazdilc7af85d2015-05-26 12:05:55 +01001998 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06001999 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002000 }
2001
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002002 RemoveElement(reverse_post_order_, block);
2003 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002004 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002005}
2006
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002007void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2008 HBasicBlock* reference,
2009 bool replace_if_back_edge) {
2010 if (block->IsLoopHeader()) {
2011 // Clear the information of which blocks are contained in that loop. Since the
2012 // information is stored as a bit vector based on block ids, we have to update
2013 // it, as those block ids were specific to the callee graph and we are now adding
2014 // these blocks to the caller graph.
2015 block->GetLoopInformation()->ClearAllBlocks();
2016 }
2017
2018 // If not already in a loop, update the loop information.
2019 if (!block->IsInLoop()) {
2020 block->SetLoopInformation(reference->GetLoopInformation());
2021 }
2022
2023 // If the block is in a loop, update all its outward loops.
2024 HLoopInformation* loop_info = block->GetLoopInformation();
2025 if (loop_info != nullptr) {
2026 for (HLoopInformationOutwardIterator loop_it(*block);
2027 !loop_it.Done();
2028 loop_it.Advance()) {
2029 loop_it.Current()->Add(block);
2030 }
2031 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2032 loop_info->ReplaceBackEdge(reference, block);
2033 }
2034 }
2035
2036 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2037 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2038 ? reference->GetTryCatchInformation()
2039 : nullptr;
2040 block->SetTryCatchInformation(try_catch_info);
2041}
2042
Calin Juravle2e768302015-07-28 14:41:11 +00002043HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002044 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002045 // Update the environments in this graph to have the invoke's environment
2046 // as parent.
2047 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002048 // Skip the entry block, we do not need to update the entry's suspend check.
2049 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002050 for (HInstructionIterator instr_it(block->GetInstructions());
2051 !instr_it.Done();
2052 instr_it.Advance()) {
2053 HInstruction* current = instr_it.Current();
2054 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002055 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002056 current->GetEnvironment()->SetAndCopyParentChain(
2057 outer_graph->GetArena(), invoke->GetEnvironment());
2058 }
2059 }
2060 }
2061 }
2062 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002063
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002064 if (HasBoundsChecks()) {
2065 outer_graph->SetHasBoundsChecks(true);
2066 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002067 if (HasLoops()) {
2068 outer_graph->SetHasLoops(true);
2069 }
2070 if (HasIrreducibleLoops()) {
2071 outer_graph->SetHasIrreducibleLoops(true);
2072 }
2073 if (HasTryCatch()) {
2074 outer_graph->SetHasTryCatch(true);
2075 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002076 if (HasSIMD()) {
2077 outer_graph->SetHasSIMD(true);
2078 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002079
Calin Juravle2e768302015-07-28 14:41:11 +00002080 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002081 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002082 // Inliner already made sure we don't inline methods that always throw.
2083 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002084 // Simple case of an entry block, a body block, and an exit block.
2085 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002086 HBasicBlock* body = GetBlocks()[1];
2087 DCHECK(GetBlocks()[0]->IsEntryBlock());
2088 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002089 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002090 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002091 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002092
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002093 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2094 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002095 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002096
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002097 // Replace the invoke with the return value of the inlined graph.
2098 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002099 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002100 } else {
2101 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002102 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002103
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002104 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002105 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002106 // Need to inline multiple blocks. We split `invoke`'s block
2107 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002108 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002109 // with the second half.
2110 ArenaAllocator* allocator = outer_graph->GetArena();
2111 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002112 // Note that we split before the invoke only to simplify polymorphic inlining.
2113 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002114
Vladimir Markoec7802a2015-10-01 20:57:57 +01002115 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002116 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002117 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002118 exit_block_->ReplaceWith(to);
2119
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002120 // Update the meta information surrounding blocks:
2121 // (1) the graph they are now in,
2122 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002123 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002124 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002125 // Note that we do not need to update catch phi inputs because they
2126 // correspond to the register file of the outer method which the inlinee
2127 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002128
2129 // We don't add the entry block, the exit block, and the first block, which
2130 // has been merged with `at`.
2131 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2132
2133 // We add the `to` block.
2134 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002135 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002136 + kNumberOfNewBlocksInCaller;
2137
2138 // Find the location of `at` in the outer graph's reverse post order. The new
2139 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002140 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002141 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2142
David Brazdil95177982015-10-30 12:56:58 -05002143 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2144 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002145 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002146 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002147 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002148 DCHECK(current->GetGraph() == this);
2149 current->SetGraph(outer_graph);
2150 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002151 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002152 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002153 }
2154 }
2155
David Brazdil95177982015-10-30 12:56:58 -05002156 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002157 to->SetGraph(outer_graph);
2158 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002159 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002160 // Only `to` can become a back edge, as the inlined blocks
2161 // are predecessors of `to`.
2162 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002163
David Brazdil3f523062016-02-29 16:53:33 +00002164 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002165 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2166 // to now get the outer graph exit block as successor. Note that the inliner
2167 // currently doesn't support inlining methods with try/catch.
2168 HPhi* return_value_phi = nullptr;
2169 bool rerun_dominance = false;
2170 bool rerun_loop_analysis = false;
2171 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2172 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002173 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002174 if (last->IsThrow()) {
2175 DCHECK(!at->IsTryBlock());
2176 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2177 --pred;
2178 // We need to re-run dominance information, as the exit block now has
2179 // a new dominator.
2180 rerun_dominance = true;
2181 if (predecessor->GetLoopInformation() != nullptr) {
2182 // The exit block and blocks post dominated by the exit block do not belong
2183 // to any loop. Because we do not compute the post dominators, we need to re-run
2184 // loop analysis to get the loop information correct.
2185 rerun_loop_analysis = true;
2186 }
2187 } else {
2188 if (last->IsReturnVoid()) {
2189 DCHECK(return_value == nullptr);
2190 DCHECK(return_value_phi == nullptr);
2191 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002192 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002193 if (return_value_phi != nullptr) {
2194 return_value_phi->AddInput(last->InputAt(0));
2195 } else if (return_value == nullptr) {
2196 return_value = last->InputAt(0);
2197 } else {
2198 // There will be multiple returns.
2199 return_value_phi = new (allocator) HPhi(
2200 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2201 to->AddPhi(return_value_phi);
2202 return_value_phi->AddInput(return_value);
2203 return_value_phi->AddInput(last->InputAt(0));
2204 return_value = return_value_phi;
2205 }
David Brazdil3f523062016-02-29 16:53:33 +00002206 }
2207 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2208 predecessor->RemoveInstruction(last);
2209 }
2210 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002211 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002212 DCHECK(!outer_graph->HasIrreducibleLoops())
2213 << "Recomputing loop information in graphs with irreducible loops "
2214 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002215 outer_graph->ClearLoopInformation();
2216 outer_graph->ClearDominanceInformation();
2217 outer_graph->BuildDominatorTree();
2218 } else if (rerun_dominance) {
2219 outer_graph->ClearDominanceInformation();
2220 outer_graph->ComputeDominanceInformation();
2221 }
David Brazdil3f523062016-02-29 16:53:33 +00002222 }
David Brazdil05144f42015-04-16 15:18:00 +01002223
2224 // Walk over the entry block and:
2225 // - Move constants from the entry block to the outer_graph's entry block,
2226 // - Replace HParameterValue instructions with their real value.
2227 // - Remove suspend checks, that hold an environment.
2228 // We must do this after the other blocks have been inlined, otherwise ids of
2229 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002230 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002231 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2232 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002233 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002234 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002235 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002236 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002237 replacement = outer_graph->GetIntConstant(
2238 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002239 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002240 replacement = outer_graph->GetLongConstant(
2241 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002242 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002243 replacement = outer_graph->GetFloatConstant(
2244 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002245 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002246 replacement = outer_graph->GetDoubleConstant(
2247 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002248 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002249 if (kIsDebugBuild
2250 && invoke->IsInvokeStaticOrDirect()
2251 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2252 // Ensure we do not use the last input of `invoke`, as it
2253 // contains a clinit check which is not an actual argument.
2254 size_t last_input_index = invoke->InputCount() - 1;
2255 DCHECK(parameter_index != last_input_index);
2256 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002257 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002258 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002259 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002260 } else {
2261 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2262 entry_block_->RemoveInstruction(current);
2263 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002264 if (replacement != nullptr) {
2265 current->ReplaceWith(replacement);
2266 // If the current is the return value then we need to update the latter.
2267 if (current == return_value) {
2268 DCHECK_EQ(entry_block_, return_value->GetBlock());
2269 return_value = replacement;
2270 }
2271 }
2272 }
2273
Calin Juravle2e768302015-07-28 14:41:11 +00002274 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002275}
2276
Mingyao Yang3584bce2015-05-19 16:01:59 -07002277/*
2278 * Loop will be transformed to:
2279 * old_pre_header
2280 * |
2281 * if_block
2282 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002283 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002284 * \ /
2285 * new_pre_header
2286 * |
2287 * header
2288 */
2289void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2290 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002291 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002292
Aart Bik3fc7f352015-11-20 22:03:03 -08002293 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002294 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002295 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2296 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002297 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2298 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002299 AddBlock(true_block);
2300 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002301 AddBlock(new_pre_header);
2302
Aart Bik3fc7f352015-11-20 22:03:03 -08002303 header->ReplacePredecessor(old_pre_header, new_pre_header);
2304 old_pre_header->successors_.clear();
2305 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002306
Aart Bik3fc7f352015-11-20 22:03:03 -08002307 old_pre_header->AddSuccessor(if_block);
2308 if_block->AddSuccessor(true_block); // True successor
2309 if_block->AddSuccessor(false_block); // False successor
2310 true_block->AddSuccessor(new_pre_header);
2311 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002312
Aart Bik3fc7f352015-11-20 22:03:03 -08002313 old_pre_header->dominated_blocks_.push_back(if_block);
2314 if_block->SetDominator(old_pre_header);
2315 if_block->dominated_blocks_.push_back(true_block);
2316 true_block->SetDominator(if_block);
2317 if_block->dominated_blocks_.push_back(false_block);
2318 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002319 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002320 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002321 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002322 header->SetDominator(new_pre_header);
2323
Aart Bik3fc7f352015-11-20 22:03:03 -08002324 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002325 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002326 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002327 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002328 reverse_post_order_[index_of_header++] = true_block;
2329 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002330 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002331
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002332 // The pre_header can never be a back edge of a loop.
2333 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2334 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2335 UpdateLoopAndTryInformationOfNewBlock(
2336 if_block, old_pre_header, /* replace_if_back_edge */ false);
2337 UpdateLoopAndTryInformationOfNewBlock(
2338 true_block, old_pre_header, /* replace_if_back_edge */ false);
2339 UpdateLoopAndTryInformationOfNewBlock(
2340 false_block, old_pre_header, /* replace_if_back_edge */ false);
2341 UpdateLoopAndTryInformationOfNewBlock(
2342 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002343}
2344
Aart Bikf8f5a162017-02-06 15:35:29 -08002345HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2346 HBasicBlock* body,
2347 HBasicBlock* exit) {
2348 DCHECK(header->IsLoopHeader());
2349 HLoopInformation* loop = header->GetLoopInformation();
2350
2351 // Add new loop blocks.
2352 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2353 HBasicBlock* new_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2354 HBasicBlock* new_body = new (arena_) HBasicBlock(this, header->GetDexPc());
2355 AddBlock(new_pre_header);
2356 AddBlock(new_header);
2357 AddBlock(new_body);
2358
2359 // Set up control flow.
2360 header->ReplaceSuccessor(exit, new_pre_header);
2361 new_pre_header->AddSuccessor(new_header);
2362 new_header->AddSuccessor(exit);
2363 new_header->AddSuccessor(new_body);
2364 new_body->AddSuccessor(new_header);
2365
2366 // Set up dominators.
2367 header->ReplaceDominatedBlock(exit, new_pre_header);
2368 new_pre_header->SetDominator(header);
2369 new_pre_header->dominated_blocks_.push_back(new_header);
2370 new_header->SetDominator(new_pre_header);
2371 new_header->dominated_blocks_.push_back(new_body);
2372 new_body->SetDominator(new_header);
2373 new_header->dominated_blocks_.push_back(exit);
2374 exit->SetDominator(new_header);
2375
2376 // Fix reverse post order.
2377 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2378 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2379 reverse_post_order_[++index_of_header] = new_pre_header;
2380 reverse_post_order_[++index_of_header] = new_header;
2381 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2382 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2383 reverse_post_order_[index_of_body] = new_body;
2384
Aart Bikb07d1bc2017-04-05 10:03:15 -07002385 // Add gotos and suspend check (client must add conditional in header).
Aart Bikf8f5a162017-02-06 15:35:29 -08002386 new_pre_header->AddInstruction(new (arena_) HGoto());
2387 HSuspendCheck* suspend_check = new (arena_) HSuspendCheck(header->GetDexPc());
2388 new_header->AddInstruction(suspend_check);
2389 new_body->AddInstruction(new (arena_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002390 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2391 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002392
2393 // Update loop information.
2394 new_header->AddBackEdge(new_body);
2395 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2396 new_header->GetLoopInformation()->Populate();
2397 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2398 HLoopInformationOutwardIterator it(*new_header);
2399 for (it.Advance(); !it.Done(); it.Advance()) {
2400 it.Current()->Add(new_pre_header);
2401 it.Current()->Add(new_header);
2402 it.Current()->Add(new_body);
2403 }
2404 return new_pre_header;
2405}
2406
David Brazdilf5552582015-12-27 13:36:12 +00002407static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002408 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002409 if (rti.IsValid()) {
2410 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2411 << " upper_bound_rti: " << upper_bound_rti
2412 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002413 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2414 << " upper_bound_rti: " << upper_bound_rti
2415 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002416 }
2417}
2418
Calin Juravle2e768302015-07-28 14:41:11 +00002419void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2420 if (kIsDebugBuild) {
2421 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2422 ScopedObjectAccess soa(Thread::Current());
2423 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2424 if (IsBoundType()) {
2425 // Having the test here spares us from making the method virtual just for
2426 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002427 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002428 }
2429 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002430 reference_type_handle_ = rti.GetTypeHandle();
2431 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002432}
2433
David Brazdilf5552582015-12-27 13:36:12 +00002434void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2435 if (kIsDebugBuild) {
2436 ScopedObjectAccess soa(Thread::Current());
2437 DCHECK(upper_bound.IsValid());
2438 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2439 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2440 }
2441 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002442 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002443}
2444
Vladimir Markoa1de9182016-02-25 11:37:38 +00002445ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002446 if (kIsDebugBuild) {
2447 ScopedObjectAccess soa(Thread::Current());
2448 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002449 if (!is_exact) {
2450 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2451 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2452 }
Calin Juravle2e768302015-07-28 14:41:11 +00002453 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002454 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002455}
2456
Calin Juravleacf735c2015-02-12 15:25:22 +00002457std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2458 ScopedObjectAccess soa(Thread::Current());
2459 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002460 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002461 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002462 << " is_exact=" << rhs.IsExact()
2463 << " ]";
2464 return os;
2465}
2466
Mark Mendellc4701932015-04-10 13:18:51 -04002467bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2468 // For now, assume that instructions in different blocks may use the
2469 // environment.
2470 // TODO: Use the control flow to decide if this is true.
2471 if (GetBlock() != other->GetBlock()) {
2472 return true;
2473 }
2474
2475 // We know that we are in the same block. Walk from 'this' to 'other',
2476 // checking to see if there is any instruction with an environment.
2477 HInstruction* current = this;
2478 for (; current != other && current != nullptr; current = current->GetNext()) {
2479 // This is a conservative check, as the instruction result may not be in
2480 // the referenced environment.
2481 if (current->HasEnvironment()) {
2482 return true;
2483 }
2484 }
2485
2486 // We should have been called with 'this' before 'other' in the block.
2487 // Just confirm this.
2488 DCHECK(current != nullptr);
2489 return false;
2490}
2491
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002492void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002493 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2494 IntrinsicSideEffects side_effects,
2495 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002496 intrinsic_ = intrinsic;
2497 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002498
Aart Bik5d75afe2015-12-14 11:57:01 -08002499 // Adjust method's side effects from intrinsic table.
2500 switch (side_effects) {
2501 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2502 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2503 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2504 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2505 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002506
2507 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2508 opt.SetDoesNotNeedDexCache();
2509 opt.SetDoesNotNeedEnvironment();
2510 } else {
2511 // If we need an environment, that means there will be a call, which can trigger GC.
2512 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2513 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002514 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002515 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002516}
2517
David Brazdil6de19382016-01-08 17:37:10 +00002518bool HNewInstance::IsStringAlloc() const {
2519 ScopedObjectAccess soa(Thread::Current());
2520 return GetReferenceTypeInfo().IsStringClass();
2521}
2522
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002523bool HInvoke::NeedsEnvironment() const {
2524 if (!IsIntrinsic()) {
2525 return true;
2526 }
2527 IntrinsicOptimizations opt(*this);
2528 return !opt.GetDoesNotNeedEnvironment();
2529}
2530
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002531const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2532 ArtMethod* caller = GetEnvironment()->GetMethod();
2533 ScopedObjectAccess soa(Thread::Current());
2534 // `caller` is null for a top-level graph representing a method whose declaring
2535 // class was not resolved.
2536 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2537}
2538
Vladimir Markodc151b22015-10-15 18:02:30 +01002539bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2540 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002541 return false;
2542 }
2543 if (!IsIntrinsic()) {
2544 return true;
2545 }
2546 IntrinsicOptimizations opt(*this);
2547 return !opt.GetDoesNotNeedDexCache();
2548}
2549
Vladimir Markof64242a2015-12-01 14:58:23 +00002550std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2551 switch (rhs) {
2552 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2553 return os << "string_init";
2554 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2555 return os << "recursive";
2556 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2557 return os << "direct";
Vladimir Markof64242a2015-12-01 14:58:23 +00002558 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2559 return os << "dex_cache_pc_relative";
2560 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2561 return os << "dex_cache_via_method";
2562 default:
2563 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2564 UNREACHABLE();
2565 }
2566}
2567
Vladimir Markofbb184a2015-11-13 14:47:00 +00002568std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2569 switch (rhs) {
2570 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2571 return os << "explicit";
2572 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2573 return os << "implicit";
2574 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2575 return os << "none";
2576 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002577 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2578 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002579 }
2580}
2581
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002582bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2583 const HLoadClass* other_load_class = other->AsLoadClass();
2584 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2585 // names rather than type indexes. However, we shall also have to re-think the hash code.
2586 if (type_index_ != other_load_class->type_index_ ||
2587 GetPackedFields() != other_load_class->GetPackedFields()) {
2588 return false;
2589 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002590 switch (GetLoadKind()) {
2591 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002592 case LoadKind::kJitTableAddress: {
2593 ScopedObjectAccess soa(Thread::Current());
2594 return GetClass().Get() == other_load_class->GetClass().Get();
2595 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002596 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002597 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002598 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002599 }
2600}
2601
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002602void HLoadClass::SetLoadKind(LoadKind load_kind) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002603 SetPackedField<LoadKindField>(load_kind);
2604
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002605 if (load_kind != LoadKind::kDexCacheViaMethod &&
2606 load_kind != LoadKind::kReferrersClass) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002607 RemoveAsUserOfInput(0u);
2608 SetRawInputAt(0u, nullptr);
2609 }
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002610
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002611 if (!NeedsEnvironment()) {
2612 RemoveEnvironment();
2613 SetSideEffects(SideEffects::None());
2614 }
2615}
2616
2617std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2618 switch (rhs) {
2619 case HLoadClass::LoadKind::kReferrersClass:
2620 return os << "ReferrersClass";
2621 case HLoadClass::LoadKind::kBootImageLinkTimeAddress:
2622 return os << "BootImageLinkTimeAddress";
2623 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2624 return os << "BootImageLinkTimePcRelative";
2625 case HLoadClass::LoadKind::kBootImageAddress:
2626 return os << "BootImageAddress";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002627 case HLoadClass::LoadKind::kBssEntry:
2628 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002629 case HLoadClass::LoadKind::kJitTableAddress:
2630 return os << "JitTableAddress";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002631 case HLoadClass::LoadKind::kDexCacheViaMethod:
2632 return os << "DexCacheViaMethod";
2633 default:
2634 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2635 UNREACHABLE();
2636 }
2637}
2638
Vladimir Marko372f10e2016-05-17 16:30:10 +01002639bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2640 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002641 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2642 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002643 if (string_index_ != other_load_string->string_index_ ||
2644 GetPackedFields() != other_load_string->GetPackedFields()) {
2645 return false;
2646 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002647 switch (GetLoadKind()) {
2648 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002649 case LoadKind::kJitTableAddress: {
2650 ScopedObjectAccess soa(Thread::Current());
2651 return GetString().Get() == other_load_string->GetString().Get();
2652 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002653 default:
2654 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002655 }
2656}
2657
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002658void HLoadString::SetLoadKind(LoadKind load_kind) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002659 // Once sharpened, the load kind should not be changed again.
2660 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2661 SetPackedField<LoadKindField>(load_kind);
2662
2663 if (load_kind != LoadKind::kDexCacheViaMethod) {
2664 RemoveAsUserOfInput(0u);
2665 SetRawInputAt(0u, nullptr);
2666 }
2667 if (!NeedsEnvironment()) {
2668 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002669 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002670 }
2671}
2672
2673std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2674 switch (rhs) {
2675 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2676 return os << "BootImageLinkTimeAddress";
2677 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2678 return os << "BootImageLinkTimePcRelative";
2679 case HLoadString::LoadKind::kBootImageAddress:
2680 return os << "BootImageAddress";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002681 case HLoadString::LoadKind::kBssEntry:
2682 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002683 case HLoadString::LoadKind::kJitTableAddress:
2684 return os << "JitTableAddress";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002685 case HLoadString::LoadKind::kDexCacheViaMethod:
2686 return os << "DexCacheViaMethod";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002687 default:
2688 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2689 UNREACHABLE();
2690 }
2691}
2692
Mark Mendellc4701932015-04-10 13:18:51 -04002693void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002694 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2695 HEnvironment* user = use.GetUser();
2696 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002697 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002698 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002699}
2700
Roland Levillainc9b21f82016-03-23 16:36:59 +00002701// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002702HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2703 ArenaAllocator* allocator = GetArena();
2704
2705 if (cond->IsCondition() &&
2706 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2707 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2708 HInstruction* lhs = cond->InputAt(0);
2709 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002710 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002711 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2712 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2713 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2714 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2715 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2716 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2717 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2718 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2719 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2720 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2721 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002722 default:
2723 LOG(FATAL) << "Unexpected condition";
2724 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002725 }
2726 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2727 return replacement;
2728 } else if (cond->IsIntConstant()) {
2729 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002730 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002731 return GetIntConstant(1);
2732 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002733 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002734 return GetIntConstant(0);
2735 }
2736 } else {
2737 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2738 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2739 return replacement;
2740 }
2741}
2742
Roland Levillainc9285912015-12-18 10:38:42 +00002743std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2744 os << "["
2745 << " source=" << rhs.GetSource()
2746 << " destination=" << rhs.GetDestination()
2747 << " type=" << rhs.GetType()
2748 << " instruction=";
2749 if (rhs.GetInstruction() != nullptr) {
2750 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2751 } else {
2752 os << "null";
2753 }
2754 os << " ]";
2755 return os;
2756}
2757
Roland Levillain86503782016-02-11 19:07:30 +00002758std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2759 switch (rhs) {
2760 case TypeCheckKind::kUnresolvedCheck:
2761 return os << "unresolved_check";
2762 case TypeCheckKind::kExactCheck:
2763 return os << "exact_check";
2764 case TypeCheckKind::kClassHierarchyCheck:
2765 return os << "class_hierarchy_check";
2766 case TypeCheckKind::kAbstractClassCheck:
2767 return os << "abstract_class_check";
2768 case TypeCheckKind::kInterfaceCheck:
2769 return os << "interface_check";
2770 case TypeCheckKind::kArrayObjectCheck:
2771 return os << "array_object_check";
2772 case TypeCheckKind::kArrayCheck:
2773 return os << "array_check";
2774 default:
2775 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2776 UNREACHABLE();
2777 }
2778}
2779
Andreas Gampe26de38b2016-07-27 17:53:11 -07002780std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2781 switch (kind) {
2782 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002783 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002784 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002785 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002786 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002787 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002788 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002789 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002790 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002791 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002792
2793 default:
2794 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
2795 UNREACHABLE();
2796 }
2797}
2798
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002799} // namespace art