blob: 48152ce08e89cf15a7a6e106dcd848f7bf3755fb [file] [log] [blame]
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Nicolas Geoffray818f2102014-02-18 16:43:35 +000016#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000017
Roland Levillain31dd3d62016-02-16 12:21:02 +000018#include <cfloat>
19
Mark Mendelle82549b2015-05-06 10:55:34 -040020#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000021#include "common_dominator.h"
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +010022#include "ssa_builder.h"
David Brazdila4b8c212015-05-07 09:59:30 +010023#include "base/bit_vector-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010024#include "base/bit_utils.h"
Vladimir Marko1f8695c2015-09-24 13:11:31 +010025#include "base/stl_util.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010026#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010027#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070028#include "scoped_thread_state_change-inl.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000029
30namespace art {
31
Roland Levillain31dd3d62016-02-16 12:21:02 +000032// Enable floating-point static evaluation during constant folding
33// only if all floating-point operations and constants evaluate in the
34// range and precision of the type used (i.e., 32-bit float, 64-bit
35// double).
36static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
37
Mathieu Chartiere8a3c572016-10-11 16:52:17 -070038void HGraph::InitializeInexactObjectRTI(VariableSizedHandleScope* handles) {
David Brazdilbadd8262016-02-02 16:28:56 +000039 ScopedObjectAccess soa(Thread::Current());
40 // Create the inexact Object reference type and store it in the HGraph.
41 ClassLinker* linker = Runtime::Current()->GetClassLinker();
42 inexact_object_rti_ = ReferenceTypeInfo::Create(
43 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
44 /* is_exact */ false);
45}
46
Nicolas Geoffray818f2102014-02-18 16:43:35 +000047void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010048 block->SetBlockId(blocks_.size());
49 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000050}
51
Nicolas Geoffray804d0932014-05-02 08:46:00 +010052void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010053 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
54 DCHECK_EQ(visited->GetHighestBitSet(), -1);
55
56 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markof6a35de2016-03-21 12:01:50 +000057 ArenaBitVector visiting(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010058 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +010059 ArenaVector<size_t> successors_visited(blocks_.size(),
60 0u,
61 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010062 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko3ea5a972016-05-09 20:23:34 +010063 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 constexpr size_t kDefaultWorklistSize = 8;
65 worklist.reserve(kDefaultWorklistSize);
66 visited->SetBit(entry_block_->GetBlockId());
67 visiting.SetBit(entry_block_->GetBlockId());
68 worklist.push_back(entry_block_);
69
70 while (!worklist.empty()) {
71 HBasicBlock* current = worklist.back();
72 uint32_t current_id = current->GetBlockId();
73 if (successors_visited[current_id] == current->GetSuccessors().size()) {
74 visiting.ClearBit(current_id);
75 worklist.pop_back();
76 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010077 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
78 uint32_t successor_id = successor->GetBlockId();
79 if (visiting.IsBitSet(successor_id)) {
80 DCHECK(ContainsElement(worklist, successor));
81 successor->AddBackEdge(current);
82 } else if (!visited->IsBitSet(successor_id)) {
83 visited->SetBit(successor_id);
84 visiting.SetBit(successor_id);
85 worklist.push_back(successor);
86 }
87 }
88 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000089}
90
Vladimir Markocac5a7e2016-02-22 10:39:50 +000091static void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010092 for (HEnvironment* environment = instruction->GetEnvironment();
93 environment != nullptr;
94 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000095 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000096 if (environment->GetInstructionAt(i) != nullptr) {
97 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +000098 }
99 }
100 }
101}
102
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000103static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100104 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000105 RemoveEnvironmentUses(instruction);
106}
107
Roland Levillainfc600dc2014-12-02 17:16:31 +0000108void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100109 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000110 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100111 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000112 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100113 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000114 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
115 RemoveAsUser(it.Current());
116 }
117 }
118 }
119}
120
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100121void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100122 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000123 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100124 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000125 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100126 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000127 for (HBasicBlock* successor : block->GetSuccessors()) {
128 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000129 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100130 // Remove the block from the list of blocks, so that further analyses
131 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100132 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600133 if (block->IsExitBlock()) {
134 SetExitBlock(nullptr);
135 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000136 // Mark the block as removed. This is used by the HGraphBuilder to discard
137 // the block as a branch target.
138 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000139 }
140 }
141}
142
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000143GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000144 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000145
David Brazdil86ea7ee2016-02-16 09:26:07 +0000146 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000147 FindBackEdges(&visited);
148
David Brazdil86ea7ee2016-02-16 09:26:07 +0000149 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000150 // the initial DFS as users from other instructions, so that
151 // users can be safely removed before uses later.
152 RemoveInstructionsAsUsersFromDeadBlocks(visited);
153
David Brazdil86ea7ee2016-02-16 09:26:07 +0000154 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000155 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000156 // predecessors list of live blocks.
157 RemoveDeadBlocks(visited);
158
David Brazdil86ea7ee2016-02-16 09:26:07 +0000159 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100160 // dominators and the reverse post order.
161 SimplifyCFG();
162
David Brazdil86ea7ee2016-02-16 09:26:07 +0000163 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100164 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000165
David Brazdil86ea7ee2016-02-16 09:26:07 +0000166 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000167 // set the loop information on each block.
168 GraphAnalysisResult result = AnalyzeLoops();
169 if (result != kAnalysisSuccess) {
170 return result;
171 }
172
David Brazdil86ea7ee2016-02-16 09:26:07 +0000173 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000174 // which needs the information to build catch block phis from values of
175 // locals at throwing instructions inside try blocks.
176 ComputeTryBlockInformation();
177
178 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100179}
180
181void HGraph::ClearDominanceInformation() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100182 for (HBasicBlock* block : GetReversePostOrder()) {
183 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100184 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100185 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100186}
187
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000188void HGraph::ClearLoopInformation() {
189 SetHasIrreducibleLoops(false);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100190 for (HBasicBlock* block : GetReversePostOrder()) {
191 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000192 }
193}
194
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100195void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000196 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100197 dominator_ = nullptr;
198}
199
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000200HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
201 HInstruction* instruction = GetFirstInstruction();
202 while (instruction->IsParallelMove()) {
203 instruction = instruction->GetNext();
204 }
205 return instruction;
206}
207
David Brazdil3f4a5222016-05-06 12:46:21 +0100208static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
209 DCHECK(ContainsElement(block->GetSuccessors(), successor));
210
211 HBasicBlock* old_dominator = successor->GetDominator();
212 HBasicBlock* new_dominator =
213 (old_dominator == nullptr) ? block
214 : CommonDominator::ForPair(old_dominator, block);
215
216 if (old_dominator == new_dominator) {
217 return false;
218 } else {
219 successor->SetDominator(new_dominator);
220 return true;
221 }
222}
223
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100224void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100225 DCHECK(reverse_post_order_.empty());
226 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100227 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100228
229 // Number of visits of a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100230 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100231 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100232 ArenaVector<size_t> successors_visited(blocks_.size(),
233 0u,
234 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100235 // Nodes for which we need to visit successors.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100236 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100237 constexpr size_t kDefaultWorklistSize = 8;
238 worklist.reserve(kDefaultWorklistSize);
239 worklist.push_back(entry_block_);
240
241 while (!worklist.empty()) {
242 HBasicBlock* current = worklist.back();
243 uint32_t current_id = current->GetBlockId();
244 if (successors_visited[current_id] == current->GetSuccessors().size()) {
245 worklist.pop_back();
246 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100247 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100248 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100249
250 // Once all the forward edges have been visited, we know the immediate
251 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100252 if (++visits[successor->GetBlockId()] ==
253 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100254 reverse_post_order_.push_back(successor);
255 worklist.push_back(successor);
256 }
257 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000258 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000259
David Brazdil3f4a5222016-05-06 12:46:21 +0100260 // Check if the graph has back edges not dominated by their respective headers.
261 // If so, we need to update the dominators of those headers and recursively of
262 // their successors. We do that with a fix-point iteration over all blocks.
263 // The algorithm is guaranteed to terminate because it loops only if the sum
264 // of all dominator chains has decreased in the current iteration.
265 bool must_run_fix_point = false;
266 for (HBasicBlock* block : blocks_) {
267 if (block != nullptr &&
268 block->IsLoopHeader() &&
269 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
270 must_run_fix_point = true;
271 break;
272 }
273 }
274 if (must_run_fix_point) {
275 bool update_occurred = true;
276 while (update_occurred) {
277 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100278 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100279 for (HBasicBlock* successor : block->GetSuccessors()) {
280 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
281 }
282 }
283 }
284 }
285
286 // Make sure that there are no remaining blocks whose dominator information
287 // needs to be updated.
288 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100289 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100290 for (HBasicBlock* successor : block->GetSuccessors()) {
291 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
292 }
293 }
294 }
295
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000296 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000297 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100298 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000299 if (!block->IsEntryBlock()) {
300 block->GetDominator()->AddDominatedBlock(block);
301 }
302 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000303}
304
David Brazdilfc6a86a2015-06-26 10:33:45 +0000305HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000306 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
307 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000308 // Use `InsertBetween` to ensure the predecessor index and successor index of
309 // `block` and `successor` are preserved.
310 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000311 return new_block;
312}
313
314void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
315 // Insert a new node between `block` and `successor` to split the
316 // critical edge.
317 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600318 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100319 if (successor->IsLoopHeader()) {
320 // If we split at a back edge boundary, make the new block the back edge.
321 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000322 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100323 info->RemoveBackEdge(block);
324 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100325 }
326 }
327}
328
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100329void HGraph::SimplifyLoop(HBasicBlock* header) {
330 HLoopInformation* info = header->GetLoopInformation();
331
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100332 // Make sure the loop has only one pre header. This simplifies SSA building by having
333 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000334 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
335 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000336 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000337 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100338 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100339 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600340 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100341
Vladimir Marko60584552015-09-03 13:35:12 +0000342 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100343 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100344 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100345 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100346 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100347 }
348 }
349 pre_header->AddSuccessor(header);
350 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100351
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100352 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100353 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
354 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000355 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100356 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100357 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000358 header->predecessors_[pred] = to_swap;
359 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100360 break;
361 }
362 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100363 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100364
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100365 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000366 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
367 // Called from DeadBlockElimination. Update SuspendCheck pointer.
368 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100369 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100370}
371
David Brazdilffee3d32015-07-06 11:48:53 +0100372void HGraph::ComputeTryBlockInformation() {
373 // Iterate in reverse post order to propagate try membership information from
374 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100375 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100376 if (block->IsEntryBlock() || block->IsCatchBlock()) {
377 // Catch blocks after simplification have only exceptional predecessors
378 // and hence are never in tries.
379 continue;
380 }
381
382 // Infer try membership from the first predecessor. Having simplified loops,
383 // the first predecessor can never be a back edge and therefore it must have
384 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100385 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100386 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100387 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000388 if (try_entry != nullptr &&
389 (block->GetTryCatchInformation() == nullptr ||
390 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
391 // We are either setting try block membership for the first time or it
392 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100393 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
394 }
David Brazdilffee3d32015-07-06 11:48:53 +0100395 }
396}
397
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100398void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000399// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100400 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000401 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100402 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
403 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
404 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
405 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100406 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000407 if (block->GetSuccessors().size() > 1) {
408 // Only split normal-flow edges. We cannot split exceptional edges as they
409 // are synthesized (approximate real control flow), and we do not need to
410 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000411 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
412 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
413 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100414 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000415 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000416 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
417 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000418 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000419 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100420 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000421 // SplitCriticalEdge could have invalidated the `normal_successors`
422 // ArrayRef. We must re-acquire it.
423 normal_successors = block->GetNormalSuccessors();
424 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
425 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100426 }
427 }
428 }
429 if (block->IsLoopHeader()) {
430 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000431 } else if (!block->IsEntryBlock() &&
432 block->GetFirstInstruction() != nullptr &&
433 block->GetFirstInstruction()->IsSuspendCheck()) {
434 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000435 // a loop got dismantled. Just remove the suspend check.
436 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100437 }
438 }
439}
440
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000441GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100442 // We iterate post order to ensure we visit inner loops before outer loops.
443 // `PopulateRecursive` needs this guarantee to know whether a natural loop
444 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100445 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100446 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100447 if (block->IsCatchBlock()) {
448 // TODO: Dealing with exceptional back edges could be tricky because
449 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000450 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100451 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000452 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100453 }
454 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000455 return kAnalysisSuccess;
456}
457
458void HLoopInformation::Dump(std::ostream& os) {
459 os << "header: " << header_->GetBlockId() << std::endl;
460 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
461 for (HBasicBlock* block : back_edges_) {
462 os << "back edge: " << block->GetBlockId() << std::endl;
463 }
464 for (HBasicBlock* block : header_->GetPredecessors()) {
465 os << "predecessor: " << block->GetBlockId() << std::endl;
466 }
467 for (uint32_t idx : blocks_.Indexes()) {
468 os << " in loop: " << idx << std::endl;
469 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100470}
471
David Brazdil8d5b8b22015-03-24 10:51:52 +0000472void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000473 // New constants are inserted before the SuspendCheck at the bottom of the
474 // entry block. Note that this method can be called from the graph builder and
475 // the entry block therefore may not end with SuspendCheck->Goto yet.
476 HInstruction* insert_before = nullptr;
477
478 HInstruction* gota = entry_block_->GetLastInstruction();
479 if (gota != nullptr && gota->IsGoto()) {
480 HInstruction* suspend_check = gota->GetPrevious();
481 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
482 insert_before = suspend_check;
483 } else {
484 insert_before = gota;
485 }
486 }
487
488 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000489 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000490 } else {
491 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000492 }
493}
494
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600495HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100496 // For simplicity, don't bother reviving the cached null constant if it is
497 // not null and not in a block. Otherwise, we need to clear the instruction
498 // id and/or any invariants the graph is assuming when adding new instructions.
499 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600500 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000501 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000502 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000503 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000504 if (kIsDebugBuild) {
505 ScopedObjectAccess soa(Thread::Current());
506 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
507 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000508 return cached_null_constant_;
509}
510
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100511HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100512 // For simplicity, don't bother reviving the cached current method if it is
513 // not null and not in a block. Otherwise, we need to clear the instruction
514 // id and/or any invariants the graph is assuming when adding new instructions.
515 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700516 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600517 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
518 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100519 if (entry_block_->GetFirstInstruction() == nullptr) {
520 entry_block_->AddInstruction(cached_current_method_);
521 } else {
522 entry_block_->InsertInstructionBefore(
523 cached_current_method_, entry_block_->GetFirstInstruction());
524 }
525 }
526 return cached_current_method_;
527}
528
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600529HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000530 switch (type) {
531 case Primitive::Type::kPrimBoolean:
532 DCHECK(IsUint<1>(value));
533 FALLTHROUGH_INTENDED;
534 case Primitive::Type::kPrimByte:
535 case Primitive::Type::kPrimChar:
536 case Primitive::Type::kPrimShort:
537 case Primitive::Type::kPrimInt:
538 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600539 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000540
541 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600542 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000543
544 default:
545 LOG(FATAL) << "Unsupported constant type";
546 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000547 }
David Brazdil46e2a392015-03-16 17:31:52 +0000548}
549
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000550void HGraph::CacheFloatConstant(HFloatConstant* constant) {
551 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
552 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
553 cached_float_constants_.Overwrite(value, constant);
554}
555
556void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
557 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
558 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
559 cached_double_constants_.Overwrite(value, constant);
560}
561
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000562void HLoopInformation::Add(HBasicBlock* block) {
563 blocks_.SetBit(block->GetBlockId());
564}
565
David Brazdil46e2a392015-03-16 17:31:52 +0000566void HLoopInformation::Remove(HBasicBlock* block) {
567 blocks_.ClearBit(block->GetBlockId());
568}
569
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100570void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
571 if (blocks_.IsBitSet(block->GetBlockId())) {
572 return;
573 }
574
575 blocks_.SetBit(block->GetBlockId());
576 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100577 if (block->IsLoopHeader()) {
578 // We're visiting loops in post-order, so inner loops must have been
579 // populated already.
580 DCHECK(block->GetLoopInformation()->IsPopulated());
581 if (block->GetLoopInformation()->IsIrreducible()) {
582 contains_irreducible_loop_ = true;
583 }
584 }
Vladimir Marko60584552015-09-03 13:35:12 +0000585 for (HBasicBlock* predecessor : block->GetPredecessors()) {
586 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100587 }
588}
589
David Brazdilc2e8af92016-04-05 17:15:19 +0100590void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
591 size_t block_id = block->GetBlockId();
592
593 // If `block` is in `finalized`, we know its membership in the loop has been
594 // decided and it does not need to be revisited.
595 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000596 return;
597 }
598
David Brazdilc2e8af92016-04-05 17:15:19 +0100599 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000600 if (block->IsLoopHeader()) {
601 // If we hit a loop header in an irreducible loop, we first check if the
602 // pre header of that loop belongs to the currently analyzed loop. If it does,
603 // then we visit the back edges.
604 // Note that we cannot use GetPreHeader, as the loop may have not been populated
605 // yet.
606 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100607 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000608 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000609 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100610 blocks_.SetBit(block_id);
611 finalized->SetBit(block_id);
612 is_finalized = true;
613
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000614 HLoopInformation* info = block->GetLoopInformation();
615 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100616 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000617 }
618 }
619 } else {
620 // Visit all predecessors. If one predecessor is part of the loop, this
621 // block is also part of this loop.
622 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100623 PopulateIrreducibleRecursive(predecessor, finalized);
624 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000625 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100626 blocks_.SetBit(block_id);
627 finalized->SetBit(block_id);
628 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000629 }
630 }
631 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100632
633 // All predecessors have been recursively visited. Mark finalized if not marked yet.
634 if (!is_finalized) {
635 finalized->SetBit(block_id);
636 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000637}
638
639void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100640 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000641 // Populate this loop: starting with the back edge, recursively add predecessors
642 // that are not already part of that loop. Set the header as part of the loop
643 // to end the recursion.
644 // This is a recursive implementation of the algorithm described in
645 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100646 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000647 blocks_.SetBit(header_->GetBlockId());
648 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100649
David Brazdil3f4a5222016-05-06 12:46:21 +0100650 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100651
652 if (is_irreducible_loop) {
653 ArenaBitVector visited(graph->GetArena(),
654 graph->GetBlocks().size(),
655 /* expandable */ false,
656 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100657 // Stop marking blocks at the loop header.
658 visited.SetBit(header_->GetBlockId());
659
David Brazdilc2e8af92016-04-05 17:15:19 +0100660 for (HBasicBlock* back_edge : GetBackEdges()) {
661 PopulateIrreducibleRecursive(back_edge, &visited);
662 }
663 } else {
664 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000665 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100666 }
David Brazdila4b8c212015-05-07 09:59:30 +0100667 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100668
Vladimir Markofd66c502016-04-18 15:37:01 +0100669 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
670 // When compiling in OSR mode, all loops in the compiled method may be entered
671 // from the interpreter. We treat this OSR entry point just like an extra entry
672 // to an irreducible loop, so we need to mark the method's loops as irreducible.
673 // This does not apply to inlined loops which do not act as OSR entry points.
674 if (suspend_check_ == nullptr) {
675 // Just building the graph in OSR mode, this loop is not inlined. We never build an
676 // inner graph in OSR mode as we can do OSR transition only from the outer method.
677 is_irreducible_loop = true;
678 } else {
679 // Look at the suspend check's environment to determine if the loop was inlined.
680 DCHECK(suspend_check_->HasEnvironment());
681 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
682 is_irreducible_loop = true;
683 }
684 }
685 }
686 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100687 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100688 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100689 graph->SetHasIrreducibleLoops(true);
690 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800691 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +0100692}
693
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100694HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000695 HBasicBlock* block = header_->GetPredecessors()[0];
696 DCHECK(irreducible_ || (block == header_->GetDominator()));
697 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100698}
699
700bool HLoopInformation::Contains(const HBasicBlock& block) const {
701 return blocks_.IsBitSet(block.GetBlockId());
702}
703
704bool HLoopInformation::IsIn(const HLoopInformation& other) const {
705 return other.blocks_.IsBitSet(header_->GetBlockId());
706}
707
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800708bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
709 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700710}
711
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100712size_t HLoopInformation::GetLifetimeEnd() const {
713 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100714 for (HBasicBlock* back_edge : GetBackEdges()) {
715 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100716 }
717 return last_position;
718}
719
David Brazdil3f4a5222016-05-06 12:46:21 +0100720bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
721 for (HBasicBlock* back_edge : GetBackEdges()) {
722 DCHECK(back_edge->GetDominator() != nullptr);
723 if (!header_->Dominates(back_edge)) {
724 return true;
725 }
726 }
727 return false;
728}
729
Anton Shaminf89381f2016-05-16 16:44:13 +0600730bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
731 for (HBasicBlock* back_edge : GetBackEdges()) {
732 if (!block->Dominates(back_edge)) {
733 return false;
734 }
735 }
736 return true;
737}
738
David Sehrc757dec2016-11-04 15:48:34 -0700739
740bool HLoopInformation::HasExitEdge() const {
741 // Determine if this loop has at least one exit edge.
742 HBlocksInLoopReversePostOrderIterator it_loop(*this);
743 for (; !it_loop.Done(); it_loop.Advance()) {
744 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
745 if (!Contains(*successor)) {
746 return true;
747 }
748 }
749 }
750 return false;
751}
752
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100753bool HBasicBlock::Dominates(HBasicBlock* other) const {
754 // Walk up the dominator tree from `other`, to find out if `this`
755 // is an ancestor.
756 HBasicBlock* current = other;
757 while (current != nullptr) {
758 if (current == this) {
759 return true;
760 }
761 current = current->GetDominator();
762 }
763 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100764}
765
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100766static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100767 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100768 for (size_t i = 0; i < inputs.size(); ++i) {
769 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100770 }
771 // Environment should be created later.
772 DCHECK(!instruction->HasEnvironment());
773}
774
Roland Levillainccc07a92014-09-16 14:48:16 +0100775void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
776 HInstruction* replacement) {
777 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400778 if (initial->IsControlFlow()) {
779 // We can only replace a control flow instruction with another control flow instruction.
780 DCHECK(replacement->IsControlFlow());
781 DCHECK_EQ(replacement->GetId(), -1);
782 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
783 DCHECK_EQ(initial->GetBlock(), this);
784 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100785 DCHECK(initial->GetUses().empty());
786 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400787 replacement->SetBlock(this);
788 replacement->SetId(GetGraph()->GetNextInstructionId());
789 instructions_.InsertInstructionBefore(replacement, initial);
790 UpdateInputsUsers(replacement);
791 } else {
792 InsertInstructionBefore(replacement, initial);
793 initial->ReplaceWith(replacement);
794 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100795 RemoveInstruction(initial);
796}
797
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100798static void Add(HInstructionList* instruction_list,
799 HBasicBlock* block,
800 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000801 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000802 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100803 instruction->SetBlock(block);
804 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100805 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100806 instruction_list->AddInstruction(instruction);
807}
808
809void HBasicBlock::AddInstruction(HInstruction* instruction) {
810 Add(&instructions_, this, instruction);
811}
812
813void HBasicBlock::AddPhi(HPhi* phi) {
814 Add(&phis_, this, phi);
815}
816
David Brazdilc3d743f2015-04-22 13:40:50 +0100817void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
818 DCHECK(!cursor->IsPhi());
819 DCHECK(!instruction->IsPhi());
820 DCHECK_EQ(instruction->GetId(), -1);
821 DCHECK_NE(cursor->GetId(), -1);
822 DCHECK_EQ(cursor->GetBlock(), this);
823 DCHECK(!instruction->IsControlFlow());
824 instruction->SetBlock(this);
825 instruction->SetId(GetGraph()->GetNextInstructionId());
826 UpdateInputsUsers(instruction);
827 instructions_.InsertInstructionBefore(instruction, cursor);
828}
829
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100830void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
831 DCHECK(!cursor->IsPhi());
832 DCHECK(!instruction->IsPhi());
833 DCHECK_EQ(instruction->GetId(), -1);
834 DCHECK_NE(cursor->GetId(), -1);
835 DCHECK_EQ(cursor->GetBlock(), this);
836 DCHECK(!instruction->IsControlFlow());
837 DCHECK(!cursor->IsControlFlow());
838 instruction->SetBlock(this);
839 instruction->SetId(GetGraph()->GetNextInstructionId());
840 UpdateInputsUsers(instruction);
841 instructions_.InsertInstructionAfter(instruction, cursor);
842}
843
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100844void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
845 DCHECK_EQ(phi->GetId(), -1);
846 DCHECK_NE(cursor->GetId(), -1);
847 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100848 phi->SetBlock(this);
849 phi->SetId(GetGraph()->GetNextInstructionId());
850 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100851 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100852}
853
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100854static void Remove(HInstructionList* instruction_list,
855 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000856 HInstruction* instruction,
857 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100858 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100859 instruction->SetBlock(nullptr);
860 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000861 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100862 DCHECK(instruction->GetUses().empty());
863 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000864 RemoveAsUser(instruction);
865 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100866}
867
David Brazdil1abb4192015-02-17 18:33:36 +0000868void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100869 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000870 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100871}
872
David Brazdil1abb4192015-02-17 18:33:36 +0000873void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
874 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100875}
876
David Brazdilc7508e92015-04-27 13:28:57 +0100877void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
878 if (instruction->IsPhi()) {
879 RemovePhi(instruction->AsPhi(), ensure_safety);
880 } else {
881 RemoveInstruction(instruction, ensure_safety);
882 }
883}
884
Vladimir Marko71bf8092015-09-15 15:33:14 +0100885void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
886 for (size_t i = 0; i < locals.size(); i++) {
887 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100888 SetRawEnvAt(i, instruction);
889 if (instruction != nullptr) {
890 instruction->AddEnvUseAt(this, i);
891 }
892 }
893}
894
David Brazdiled596192015-01-23 10:39:45 +0000895void HEnvironment::CopyFrom(HEnvironment* env) {
896 for (size_t i = 0; i < env->Size(); i++) {
897 HInstruction* instruction = env->GetInstructionAt(i);
898 SetRawEnvAt(i, instruction);
899 if (instruction != nullptr) {
900 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100901 }
David Brazdiled596192015-01-23 10:39:45 +0000902 }
903}
904
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700905void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
906 HBasicBlock* loop_header) {
907 DCHECK(loop_header->IsLoopHeader());
908 for (size_t i = 0; i < env->Size(); i++) {
909 HInstruction* instruction = env->GetInstructionAt(i);
910 SetRawEnvAt(i, instruction);
911 if (instruction == nullptr) {
912 continue;
913 }
914 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
915 // At the end of the loop pre-header, the corresponding value for instruction
916 // is the first input of the phi.
917 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700918 SetRawEnvAt(i, initial);
919 initial->AddEnvUseAt(this, i);
920 } else {
921 instruction->AddEnvUseAt(this, i);
922 }
923 }
924}
925
David Brazdil1abb4192015-02-17 18:33:36 +0000926void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100927 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
928 HInstruction* user = env_use.GetInstruction();
929 auto before_env_use_node = env_use.GetBeforeUseNode();
930 user->env_uses_.erase_after(before_env_use_node);
931 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100932}
933
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000934HInstruction::InstructionKind HInstruction::GetKind() const {
935 return GetKindInternal();
936}
937
Calin Juravle77520bc2015-01-12 18:45:46 +0000938HInstruction* HInstruction::GetNextDisregardingMoves() const {
939 HInstruction* next = GetNext();
940 while (next != nullptr && next->IsParallelMove()) {
941 next = next->GetNext();
942 }
943 return next;
944}
945
946HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
947 HInstruction* previous = GetPrevious();
948 while (previous != nullptr && previous->IsParallelMove()) {
949 previous = previous->GetPrevious();
950 }
951 return previous;
952}
953
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100954void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000955 if (first_instruction_ == nullptr) {
956 DCHECK(last_instruction_ == nullptr);
957 first_instruction_ = last_instruction_ = instruction;
958 } else {
959 last_instruction_->next_ = instruction;
960 instruction->previous_ = last_instruction_;
961 last_instruction_ = instruction;
962 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000963}
964
David Brazdilc3d743f2015-04-22 13:40:50 +0100965void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
966 DCHECK(Contains(cursor));
967 if (cursor == first_instruction_) {
968 cursor->previous_ = instruction;
969 instruction->next_ = cursor;
970 first_instruction_ = instruction;
971 } else {
972 instruction->previous_ = cursor->previous_;
973 instruction->next_ = cursor;
974 cursor->previous_ = instruction;
975 instruction->previous_->next_ = instruction;
976 }
977}
978
979void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
980 DCHECK(Contains(cursor));
981 if (cursor == last_instruction_) {
982 cursor->next_ = instruction;
983 instruction->previous_ = cursor;
984 last_instruction_ = instruction;
985 } else {
986 instruction->next_ = cursor->next_;
987 instruction->previous_ = cursor;
988 cursor->next_ = instruction;
989 instruction->next_->previous_ = instruction;
990 }
991}
992
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100993void HInstructionList::RemoveInstruction(HInstruction* instruction) {
994 if (instruction->previous_ != nullptr) {
995 instruction->previous_->next_ = instruction->next_;
996 }
997 if (instruction->next_ != nullptr) {
998 instruction->next_->previous_ = instruction->previous_;
999 }
1000 if (instruction == first_instruction_) {
1001 first_instruction_ = instruction->next_;
1002 }
1003 if (instruction == last_instruction_) {
1004 last_instruction_ = instruction->previous_;
1005 }
1006}
1007
Roland Levillain6b469232014-09-25 10:10:38 +01001008bool HInstructionList::Contains(HInstruction* instruction) const {
1009 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1010 if (it.Current() == instruction) {
1011 return true;
1012 }
1013 }
1014 return false;
1015}
1016
Roland Levillainccc07a92014-09-16 14:48:16 +01001017bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1018 const HInstruction* instruction2) const {
1019 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1020 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1021 if (it.Current() == instruction1) {
1022 return true;
1023 }
1024 if (it.Current() == instruction2) {
1025 return false;
1026 }
1027 }
1028 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1029 return true;
1030}
1031
Roland Levillain6c82d402014-10-13 16:10:27 +01001032bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1033 if (other_instruction == this) {
1034 // An instruction does not strictly dominate itself.
1035 return false;
1036 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001037 HBasicBlock* block = GetBlock();
1038 HBasicBlock* other_block = other_instruction->GetBlock();
1039 if (block != other_block) {
1040 return GetBlock()->Dominates(other_instruction->GetBlock());
1041 } else {
1042 // If both instructions are in the same block, ensure this
1043 // instruction comes before `other_instruction`.
1044 if (IsPhi()) {
1045 if (!other_instruction->IsPhi()) {
1046 // Phis appear before non phi-instructions so this instruction
1047 // dominates `other_instruction`.
1048 return true;
1049 } else {
1050 // There is no order among phis.
1051 LOG(FATAL) << "There is no dominance between phis of a same block.";
1052 return false;
1053 }
1054 } else {
1055 // `this` is not a phi.
1056 if (other_instruction->IsPhi()) {
1057 // Phis appear before non phi-instructions so this instruction
1058 // does not dominate `other_instruction`.
1059 return false;
1060 } else {
1061 // Check whether this instruction comes before
1062 // `other_instruction` in the instruction list.
1063 return block->GetInstructions().FoundBefore(this, other_instruction);
1064 }
1065 }
1066 }
1067}
1068
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001069void HInstruction::RemoveEnvironment() {
1070 RemoveEnvironmentUses(this);
1071 environment_ = nullptr;
1072}
1073
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001074void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001075 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001076 // Note: fixup_end remains valid across splice_after().
1077 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1078 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1079 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001080
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001081 // Note: env_fixup_end remains valid across splice_after().
1082 auto env_fixup_end =
1083 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1084 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1085 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001086
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001087 DCHECK(uses_.empty());
1088 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001089}
1090
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001091void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1092 const HUseList<HInstruction*>& uses = GetUses();
1093 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1094 HInstruction* user = it->GetUser();
1095 size_t index = it->GetIndex();
1096 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1097 ++it;
1098 if (dominator->StrictlyDominates(user)) {
1099 user->ReplaceInput(replacement, index);
1100 }
1101 }
1102}
1103
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001104void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001105 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001106 if (input_use.GetInstruction() == replacement) {
1107 // Nothing to do.
1108 return;
1109 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001110 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001111 // Note: fixup_end remains valid across splice_after().
1112 auto fixup_end =
1113 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1114 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1115 input_use.GetInstruction()->uses_,
1116 before_use_node);
1117 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1118 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001119}
1120
Nicolas Geoffray39468442014-09-02 15:17:15 +01001121size_t HInstruction::EnvironmentSize() const {
1122 return HasEnvironment() ? environment_->Size() : 0;
1123}
1124
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001125void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001126 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001127 inputs_.push_back(HUserRecord<HInstruction*>(input));
1128 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001129}
1130
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001131void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1132 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1133 input->AddUseAt(this, index);
1134 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1135 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1136 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1137 inputs_[i].GetUseNode()->SetIndex(i);
1138 }
1139}
1140
1141void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001142 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001143 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001144 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1145 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1146 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1147 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001148 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001149}
1150
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001151#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001152void H##name::Accept(HGraphVisitor* visitor) { \
1153 visitor->Visit##name(this); \
1154}
1155
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001156FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001157
1158#undef DEFINE_ACCEPT
1159
1160void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001161 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1162 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001163 if (block != nullptr) {
1164 VisitBasicBlock(block);
1165 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001166 }
1167}
1168
Roland Levillain633021e2014-10-01 14:12:25 +01001169void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001170 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1171 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001172 }
1173}
1174
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001175void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001176 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001177 it.Current()->Accept(this);
1178 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001179 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001180 it.Current()->Accept(this);
1181 }
1182}
1183
Mark Mendelle82549b2015-05-06 10:55:34 -04001184HConstant* HTypeConversion::TryStaticEvaluation() const {
1185 HGraph* graph = GetBlock()->GetGraph();
1186 if (GetInput()->IsIntConstant()) {
1187 int32_t value = GetInput()->AsIntConstant()->GetValue();
1188 switch (GetResultType()) {
1189 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001190 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001191 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001192 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001193 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001194 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001195 default:
1196 return nullptr;
1197 }
1198 } else if (GetInput()->IsLongConstant()) {
1199 int64_t value = GetInput()->AsLongConstant()->GetValue();
1200 switch (GetResultType()) {
1201 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001202 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001203 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001204 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001205 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001206 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001207 default:
1208 return nullptr;
1209 }
1210 } else if (GetInput()->IsFloatConstant()) {
1211 float value = GetInput()->AsFloatConstant()->GetValue();
1212 switch (GetResultType()) {
1213 case Primitive::kPrimInt:
1214 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001215 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001216 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001217 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001218 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001219 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1220 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001221 case Primitive::kPrimLong:
1222 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001223 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001224 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001225 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001226 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001227 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1228 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001229 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001230 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001231 default:
1232 return nullptr;
1233 }
1234 } else if (GetInput()->IsDoubleConstant()) {
1235 double value = GetInput()->AsDoubleConstant()->GetValue();
1236 switch (GetResultType()) {
1237 case Primitive::kPrimInt:
1238 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001239 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001240 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001241 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001242 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001243 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1244 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001245 case Primitive::kPrimLong:
1246 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001247 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001248 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001249 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001250 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001251 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1252 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001253 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001254 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001255 default:
1256 return nullptr;
1257 }
1258 }
1259 return nullptr;
1260}
1261
Roland Levillain9240d6a2014-10-20 16:47:04 +01001262HConstant* HUnaryOperation::TryStaticEvaluation() const {
1263 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001264 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001265 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001266 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001267 } else if (kEnableFloatingPointStaticEvaluation) {
1268 if (GetInput()->IsFloatConstant()) {
1269 return Evaluate(GetInput()->AsFloatConstant());
1270 } else if (GetInput()->IsDoubleConstant()) {
1271 return Evaluate(GetInput()->AsDoubleConstant());
1272 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001273 }
1274 return nullptr;
1275}
1276
1277HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001278 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1279 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001280 } else if (GetLeft()->IsLongConstant()) {
1281 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001282 // The binop(long, int) case is only valid for shifts and rotations.
1283 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001284 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1285 } else if (GetRight()->IsLongConstant()) {
1286 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001287 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001288 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001289 // The binop(null, null) case is only valid for equal and not-equal conditions.
1290 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001291 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001292 } else if (kEnableFloatingPointStaticEvaluation) {
1293 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1294 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1295 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1296 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1297 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001298 }
1299 return nullptr;
1300}
Dave Allison20dfc792014-06-16 20:44:29 -07001301
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001302HConstant* HBinaryOperation::GetConstantRight() const {
1303 if (GetRight()->IsConstant()) {
1304 return GetRight()->AsConstant();
1305 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1306 return GetLeft()->AsConstant();
1307 } else {
1308 return nullptr;
1309 }
1310}
1311
1312// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001313// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001314HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1315 HInstruction* most_constant_right = GetConstantRight();
1316 if (most_constant_right == nullptr) {
1317 return nullptr;
1318 } else if (most_constant_right == GetLeft()) {
1319 return GetRight();
1320 } else {
1321 return GetLeft();
1322 }
1323}
1324
Roland Levillain31dd3d62016-02-16 12:21:02 +00001325std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1326 switch (rhs) {
1327 case ComparisonBias::kNoBias:
1328 return os << "no_bias";
1329 case ComparisonBias::kGtBias:
1330 return os << "gt_bias";
1331 case ComparisonBias::kLtBias:
1332 return os << "lt_bias";
1333 default:
1334 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1335 UNREACHABLE();
1336 }
1337}
1338
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001339std::ostream& operator<<(std::ostream& os, const HDeoptimize::Kind& rhs) {
1340 switch (rhs) {
1341 case HDeoptimize::Kind::kBCE:
1342 return os << "bce";
1343 case HDeoptimize::Kind::kInline:
1344 return os << "inline";
1345 default:
1346 LOG(FATAL) << "Unknown Deoptimization kind: " << static_cast<int>(rhs);
1347 UNREACHABLE();
1348 }
1349}
1350
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001351bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1352 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001353}
1354
Vladimir Marko372f10e2016-05-17 16:30:10 +01001355bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001356 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001357 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001358 if (!InstructionDataEquals(other)) return false;
1359 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001360 HConstInputsRef inputs = GetInputs();
1361 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001362 if (inputs.size() != other_inputs.size()) return false;
1363 for (size_t i = 0; i != inputs.size(); ++i) {
1364 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001365 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001366
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001367 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001368 return true;
1369}
1370
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001371std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1372#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1373 switch (rhs) {
1374 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1375 default:
1376 os << "Unknown instruction kind " << static_cast<int>(rhs);
1377 break;
1378 }
1379#undef DECLARE_CASE
1380 return os;
1381}
1382
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001383void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1384 if (do_checks) {
1385 DCHECK(!IsPhi());
1386 DCHECK(!IsControlFlow());
1387 DCHECK(CanBeMoved() ||
1388 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1389 IsShouldDeoptimizeFlag());
1390 DCHECK(!cursor->IsPhi());
1391 }
David Brazdild6c205e2016-06-07 14:20:52 +01001392
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001393 next_->previous_ = previous_;
1394 if (previous_ != nullptr) {
1395 previous_->next_ = next_;
1396 }
1397 if (block_->instructions_.first_instruction_ == this) {
1398 block_->instructions_.first_instruction_ = next_;
1399 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001400 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001401
1402 previous_ = cursor->previous_;
1403 if (previous_ != nullptr) {
1404 previous_->next_ = this;
1405 }
1406 next_ = cursor;
1407 cursor->previous_ = this;
1408 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001409
1410 if (block_->instructions_.first_instruction_ == cursor) {
1411 block_->instructions_.first_instruction_ = this;
1412 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001413}
1414
Vladimir Markofb337ea2015-11-25 15:25:10 +00001415void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1416 DCHECK(!CanThrow());
1417 DCHECK(!HasSideEffects());
1418 DCHECK(!HasEnvironmentUses());
1419 DCHECK(HasNonEnvironmentUses());
1420 DCHECK(!IsPhi()); // Makes no sense for Phi.
1421 DCHECK_EQ(InputCount(), 0u);
1422
1423 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001424 auto uses_it = GetUses().begin();
1425 auto uses_end = GetUses().end();
1426 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1427 ++uses_it;
1428 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1429 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001430 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001431 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001432 // This instruction has uses in two or more blocks. Find the common dominator.
1433 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001434 for (; uses_it != uses_end; ++uses_it) {
1435 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001436 }
1437 target_block = finder.Get();
1438 DCHECK(target_block != nullptr);
1439 }
1440 // Move to the first dominator not in a loop.
1441 while (target_block->IsInLoop()) {
1442 target_block = target_block->GetDominator();
1443 DCHECK(target_block != nullptr);
1444 }
1445
1446 // Find insertion position.
1447 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001448 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1449 if (use.GetUser()->GetBlock() == target_block &&
1450 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1451 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001452 }
1453 }
1454 if (insert_pos == nullptr) {
1455 // No user in `target_block`, insert before the control flow instruction.
1456 insert_pos = target_block->GetLastInstruction();
1457 DCHECK(insert_pos->IsControlFlow());
1458 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1459 if (insert_pos->IsIf()) {
1460 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1461 if (if_input == insert_pos->GetPrevious()) {
1462 insert_pos = if_input;
1463 }
1464 }
1465 }
1466 MoveBefore(insert_pos);
1467}
1468
David Brazdilfc6a86a2015-06-26 10:33:45 +00001469HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001470 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001471 DCHECK_EQ(cursor->GetBlock(), this);
1472
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001473 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1474 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001475 new_block->instructions_.first_instruction_ = cursor;
1476 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1477 instructions_.last_instruction_ = cursor->previous_;
1478 if (cursor->previous_ == nullptr) {
1479 instructions_.first_instruction_ = nullptr;
1480 } else {
1481 cursor->previous_->next_ = nullptr;
1482 cursor->previous_ = nullptr;
1483 }
1484
1485 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001486 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001487
Vladimir Marko60584552015-09-03 13:35:12 +00001488 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001489 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001490 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001491 new_block->successors_.swap(successors_);
1492 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001493 AddSuccessor(new_block);
1494
David Brazdil56e1acc2015-06-30 15:41:36 +01001495 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001496 return new_block;
1497}
1498
David Brazdild7558da2015-09-22 13:04:14 +01001499HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001500 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001501 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1502
1503 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1504
1505 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001506 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1507 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001508 new_block->predecessors_.swap(predecessors_);
1509 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001510 AddPredecessor(new_block);
1511
1512 GetGraph()->AddBlock(new_block);
1513 return new_block;
1514}
1515
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001516HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1517 DCHECK_EQ(cursor->GetBlock(), this);
1518
1519 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1520 cursor->GetDexPc());
1521 new_block->instructions_.first_instruction_ = cursor;
1522 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1523 instructions_.last_instruction_ = cursor->previous_;
1524 if (cursor->previous_ == nullptr) {
1525 instructions_.first_instruction_ = nullptr;
1526 } else {
1527 cursor->previous_->next_ = nullptr;
1528 cursor->previous_ = nullptr;
1529 }
1530
1531 new_block->instructions_.SetBlockOfInstructions(new_block);
1532
1533 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001534 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1535 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001536 new_block->successors_.swap(successors_);
1537 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001538
1539 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1540 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001541 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001542 new_block->dominated_blocks_.swap(dominated_blocks_);
1543 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001544 return new_block;
1545}
1546
1547HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001548 DCHECK(!cursor->IsControlFlow());
1549 DCHECK_NE(instructions_.last_instruction_, cursor);
1550 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001551
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001552 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1553 new_block->instructions_.first_instruction_ = cursor->GetNext();
1554 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1555 cursor->next_->previous_ = nullptr;
1556 cursor->next_ = nullptr;
1557 instructions_.last_instruction_ = cursor;
1558
1559 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001560 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001561 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001562 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001563 new_block->successors_.swap(successors_);
1564 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001565
Vladimir Marko60584552015-09-03 13:35:12 +00001566 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001567 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001568 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001569 new_block->dominated_blocks_.swap(dominated_blocks_);
1570 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001571 return new_block;
1572}
1573
David Brazdilec16f792015-08-19 15:04:01 +01001574const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001575 if (EndsWithTryBoundary()) {
1576 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1577 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001578 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001579 return try_boundary;
1580 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001581 DCHECK(IsTryBlock());
1582 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001583 return nullptr;
1584 }
David Brazdilec16f792015-08-19 15:04:01 +01001585 } else if (IsTryBlock()) {
1586 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001587 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001588 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001589 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001590}
1591
David Brazdild7558da2015-09-22 13:04:14 +01001592bool HBasicBlock::HasThrowingInstructions() const {
1593 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1594 if (it.Current()->CanThrow()) {
1595 return true;
1596 }
1597 }
1598 return false;
1599}
1600
David Brazdilfc6a86a2015-06-26 10:33:45 +00001601static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1602 return block.GetPhis().IsEmpty()
1603 && !block.GetInstructions().IsEmpty()
1604 && block.GetFirstInstruction() == block.GetLastInstruction();
1605}
1606
David Brazdil46e2a392015-03-16 17:31:52 +00001607bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001608 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1609}
1610
1611bool HBasicBlock::IsSingleTryBoundary() const {
1612 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001613}
1614
David Brazdil8d5b8b22015-03-24 10:51:52 +00001615bool HBasicBlock::EndsWithControlFlowInstruction() const {
1616 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1617}
1618
David Brazdilb2bd1c52015-03-25 11:17:37 +00001619bool HBasicBlock::EndsWithIf() const {
1620 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1621}
1622
David Brazdilffee3d32015-07-06 11:48:53 +01001623bool HBasicBlock::EndsWithTryBoundary() const {
1624 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1625}
1626
David Brazdilb2bd1c52015-03-25 11:17:37 +00001627bool HBasicBlock::HasSinglePhi() const {
1628 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1629}
1630
David Brazdild26a4112015-11-10 11:07:31 +00001631ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1632 if (EndsWithTryBoundary()) {
1633 // The normal-flow successor of HTryBoundary is always stored at index zero.
1634 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1635 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1636 } else {
1637 // All successors of blocks not ending with TryBoundary are normal.
1638 return ArrayRef<HBasicBlock* const>(successors_);
1639 }
1640}
1641
1642ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1643 if (EndsWithTryBoundary()) {
1644 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1645 } else {
1646 // Blocks not ending with TryBoundary do not have exceptional successors.
1647 return ArrayRef<HBasicBlock* const>();
1648 }
1649}
1650
David Brazdilffee3d32015-07-06 11:48:53 +01001651bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001652 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1653 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1654
1655 size_t length = handlers1.size();
1656 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001657 return false;
1658 }
1659
David Brazdilb618ade2015-07-29 10:31:29 +01001660 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001661 for (size_t i = 0; i < length; ++i) {
1662 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001663 return false;
1664 }
1665 }
1666 return true;
1667}
1668
David Brazdil2d7352b2015-04-20 14:52:42 +01001669size_t HInstructionList::CountSize() const {
1670 size_t size = 0;
1671 HInstruction* current = first_instruction_;
1672 for (; current != nullptr; current = current->GetNext()) {
1673 size++;
1674 }
1675 return size;
1676}
1677
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001678void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1679 for (HInstruction* current = first_instruction_;
1680 current != nullptr;
1681 current = current->GetNext()) {
1682 current->SetBlock(block);
1683 }
1684}
1685
1686void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1687 DCHECK(Contains(cursor));
1688 if (!instruction_list.IsEmpty()) {
1689 if (cursor == last_instruction_) {
1690 last_instruction_ = instruction_list.last_instruction_;
1691 } else {
1692 cursor->next_->previous_ = instruction_list.last_instruction_;
1693 }
1694 instruction_list.last_instruction_->next_ = cursor->next_;
1695 cursor->next_ = instruction_list.first_instruction_;
1696 instruction_list.first_instruction_->previous_ = cursor;
1697 }
1698}
1699
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001700void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1701 DCHECK(Contains(cursor));
1702 if (!instruction_list.IsEmpty()) {
1703 if (cursor == first_instruction_) {
1704 first_instruction_ = instruction_list.first_instruction_;
1705 } else {
1706 cursor->previous_->next_ = instruction_list.first_instruction_;
1707 }
1708 instruction_list.last_instruction_->next_ = cursor;
1709 instruction_list.first_instruction_->previous_ = cursor->previous_;
1710 cursor->previous_ = instruction_list.last_instruction_;
1711 }
1712}
1713
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001714void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001715 if (IsEmpty()) {
1716 first_instruction_ = instruction_list.first_instruction_;
1717 last_instruction_ = instruction_list.last_instruction_;
1718 } else {
1719 AddAfter(last_instruction_, instruction_list);
1720 }
1721}
1722
David Brazdil04ff4e82015-12-10 13:54:52 +00001723// Should be called on instructions in a dead block in post order. This method
1724// assumes `insn` has been removed from all users with the exception of catch
1725// phis because of missing exceptional edges in the graph. It removes the
1726// instruction from catch phi uses, together with inputs of other catch phis in
1727// the catch block at the same index, as these must be dead too.
1728static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1729 DCHECK(!insn->HasEnvironmentUses());
1730 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001731 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1732 size_t use_index = use.GetIndex();
1733 HBasicBlock* user_block = use.GetUser()->GetBlock();
1734 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001735 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1736 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1737 }
1738 }
1739}
1740
David Brazdil2d7352b2015-04-20 14:52:42 +01001741void HBasicBlock::DisconnectAndDelete() {
1742 // Dominators must be removed after all the blocks they dominate. This way
1743 // a loop header is removed last, a requirement for correct loop information
1744 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001745 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001746
David Brazdil9eeebf62016-03-24 11:18:15 +00001747 // The following steps gradually remove the block from all its dependants in
1748 // post order (b/27683071).
1749
1750 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1751 // We need to do this before step (4) which destroys the predecessor list.
1752 HBasicBlock* loop_update_start = this;
1753 if (IsLoopHeader()) {
1754 HLoopInformation* loop_info = GetLoopInformation();
1755 // All other blocks in this loop should have been removed because the header
1756 // was their dominator.
1757 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1758 DCHECK(!loop_info->IsIrreducible());
1759 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1760 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1761 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001762 }
1763
David Brazdil9eeebf62016-03-24 11:18:15 +00001764 // (2) Disconnect the block from its successors and update their phis.
1765 for (HBasicBlock* successor : successors_) {
1766 // Delete this block from the list of predecessors.
1767 size_t this_index = successor->GetPredecessorIndexOf(this);
1768 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1769
1770 // Check that `successor` has other predecessors, otherwise `this` is the
1771 // dominator of `successor` which violates the order DCHECKed at the top.
1772 DCHECK(!successor->predecessors_.empty());
1773
1774 // Remove this block's entries in the successor's phis. Skip exceptional
1775 // successors because catch phi inputs do not correspond to predecessor
1776 // blocks but throwing instructions. The inputs of the catch phis will be
1777 // updated in step (3).
1778 if (!successor->IsCatchBlock()) {
1779 if (successor->predecessors_.size() == 1u) {
1780 // The successor has just one predecessor left. Replace phis with the only
1781 // remaining input.
1782 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1783 HPhi* phi = phi_it.Current()->AsPhi();
1784 phi->ReplaceWith(phi->InputAt(1 - this_index));
1785 successor->RemovePhi(phi);
1786 }
1787 } else {
1788 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1789 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1790 }
1791 }
1792 }
1793 }
1794 successors_.clear();
1795
1796 // (3) Remove instructions and phis. Instructions should have no remaining uses
1797 // except in catch phis. If an instruction is used by a catch phi at `index`,
1798 // remove `index`-th input of all phis in the catch block since they are
1799 // guaranteed dead. Note that we may miss dead inputs this way but the
1800 // graph will always remain consistent.
1801 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1802 HInstruction* insn = it.Current();
1803 RemoveUsesOfDeadInstruction(insn);
1804 RemoveInstruction(insn);
1805 }
1806 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1807 HPhi* insn = it.Current()->AsPhi();
1808 RemoveUsesOfDeadInstruction(insn);
1809 RemovePhi(insn);
1810 }
1811
1812 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001813 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001814 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001815 // We should not see any back edges as they would have been removed by step (3).
1816 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1817
David Brazdil2d7352b2015-04-20 14:52:42 +01001818 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001819 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1820 // This block is the only normal-flow successor of the TryBoundary which
1821 // makes `predecessor` dead. Since DCE removes blocks in post order,
1822 // exception handlers of this TryBoundary were already visited and any
1823 // remaining handlers therefore must be live. We remove `predecessor` from
1824 // their list of predecessors.
1825 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1826 while (predecessor->GetSuccessors().size() > 1) {
1827 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1828 DCHECK(handler->IsCatchBlock());
1829 predecessor->RemoveSuccessor(handler);
1830 handler->RemovePredecessor(predecessor);
1831 }
1832 }
1833
David Brazdil2d7352b2015-04-20 14:52:42 +01001834 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001835 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1836 if (num_pred_successors == 1u) {
1837 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001838 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1839 // successor. Replace those with a HGoto.
1840 DCHECK(last_instruction->IsIf() ||
1841 last_instruction->IsPackedSwitch() ||
1842 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001843 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001844 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001845 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001846 // The predecessor has no remaining successors and therefore must be dead.
1847 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001848 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001849 predecessor->RemoveInstruction(last_instruction);
1850 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001851 // There are multiple successors left. The removed block might be a successor
1852 // of a PackedSwitch which will be completely removed (perhaps replaced with
1853 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1854 // case, leave `last_instruction` as is for now.
1855 DCHECK(last_instruction->IsPackedSwitch() ||
1856 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001857 }
David Brazdil46e2a392015-03-16 17:31:52 +00001858 }
Vladimir Marko60584552015-09-03 13:35:12 +00001859 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001860
David Brazdil9eeebf62016-03-24 11:18:15 +00001861 // (5) Remove the block from all loops it is included in. Skip the inner-most
1862 // loop if this is the loop header (see definition of `loop_update_start`)
1863 // because the loop header's predecessor list has been destroyed in step (4).
1864 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1865 HLoopInformation* loop_info = it.Current();
1866 loop_info->Remove(this);
1867 if (loop_info->IsBackEdge(*this)) {
1868 // If this was the last back edge of the loop, we deliberately leave the
1869 // loop in an inconsistent state and will fail GraphChecker unless the
1870 // entire loop is removed during the pass.
1871 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001872 }
1873 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001874
David Brazdil9eeebf62016-03-24 11:18:15 +00001875 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01001876 dominator_->RemoveDominatedBlock(this);
1877 SetDominator(nullptr);
1878
David Brazdil9eeebf62016-03-24 11:18:15 +00001879 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001880 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001881 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001882}
1883
Aart Bik6b69e0a2017-01-11 10:20:43 -08001884void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
1885 DCHECK(EndsWithControlFlowInstruction());
1886 RemoveInstruction(GetLastInstruction());
1887 instructions_.Add(other->GetInstructions());
1888 other->instructions_.SetBlockOfInstructions(this);
1889 other->instructions_.Clear();
1890}
1891
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001892void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001893 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001894 DCHECK(ContainsElement(dominated_blocks_, other));
1895 DCHECK_EQ(GetSingleSuccessor(), other);
1896 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001897 DCHECK(other->GetPhis().IsEmpty());
1898
David Brazdil2d7352b2015-04-20 14:52:42 +01001899 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08001900 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001901
David Brazdil2d7352b2015-04-20 14:52:42 +01001902 // Remove `other` from the loops it is included in.
1903 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
1904 HLoopInformation* loop_info = it.Current();
1905 loop_info->Remove(other);
1906 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001907 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001908 }
1909 }
1910
1911 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001912 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00001913 for (HBasicBlock* successor : other->GetSuccessors()) {
1914 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001915 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001916 successors_.swap(other->successors_);
1917 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001918
David Brazdil2d7352b2015-04-20 14:52:42 +01001919 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001920 RemoveDominatedBlock(other);
1921 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001922 dominated->SetDominator(this);
1923 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001924 dominated_blocks_.insert(
1925 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00001926 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001927 other->dominator_ = nullptr;
1928
1929 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00001930 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001931
1932 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001933 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01001934 other->SetGraph(nullptr);
1935}
1936
1937void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
1938 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00001939 DCHECK(GetDominatedBlocks().empty());
1940 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001941 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00001942 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01001943 DCHECK(other->GetPhis().IsEmpty());
1944 DCHECK(!other->IsInLoop());
1945
1946 // Move instructions from `other` to `this`.
1947 instructions_.Add(other->GetInstructions());
1948 other->instructions_.SetBlockOfInstructions(this);
1949
1950 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00001951 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00001952 for (HBasicBlock* successor : other->GetSuccessors()) {
1953 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01001954 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001955 successors_.swap(other->successors_);
1956 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001957
1958 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00001959 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001960 dominated->SetDominator(this);
1961 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001962 dominated_blocks_.insert(
1963 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00001964 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001965 other->dominator_ = nullptr;
1966 other->graph_ = nullptr;
1967}
1968
1969void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00001970 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001971 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001972 predecessor->ReplaceSuccessor(this, other);
1973 }
Vladimir Marko60584552015-09-03 13:35:12 +00001974 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01001975 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001976 successor->ReplacePredecessor(this, other);
1977 }
Vladimir Marko60584552015-09-03 13:35:12 +00001978 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1979 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001980 }
1981 GetDominator()->ReplaceDominatedBlock(this, other);
1982 other->SetDominator(GetDominator());
1983 dominator_ = nullptr;
1984 graph_ = nullptr;
1985}
1986
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001987void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001988 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00001989 DCHECK(block->GetSuccessors().empty());
1990 DCHECK(block->GetPredecessors().empty());
1991 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001992 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001993 DCHECK(block->GetInstructions().IsEmpty());
1994 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01001995
David Brazdilc7af85d2015-05-26 12:05:55 +01001996 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06001997 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01001998 }
1999
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002000 RemoveElement(reverse_post_order_, block);
2001 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002002 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002003}
2004
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002005void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2006 HBasicBlock* reference,
2007 bool replace_if_back_edge) {
2008 if (block->IsLoopHeader()) {
2009 // Clear the information of which blocks are contained in that loop. Since the
2010 // information is stored as a bit vector based on block ids, we have to update
2011 // it, as those block ids were specific to the callee graph and we are now adding
2012 // these blocks to the caller graph.
2013 block->GetLoopInformation()->ClearAllBlocks();
2014 }
2015
2016 // If not already in a loop, update the loop information.
2017 if (!block->IsInLoop()) {
2018 block->SetLoopInformation(reference->GetLoopInformation());
2019 }
2020
2021 // If the block is in a loop, update all its outward loops.
2022 HLoopInformation* loop_info = block->GetLoopInformation();
2023 if (loop_info != nullptr) {
2024 for (HLoopInformationOutwardIterator loop_it(*block);
2025 !loop_it.Done();
2026 loop_it.Advance()) {
2027 loop_it.Current()->Add(block);
2028 }
2029 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2030 loop_info->ReplaceBackEdge(reference, block);
2031 }
2032 }
2033
2034 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2035 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2036 ? reference->GetTryCatchInformation()
2037 : nullptr;
2038 block->SetTryCatchInformation(try_catch_info);
2039}
2040
Calin Juravle2e768302015-07-28 14:41:11 +00002041HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002042 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002043 // Update the environments in this graph to have the invoke's environment
2044 // as parent.
2045 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002046 // Skip the entry block, we do not need to update the entry's suspend check.
2047 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002048 for (HInstructionIterator instr_it(block->GetInstructions());
2049 !instr_it.Done();
2050 instr_it.Advance()) {
2051 HInstruction* current = instr_it.Current();
2052 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002053 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002054 current->GetEnvironment()->SetAndCopyParentChain(
2055 outer_graph->GetArena(), invoke->GetEnvironment());
2056 }
2057 }
2058 }
2059 }
2060 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002061
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002062 if (HasBoundsChecks()) {
2063 outer_graph->SetHasBoundsChecks(true);
2064 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002065 if (HasLoops()) {
2066 outer_graph->SetHasLoops(true);
2067 }
2068 if (HasIrreducibleLoops()) {
2069 outer_graph->SetHasIrreducibleLoops(true);
2070 }
2071 if (HasTryCatch()) {
2072 outer_graph->SetHasTryCatch(true);
2073 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002074
Calin Juravle2e768302015-07-28 14:41:11 +00002075 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002076 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002077 // Inliner already made sure we don't inline methods that always throw.
2078 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002079 // Simple case of an entry block, a body block, and an exit block.
2080 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002081 HBasicBlock* body = GetBlocks()[1];
2082 DCHECK(GetBlocks()[0]->IsEntryBlock());
2083 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002084 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002085 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002086 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002087
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002088 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2089 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002090 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002091
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002092 // Replace the invoke with the return value of the inlined graph.
2093 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002094 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002095 } else {
2096 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002097 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002098
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002099 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002100 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002101 // Need to inline multiple blocks. We split `invoke`'s block
2102 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002103 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002104 // with the second half.
2105 ArenaAllocator* allocator = outer_graph->GetArena();
2106 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002107 // Note that we split before the invoke only to simplify polymorphic inlining.
2108 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002109
Vladimir Markoec7802a2015-10-01 20:57:57 +01002110 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002111 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002112 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002113 exit_block_->ReplaceWith(to);
2114
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002115 // Update the meta information surrounding blocks:
2116 // (1) the graph they are now in,
2117 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002118 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002119 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002120 // Note that we do not need to update catch phi inputs because they
2121 // correspond to the register file of the outer method which the inlinee
2122 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002123
2124 // We don't add the entry block, the exit block, and the first block, which
2125 // has been merged with `at`.
2126 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2127
2128 // We add the `to` block.
2129 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002130 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002131 + kNumberOfNewBlocksInCaller;
2132
2133 // Find the location of `at` in the outer graph's reverse post order. The new
2134 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002135 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002136 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2137
David Brazdil95177982015-10-30 12:56:58 -05002138 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2139 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002140 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002141 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002142 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002143 DCHECK(current->GetGraph() == this);
2144 current->SetGraph(outer_graph);
2145 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002146 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002147 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002148 }
2149 }
2150
David Brazdil95177982015-10-30 12:56:58 -05002151 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002152 to->SetGraph(outer_graph);
2153 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002154 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002155 // Only `to` can become a back edge, as the inlined blocks
2156 // are predecessors of `to`.
2157 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002158
David Brazdil3f523062016-02-29 16:53:33 +00002159 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002160 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2161 // to now get the outer graph exit block as successor. Note that the inliner
2162 // currently doesn't support inlining methods with try/catch.
2163 HPhi* return_value_phi = nullptr;
2164 bool rerun_dominance = false;
2165 bool rerun_loop_analysis = false;
2166 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2167 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002168 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002169 if (last->IsThrow()) {
2170 DCHECK(!at->IsTryBlock());
2171 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2172 --pred;
2173 // We need to re-run dominance information, as the exit block now has
2174 // a new dominator.
2175 rerun_dominance = true;
2176 if (predecessor->GetLoopInformation() != nullptr) {
2177 // The exit block and blocks post dominated by the exit block do not belong
2178 // to any loop. Because we do not compute the post dominators, we need to re-run
2179 // loop analysis to get the loop information correct.
2180 rerun_loop_analysis = true;
2181 }
2182 } else {
2183 if (last->IsReturnVoid()) {
2184 DCHECK(return_value == nullptr);
2185 DCHECK(return_value_phi == nullptr);
2186 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002187 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002188 if (return_value_phi != nullptr) {
2189 return_value_phi->AddInput(last->InputAt(0));
2190 } else if (return_value == nullptr) {
2191 return_value = last->InputAt(0);
2192 } else {
2193 // There will be multiple returns.
2194 return_value_phi = new (allocator) HPhi(
2195 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2196 to->AddPhi(return_value_phi);
2197 return_value_phi->AddInput(return_value);
2198 return_value_phi->AddInput(last->InputAt(0));
2199 return_value = return_value_phi;
2200 }
David Brazdil3f523062016-02-29 16:53:33 +00002201 }
2202 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2203 predecessor->RemoveInstruction(last);
2204 }
2205 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002206 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002207 DCHECK(!outer_graph->HasIrreducibleLoops())
2208 << "Recomputing loop information in graphs with irreducible loops "
2209 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002210 outer_graph->ClearLoopInformation();
2211 outer_graph->ClearDominanceInformation();
2212 outer_graph->BuildDominatorTree();
2213 } else if (rerun_dominance) {
2214 outer_graph->ClearDominanceInformation();
2215 outer_graph->ComputeDominanceInformation();
2216 }
David Brazdil3f523062016-02-29 16:53:33 +00002217 }
David Brazdil05144f42015-04-16 15:18:00 +01002218
2219 // Walk over the entry block and:
2220 // - Move constants from the entry block to the outer_graph's entry block,
2221 // - Replace HParameterValue instructions with their real value.
2222 // - Remove suspend checks, that hold an environment.
2223 // We must do this after the other blocks have been inlined, otherwise ids of
2224 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002225 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002226 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2227 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002228 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002229 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002230 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002231 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002232 replacement = outer_graph->GetIntConstant(
2233 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002234 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002235 replacement = outer_graph->GetLongConstant(
2236 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002237 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002238 replacement = outer_graph->GetFloatConstant(
2239 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002240 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002241 replacement = outer_graph->GetDoubleConstant(
2242 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002243 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002244 if (kIsDebugBuild
2245 && invoke->IsInvokeStaticOrDirect()
2246 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2247 // Ensure we do not use the last input of `invoke`, as it
2248 // contains a clinit check which is not an actual argument.
2249 size_t last_input_index = invoke->InputCount() - 1;
2250 DCHECK(parameter_index != last_input_index);
2251 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002252 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002253 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002254 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002255 } else {
2256 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2257 entry_block_->RemoveInstruction(current);
2258 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002259 if (replacement != nullptr) {
2260 current->ReplaceWith(replacement);
2261 // If the current is the return value then we need to update the latter.
2262 if (current == return_value) {
2263 DCHECK_EQ(entry_block_, return_value->GetBlock());
2264 return_value = replacement;
2265 }
2266 }
2267 }
2268
Calin Juravle2e768302015-07-28 14:41:11 +00002269 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002270}
2271
Mingyao Yang3584bce2015-05-19 16:01:59 -07002272/*
2273 * Loop will be transformed to:
2274 * old_pre_header
2275 * |
2276 * if_block
2277 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002278 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002279 * \ /
2280 * new_pre_header
2281 * |
2282 * header
2283 */
2284void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2285 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002286 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002287
Aart Bik3fc7f352015-11-20 22:03:03 -08002288 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002289 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002290 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2291 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002292 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2293 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002294 AddBlock(true_block);
2295 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002296 AddBlock(new_pre_header);
2297
Aart Bik3fc7f352015-11-20 22:03:03 -08002298 header->ReplacePredecessor(old_pre_header, new_pre_header);
2299 old_pre_header->successors_.clear();
2300 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002301
Aart Bik3fc7f352015-11-20 22:03:03 -08002302 old_pre_header->AddSuccessor(if_block);
2303 if_block->AddSuccessor(true_block); // True successor
2304 if_block->AddSuccessor(false_block); // False successor
2305 true_block->AddSuccessor(new_pre_header);
2306 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002307
Aart Bik3fc7f352015-11-20 22:03:03 -08002308 old_pre_header->dominated_blocks_.push_back(if_block);
2309 if_block->SetDominator(old_pre_header);
2310 if_block->dominated_blocks_.push_back(true_block);
2311 true_block->SetDominator(if_block);
2312 if_block->dominated_blocks_.push_back(false_block);
2313 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002314 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002315 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002316 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002317 header->SetDominator(new_pre_header);
2318
Aart Bik3fc7f352015-11-20 22:03:03 -08002319 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002320 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002321 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002322 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002323 reverse_post_order_[index_of_header++] = true_block;
2324 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002325 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002326
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002327 // The pre_header can never be a back edge of a loop.
2328 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2329 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2330 UpdateLoopAndTryInformationOfNewBlock(
2331 if_block, old_pre_header, /* replace_if_back_edge */ false);
2332 UpdateLoopAndTryInformationOfNewBlock(
2333 true_block, old_pre_header, /* replace_if_back_edge */ false);
2334 UpdateLoopAndTryInformationOfNewBlock(
2335 false_block, old_pre_header, /* replace_if_back_edge */ false);
2336 UpdateLoopAndTryInformationOfNewBlock(
2337 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002338}
2339
David Brazdilf5552582015-12-27 13:36:12 +00002340static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002341 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002342 if (rti.IsValid()) {
2343 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2344 << " upper_bound_rti: " << upper_bound_rti
2345 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002346 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2347 << " upper_bound_rti: " << upper_bound_rti
2348 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002349 }
2350}
2351
Calin Juravle2e768302015-07-28 14:41:11 +00002352void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2353 if (kIsDebugBuild) {
2354 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2355 ScopedObjectAccess soa(Thread::Current());
2356 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2357 if (IsBoundType()) {
2358 // Having the test here spares us from making the method virtual just for
2359 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002360 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002361 }
2362 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002363 reference_type_handle_ = rti.GetTypeHandle();
2364 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002365}
2366
David Brazdilf5552582015-12-27 13:36:12 +00002367void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2368 if (kIsDebugBuild) {
2369 ScopedObjectAccess soa(Thread::Current());
2370 DCHECK(upper_bound.IsValid());
2371 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2372 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2373 }
2374 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002375 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002376}
2377
Vladimir Markoa1de9182016-02-25 11:37:38 +00002378ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002379 if (kIsDebugBuild) {
2380 ScopedObjectAccess soa(Thread::Current());
2381 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002382 if (!is_exact) {
2383 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2384 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2385 }
Calin Juravle2e768302015-07-28 14:41:11 +00002386 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002387 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002388}
2389
Calin Juravleacf735c2015-02-12 15:25:22 +00002390std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2391 ScopedObjectAccess soa(Thread::Current());
2392 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002393 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002394 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002395 << " is_exact=" << rhs.IsExact()
2396 << " ]";
2397 return os;
2398}
2399
Mark Mendellc4701932015-04-10 13:18:51 -04002400bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2401 // For now, assume that instructions in different blocks may use the
2402 // environment.
2403 // TODO: Use the control flow to decide if this is true.
2404 if (GetBlock() != other->GetBlock()) {
2405 return true;
2406 }
2407
2408 // We know that we are in the same block. Walk from 'this' to 'other',
2409 // checking to see if there is any instruction with an environment.
2410 HInstruction* current = this;
2411 for (; current != other && current != nullptr; current = current->GetNext()) {
2412 // This is a conservative check, as the instruction result may not be in
2413 // the referenced environment.
2414 if (current->HasEnvironment()) {
2415 return true;
2416 }
2417 }
2418
2419 // We should have been called with 'this' before 'other' in the block.
2420 // Just confirm this.
2421 DCHECK(current != nullptr);
2422 return false;
2423}
2424
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002425void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002426 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2427 IntrinsicSideEffects side_effects,
2428 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002429 intrinsic_ = intrinsic;
2430 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002431
Aart Bik5d75afe2015-12-14 11:57:01 -08002432 // Adjust method's side effects from intrinsic table.
2433 switch (side_effects) {
2434 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2435 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2436 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2437 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2438 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002439
2440 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2441 opt.SetDoesNotNeedDexCache();
2442 opt.SetDoesNotNeedEnvironment();
2443 } else {
2444 // If we need an environment, that means there will be a call, which can trigger GC.
2445 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2446 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002447 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002448 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002449}
2450
David Brazdil6de19382016-01-08 17:37:10 +00002451bool HNewInstance::IsStringAlloc() const {
2452 ScopedObjectAccess soa(Thread::Current());
2453 return GetReferenceTypeInfo().IsStringClass();
2454}
2455
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002456bool HInvoke::NeedsEnvironment() const {
2457 if (!IsIntrinsic()) {
2458 return true;
2459 }
2460 IntrinsicOptimizations opt(*this);
2461 return !opt.GetDoesNotNeedEnvironment();
2462}
2463
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002464const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2465 ArtMethod* caller = GetEnvironment()->GetMethod();
2466 ScopedObjectAccess soa(Thread::Current());
2467 // `caller` is null for a top-level graph representing a method whose declaring
2468 // class was not resolved.
2469 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2470}
2471
Vladimir Markodc151b22015-10-15 18:02:30 +01002472bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
2473 if (GetMethodLoadKind() != MethodLoadKind::kDexCacheViaMethod) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002474 return false;
2475 }
2476 if (!IsIntrinsic()) {
2477 return true;
2478 }
2479 IntrinsicOptimizations opt(*this);
2480 return !opt.GetDoesNotNeedDexCache();
2481}
2482
Vladimir Markof64242a2015-12-01 14:58:23 +00002483std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2484 switch (rhs) {
2485 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
2486 return os << "string_init";
2487 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
2488 return os << "recursive";
2489 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
2490 return os << "direct";
Vladimir Markof64242a2015-12-01 14:58:23 +00002491 case HInvokeStaticOrDirect::MethodLoadKind::kDexCachePcRelative:
2492 return os << "dex_cache_pc_relative";
2493 case HInvokeStaticOrDirect::MethodLoadKind::kDexCacheViaMethod:
2494 return os << "dex_cache_via_method";
2495 default:
2496 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2497 UNREACHABLE();
2498 }
2499}
2500
Vladimir Markofbb184a2015-11-13 14:47:00 +00002501std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2502 switch (rhs) {
2503 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2504 return os << "explicit";
2505 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2506 return os << "implicit";
2507 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2508 return os << "none";
2509 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002510 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2511 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002512 }
2513}
2514
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002515bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2516 const HLoadClass* other_load_class = other->AsLoadClass();
2517 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2518 // names rather than type indexes. However, we shall also have to re-think the hash code.
2519 if (type_index_ != other_load_class->type_index_ ||
2520 GetPackedFields() != other_load_class->GetPackedFields()) {
2521 return false;
2522 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002523 switch (GetLoadKind()) {
2524 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002525 case LoadKind::kJitTableAddress: {
2526 ScopedObjectAccess soa(Thread::Current());
2527 return GetClass().Get() == other_load_class->GetClass().Get();
2528 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002529 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002530 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002531 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002532 }
2533}
2534
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002535void HLoadClass::SetLoadKind(LoadKind load_kind) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002536 SetPackedField<LoadKindField>(load_kind);
2537
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002538 if (load_kind != LoadKind::kDexCacheViaMethod &&
2539 load_kind != LoadKind::kReferrersClass) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002540 RemoveAsUserOfInput(0u);
2541 SetRawInputAt(0u, nullptr);
2542 }
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002543
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002544 if (!NeedsEnvironment()) {
2545 RemoveEnvironment();
2546 SetSideEffects(SideEffects::None());
2547 }
2548}
2549
2550std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2551 switch (rhs) {
2552 case HLoadClass::LoadKind::kReferrersClass:
2553 return os << "ReferrersClass";
2554 case HLoadClass::LoadKind::kBootImageLinkTimeAddress:
2555 return os << "BootImageLinkTimeAddress";
2556 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2557 return os << "BootImageLinkTimePcRelative";
2558 case HLoadClass::LoadKind::kBootImageAddress:
2559 return os << "BootImageAddress";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002560 case HLoadClass::LoadKind::kBssEntry:
2561 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002562 case HLoadClass::LoadKind::kJitTableAddress:
2563 return os << "JitTableAddress";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002564 case HLoadClass::LoadKind::kDexCacheViaMethod:
2565 return os << "DexCacheViaMethod";
2566 default:
2567 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2568 UNREACHABLE();
2569 }
2570}
2571
Vladimir Marko372f10e2016-05-17 16:30:10 +01002572bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2573 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002574 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2575 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002576 if (string_index_ != other_load_string->string_index_ ||
2577 GetPackedFields() != other_load_string->GetPackedFields()) {
2578 return false;
2579 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002580 switch (GetLoadKind()) {
2581 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002582 case LoadKind::kJitTableAddress: {
2583 ScopedObjectAccess soa(Thread::Current());
2584 return GetString().Get() == other_load_string->GetString().Get();
2585 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002586 default:
2587 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002588 }
2589}
2590
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002591void HLoadString::SetLoadKind(LoadKind load_kind) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002592 // Once sharpened, the load kind should not be changed again.
2593 DCHECK_EQ(GetLoadKind(), LoadKind::kDexCacheViaMethod);
2594 SetPackedField<LoadKindField>(load_kind);
2595
2596 if (load_kind != LoadKind::kDexCacheViaMethod) {
2597 RemoveAsUserOfInput(0u);
2598 SetRawInputAt(0u, nullptr);
2599 }
2600 if (!NeedsEnvironment()) {
2601 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002602 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002603 }
2604}
2605
2606std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2607 switch (rhs) {
2608 case HLoadString::LoadKind::kBootImageLinkTimeAddress:
2609 return os << "BootImageLinkTimeAddress";
2610 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2611 return os << "BootImageLinkTimePcRelative";
2612 case HLoadString::LoadKind::kBootImageAddress:
2613 return os << "BootImageAddress";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002614 case HLoadString::LoadKind::kBssEntry:
2615 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002616 case HLoadString::LoadKind::kJitTableAddress:
2617 return os << "JitTableAddress";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002618 case HLoadString::LoadKind::kDexCacheViaMethod:
2619 return os << "DexCacheViaMethod";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002620 default:
2621 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2622 UNREACHABLE();
2623 }
2624}
2625
Mark Mendellc4701932015-04-10 13:18:51 -04002626void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002627 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2628 HEnvironment* user = use.GetUser();
2629 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002630 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002631 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002632}
2633
Roland Levillainc9b21f82016-03-23 16:36:59 +00002634// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002635HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2636 ArenaAllocator* allocator = GetArena();
2637
2638 if (cond->IsCondition() &&
2639 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2640 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2641 HInstruction* lhs = cond->InputAt(0);
2642 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002643 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002644 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2645 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2646 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2647 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2648 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2649 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2650 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2651 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2652 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2653 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2654 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002655 default:
2656 LOG(FATAL) << "Unexpected condition";
2657 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002658 }
2659 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2660 return replacement;
2661 } else if (cond->IsIntConstant()) {
2662 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002663 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002664 return GetIntConstant(1);
2665 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002666 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002667 return GetIntConstant(0);
2668 }
2669 } else {
2670 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2671 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2672 return replacement;
2673 }
2674}
2675
Roland Levillainc9285912015-12-18 10:38:42 +00002676std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2677 os << "["
2678 << " source=" << rhs.GetSource()
2679 << " destination=" << rhs.GetDestination()
2680 << " type=" << rhs.GetType()
2681 << " instruction=";
2682 if (rhs.GetInstruction() != nullptr) {
2683 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2684 } else {
2685 os << "null";
2686 }
2687 os << " ]";
2688 return os;
2689}
2690
Roland Levillain86503782016-02-11 19:07:30 +00002691std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2692 switch (rhs) {
2693 case TypeCheckKind::kUnresolvedCheck:
2694 return os << "unresolved_check";
2695 case TypeCheckKind::kExactCheck:
2696 return os << "exact_check";
2697 case TypeCheckKind::kClassHierarchyCheck:
2698 return os << "class_hierarchy_check";
2699 case TypeCheckKind::kAbstractClassCheck:
2700 return os << "abstract_class_check";
2701 case TypeCheckKind::kInterfaceCheck:
2702 return os << "interface_check";
2703 case TypeCheckKind::kArrayObjectCheck:
2704 return os << "array_object_check";
2705 case TypeCheckKind::kArrayCheck:
2706 return os << "array_check";
2707 default:
2708 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2709 UNREACHABLE();
2710 }
2711}
2712
Andreas Gampe26de38b2016-07-27 17:53:11 -07002713std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2714 switch (kind) {
2715 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002716 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002717 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002718 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002719 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002720 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002721 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002722 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002723 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002724 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002725
2726 default:
2727 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
2728 UNREACHABLE();
2729 }
2730}
2731
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002732} // namespace art