blob: 8644f676e83a194134b0042f5284f40185838022 [file] [log] [blame]
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Nicolas Geoffray818f2102014-02-18 16:43:35 +000016#include "nodes.h"
Calin Juravle77520bc2015-01-12 18:45:46 +000017
Roland Levillain31dd3d62016-02-16 12:21:02 +000018#include <cfloat>
19
Andreas Gampec6ea7d02017-02-01 16:46:28 -080020#include "art_method-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include "base/bit_utils.h"
22#include "base/bit_vector-inl.h"
23#include "base/stl_util.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080024#include "class_linker-inl.h"
Mark Mendelle82549b2015-05-06 10:55:34 -040025#include "code_generator.h"
Vladimir Marko391d01f2015-11-06 11:02:08 +000026#include "common_dominator.h"
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010027#include "intrinsics.h"
David Brazdilbaf89b82015-09-15 11:36:54 +010028#include "mirror/class-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070029#include "scoped_thread_state_change-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070030#include "ssa_builder.h"
Nicolas Geoffray818f2102014-02-18 16:43:35 +000031
32namespace art {
33
Roland Levillain31dd3d62016-02-16 12:21:02 +000034// Enable floating-point static evaluation during constant folding
35// only if all floating-point operations and constants evaluate in the
36// range and precision of the type used (i.e., 32-bit float, 64-bit
37// double).
38static constexpr bool kEnableFloatingPointStaticEvaluation = (FLT_EVAL_METHOD == 0);
39
Mathieu Chartiere8a3c572016-10-11 16:52:17 -070040void HGraph::InitializeInexactObjectRTI(VariableSizedHandleScope* handles) {
David Brazdilbadd8262016-02-02 16:28:56 +000041 ScopedObjectAccess soa(Thread::Current());
42 // Create the inexact Object reference type and store it in the HGraph.
43 ClassLinker* linker = Runtime::Current()->GetClassLinker();
44 inexact_object_rti_ = ReferenceTypeInfo::Create(
45 handles->NewHandle(linker->GetClassRoot(ClassLinker::kJavaLangObject)),
46 /* is_exact */ false);
47}
48
Nicolas Geoffray818f2102014-02-18 16:43:35 +000049void HGraph::AddBlock(HBasicBlock* block) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +010050 block->SetBlockId(blocks_.size());
51 blocks_.push_back(block);
Nicolas Geoffray818f2102014-02-18 16:43:35 +000052}
53
Nicolas Geoffray804d0932014-05-02 08:46:00 +010054void HGraph::FindBackEdges(ArenaBitVector* visited) {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010055 // "visited" must be empty on entry, it's an output argument for all visited (i.e. live) blocks.
56 DCHECK_EQ(visited->GetHighestBitSet(), -1);
57
58 // Nodes that we're currently visiting, indexed by block id.
Vladimir Markof6a35de2016-03-21 12:01:50 +000059 ArenaBitVector visiting(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Vladimir Marko1f8695c2015-09-24 13:11:31 +010060 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +010061 ArenaVector<size_t> successors_visited(blocks_.size(),
62 0u,
63 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010064 // Stack of nodes that we're currently visiting (same as marked in "visiting" above).
Vladimir Marko3ea5a972016-05-09 20:23:34 +010065 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Marko1f8695c2015-09-24 13:11:31 +010066 constexpr size_t kDefaultWorklistSize = 8;
67 worklist.reserve(kDefaultWorklistSize);
68 visited->SetBit(entry_block_->GetBlockId());
69 visiting.SetBit(entry_block_->GetBlockId());
70 worklist.push_back(entry_block_);
71
72 while (!worklist.empty()) {
73 HBasicBlock* current = worklist.back();
74 uint32_t current_id = current->GetBlockId();
75 if (successors_visited[current_id] == current->GetSuccessors().size()) {
76 visiting.ClearBit(current_id);
77 worklist.pop_back();
78 } else {
Vladimir Marko1f8695c2015-09-24 13:11:31 +010079 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
80 uint32_t successor_id = successor->GetBlockId();
81 if (visiting.IsBitSet(successor_id)) {
82 DCHECK(ContainsElement(worklist, successor));
83 successor->AddBackEdge(current);
84 } else if (!visited->IsBitSet(successor_id)) {
85 visited->SetBit(successor_id);
86 visiting.SetBit(successor_id);
87 worklist.push_back(successor);
88 }
89 }
90 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +000091}
92
Artem Serov21c7e6f2017-07-27 16:04:42 +010093// Remove the environment use records of the instruction for users.
94void RemoveEnvironmentUses(HInstruction* instruction) {
Nicolas Geoffray0a23d742015-05-07 11:57:35 +010095 for (HEnvironment* environment = instruction->GetEnvironment();
96 environment != nullptr;
97 environment = environment->GetParent()) {
Roland Levillainfc600dc2014-12-02 17:16:31 +000098 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
David Brazdil1abb4192015-02-17 18:33:36 +000099 if (environment->GetInstructionAt(i) != nullptr) {
100 environment->RemoveAsUserOfInput(i);
Roland Levillainfc600dc2014-12-02 17:16:31 +0000101 }
102 }
103 }
104}
105
Artem Serov21c7e6f2017-07-27 16:04:42 +0100106// Return whether the instruction has an environment and it's used by others.
107bool HasEnvironmentUsedByOthers(HInstruction* instruction) {
108 for (HEnvironment* environment = instruction->GetEnvironment();
109 environment != nullptr;
110 environment = environment->GetParent()) {
111 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
112 HInstruction* user = environment->GetInstructionAt(i);
113 if (user != nullptr) {
114 return true;
115 }
116 }
117 }
118 return false;
119}
120
121// Reset environment records of the instruction itself.
122void ResetEnvironmentInputRecords(HInstruction* instruction) {
123 for (HEnvironment* environment = instruction->GetEnvironment();
124 environment != nullptr;
125 environment = environment->GetParent()) {
126 for (size_t i = 0, e = environment->Size(); i < e; ++i) {
127 DCHECK(environment->GetHolder() == instruction);
128 if (environment->GetInstructionAt(i) != nullptr) {
129 environment->SetRawEnvAt(i, nullptr);
130 }
131 }
132 }
133}
134
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000135static void RemoveAsUser(HInstruction* instruction) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100136 instruction->RemoveAsUserOfAllInputs();
Vladimir Markocac5a7e2016-02-22 10:39:50 +0000137 RemoveEnvironmentUses(instruction);
138}
139
Roland Levillainfc600dc2014-12-02 17:16:31 +0000140void HGraph::RemoveInstructionsAsUsersFromDeadBlocks(const ArenaBitVector& visited) const {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100141 for (size_t i = 0; i < blocks_.size(); ++i) {
Roland Levillainfc600dc2014-12-02 17:16:31 +0000142 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100143 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000144 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100145 DCHECK(block->GetPhis().IsEmpty()) << "Phis are not inserted at this stage";
Roland Levillainfc600dc2014-12-02 17:16:31 +0000146 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
147 RemoveAsUser(it.Current());
148 }
149 }
150 }
151}
152
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100153void HGraph::RemoveDeadBlocks(const ArenaBitVector& visited) {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100154 for (size_t i = 0; i < blocks_.size(); ++i) {
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000155 if (!visited.IsBitSet(i)) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100156 HBasicBlock* block = blocks_[i];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000157 if (block == nullptr) continue;
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100158 // We only need to update the successor, which might be live.
Vladimir Marko60584552015-09-03 13:35:12 +0000159 for (HBasicBlock* successor : block->GetSuccessors()) {
160 successor->RemovePredecessor(block);
David Brazdil1abb4192015-02-17 18:33:36 +0000161 }
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100162 // Remove the block from the list of blocks, so that further analyses
163 // never see it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100164 blocks_[i] = nullptr;
Serguei Katkov7ba99662016-03-02 16:25:36 +0600165 if (block->IsExitBlock()) {
166 SetExitBlock(nullptr);
167 }
David Brazdil86ea7ee2016-02-16 09:26:07 +0000168 // Mark the block as removed. This is used by the HGraphBuilder to discard
169 // the block as a branch target.
170 block->SetGraph(nullptr);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000171 }
172 }
173}
174
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000175GraphAnalysisResult HGraph::BuildDominatorTree() {
Vladimir Markof6a35de2016-03-21 12:01:50 +0000176 ArenaBitVector visited(arena_, blocks_.size(), false, kArenaAllocGraphBuilder);
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000177
David Brazdil86ea7ee2016-02-16 09:26:07 +0000178 // (1) Find the back edges in the graph doing a DFS traversal.
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000179 FindBackEdges(&visited);
180
David Brazdil86ea7ee2016-02-16 09:26:07 +0000181 // (2) Remove instructions and phis from blocks not visited during
Roland Levillainfc600dc2014-12-02 17:16:31 +0000182 // the initial DFS as users from other instructions, so that
183 // users can be safely removed before uses later.
184 RemoveInstructionsAsUsersFromDeadBlocks(visited);
185
David Brazdil86ea7ee2016-02-16 09:26:07 +0000186 // (3) Remove blocks not visited during the initial DFS.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000187 // Step (5) requires dead blocks to be removed from the
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000188 // predecessors list of live blocks.
189 RemoveDeadBlocks(visited);
190
David Brazdil86ea7ee2016-02-16 09:26:07 +0000191 // (4) Simplify the CFG now, so that we don't need to recompute
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100192 // dominators and the reverse post order.
193 SimplifyCFG();
194
David Brazdil86ea7ee2016-02-16 09:26:07 +0000195 // (5) Compute the dominance information and the reverse post order.
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100196 ComputeDominanceInformation();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000197
David Brazdil86ea7ee2016-02-16 09:26:07 +0000198 // (6) Analyze loops discovered through back edge analysis, and
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000199 // set the loop information on each block.
200 GraphAnalysisResult result = AnalyzeLoops();
201 if (result != kAnalysisSuccess) {
202 return result;
203 }
204
David Brazdil86ea7ee2016-02-16 09:26:07 +0000205 // (7) Precompute per-block try membership before entering the SSA builder,
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000206 // which needs the information to build catch block phis from values of
207 // locals at throwing instructions inside try blocks.
208 ComputeTryBlockInformation();
209
210 return kAnalysisSuccess;
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100211}
212
213void HGraph::ClearDominanceInformation() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100214 for (HBasicBlock* block : GetReversePostOrder()) {
215 block->ClearDominanceInformation();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100216 }
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100217 reverse_post_order_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100218}
219
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000220void HGraph::ClearLoopInformation() {
221 SetHasIrreducibleLoops(false);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100222 for (HBasicBlock* block : GetReversePostOrder()) {
223 block->SetLoopInformation(nullptr);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000224 }
225}
226
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100227void HBasicBlock::ClearDominanceInformation() {
Vladimir Marko60584552015-09-03 13:35:12 +0000228 dominated_blocks_.clear();
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100229 dominator_ = nullptr;
230}
231
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000232HInstruction* HBasicBlock::GetFirstInstructionDisregardMoves() const {
233 HInstruction* instruction = GetFirstInstruction();
234 while (instruction->IsParallelMove()) {
235 instruction = instruction->GetNext();
236 }
237 return instruction;
238}
239
David Brazdil3f4a5222016-05-06 12:46:21 +0100240static bool UpdateDominatorOfSuccessor(HBasicBlock* block, HBasicBlock* successor) {
241 DCHECK(ContainsElement(block->GetSuccessors(), successor));
242
243 HBasicBlock* old_dominator = successor->GetDominator();
244 HBasicBlock* new_dominator =
245 (old_dominator == nullptr) ? block
246 : CommonDominator::ForPair(old_dominator, block);
247
248 if (old_dominator == new_dominator) {
249 return false;
250 } else {
251 successor->SetDominator(new_dominator);
252 return true;
253 }
254}
255
Nicolas Geoffray1f82ecc2015-06-24 12:20:24 +0100256void HGraph::ComputeDominanceInformation() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100257 DCHECK(reverse_post_order_.empty());
258 reverse_post_order_.reserve(blocks_.size());
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100259 reverse_post_order_.push_back(entry_block_);
Vladimir Markod76d1392015-09-23 16:07:14 +0100260
261 // Number of visits of a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100262 ArenaVector<size_t> visits(blocks_.size(), 0u, arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100263 // Number of successors visited from a given node, indexed by block id.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100264 ArenaVector<size_t> successors_visited(blocks_.size(),
265 0u,
266 arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100267 // Nodes for which we need to visit successors.
Vladimir Marko3ea5a972016-05-09 20:23:34 +0100268 ArenaVector<HBasicBlock*> worklist(arena_->Adapter(kArenaAllocGraphBuilder));
Vladimir Markod76d1392015-09-23 16:07:14 +0100269 constexpr size_t kDefaultWorklistSize = 8;
270 worklist.reserve(kDefaultWorklistSize);
271 worklist.push_back(entry_block_);
272
273 while (!worklist.empty()) {
274 HBasicBlock* current = worklist.back();
275 uint32_t current_id = current->GetBlockId();
276 if (successors_visited[current_id] == current->GetSuccessors().size()) {
277 worklist.pop_back();
278 } else {
Vladimir Markod76d1392015-09-23 16:07:14 +0100279 HBasicBlock* successor = current->GetSuccessors()[successors_visited[current_id]++];
David Brazdil3f4a5222016-05-06 12:46:21 +0100280 UpdateDominatorOfSuccessor(current, successor);
Vladimir Markod76d1392015-09-23 16:07:14 +0100281
282 // Once all the forward edges have been visited, we know the immediate
283 // dominator of the block. We can then start visiting its successors.
Vladimir Markod76d1392015-09-23 16:07:14 +0100284 if (++visits[successor->GetBlockId()] ==
285 successor->GetPredecessors().size() - successor->NumberOfBackEdges()) {
Vladimir Markod76d1392015-09-23 16:07:14 +0100286 reverse_post_order_.push_back(successor);
287 worklist.push_back(successor);
288 }
289 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000290 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000291
David Brazdil3f4a5222016-05-06 12:46:21 +0100292 // Check if the graph has back edges not dominated by their respective headers.
293 // If so, we need to update the dominators of those headers and recursively of
294 // their successors. We do that with a fix-point iteration over all blocks.
295 // The algorithm is guaranteed to terminate because it loops only if the sum
296 // of all dominator chains has decreased in the current iteration.
297 bool must_run_fix_point = false;
298 for (HBasicBlock* block : blocks_) {
299 if (block != nullptr &&
300 block->IsLoopHeader() &&
301 block->GetLoopInformation()->HasBackEdgeNotDominatedByHeader()) {
302 must_run_fix_point = true;
303 break;
304 }
305 }
306 if (must_run_fix_point) {
307 bool update_occurred = true;
308 while (update_occurred) {
309 update_occurred = false;
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100310 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100311 for (HBasicBlock* successor : block->GetSuccessors()) {
312 update_occurred |= UpdateDominatorOfSuccessor(block, successor);
313 }
314 }
315 }
316 }
317
318 // Make sure that there are no remaining blocks whose dominator information
319 // needs to be updated.
320 if (kIsDebugBuild) {
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100321 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdil3f4a5222016-05-06 12:46:21 +0100322 for (HBasicBlock* successor : block->GetSuccessors()) {
323 DCHECK(!UpdateDominatorOfSuccessor(block, successor));
324 }
325 }
326 }
327
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000328 // Populate `dominated_blocks_` information after computing all dominators.
Roland Levillainc9b21f82016-03-23 16:36:59 +0000329 // The potential presence of irreducible loops requires to do it after.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100330 for (HBasicBlock* block : GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000331 if (!block->IsEntryBlock()) {
332 block->GetDominator()->AddDominatedBlock(block);
333 }
334 }
Nicolas Geoffraybe9a92a2014-02-25 14:22:56 +0000335}
336
David Brazdilfc6a86a2015-06-26 10:33:45 +0000337HBasicBlock* HGraph::SplitEdge(HBasicBlock* block, HBasicBlock* successor) {
David Brazdil3e187382015-06-26 09:59:52 +0000338 HBasicBlock* new_block = new (arena_) HBasicBlock(this, successor->GetDexPc());
339 AddBlock(new_block);
David Brazdil3e187382015-06-26 09:59:52 +0000340 // Use `InsertBetween` to ensure the predecessor index and successor index of
341 // `block` and `successor` are preserved.
342 new_block->InsertBetween(block, successor);
David Brazdilfc6a86a2015-06-26 10:33:45 +0000343 return new_block;
344}
345
346void HGraph::SplitCriticalEdge(HBasicBlock* block, HBasicBlock* successor) {
347 // Insert a new node between `block` and `successor` to split the
348 // critical edge.
349 HBasicBlock* new_block = SplitEdge(block, successor);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600350 new_block->AddInstruction(new (arena_) HGoto(successor->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100351 if (successor->IsLoopHeader()) {
352 // If we split at a back edge boundary, make the new block the back edge.
353 HLoopInformation* info = successor->GetLoopInformation();
David Brazdil46e2a392015-03-16 17:31:52 +0000354 if (info->IsBackEdge(*block)) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100355 info->RemoveBackEdge(block);
356 info->AddBackEdge(new_block);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100357 }
358 }
359}
360
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100361void HGraph::SimplifyLoop(HBasicBlock* header) {
362 HLoopInformation* info = header->GetLoopInformation();
363
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100364 // Make sure the loop has only one pre header. This simplifies SSA building by having
365 // to just look at the pre header to know which locals are initialized at entry of the
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000366 // loop. Also, don't allow the entry block to be a pre header: this simplifies inlining
367 // this graph.
Vladimir Marko60584552015-09-03 13:35:12 +0000368 size_t number_of_incomings = header->GetPredecessors().size() - info->NumberOfBackEdges();
Nicolas Geoffray788f2f02016-01-22 12:41:38 +0000369 if (number_of_incomings != 1 || (GetEntryBlock()->GetSingleSuccessor() == header)) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100370 HBasicBlock* pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100371 AddBlock(pre_header);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600372 pre_header->AddInstruction(new (arena_) HGoto(header->GetDexPc()));
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100373
Vladimir Marko60584552015-09-03 13:35:12 +0000374 for (size_t pred = 0; pred < header->GetPredecessors().size(); ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100375 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100376 if (!info->IsBackEdge(*predecessor)) {
Nicolas Geoffrayec7e4722014-06-06 11:24:33 +0100377 predecessor->ReplaceSuccessor(header, pre_header);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100378 pred--;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100379 }
380 }
381 pre_header->AddSuccessor(header);
382 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100383
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100384 // Make sure the first predecessor of a loop header is the incoming block.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100385 if (info->IsBackEdge(*header->GetPredecessors()[0])) {
386 HBasicBlock* to_swap = header->GetPredecessors()[0];
Vladimir Marko60584552015-09-03 13:35:12 +0000387 for (size_t pred = 1, e = header->GetPredecessors().size(); pred < e; ++pred) {
Vladimir Markoec7802a2015-10-01 20:57:57 +0100388 HBasicBlock* predecessor = header->GetPredecessors()[pred];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100389 if (!info->IsBackEdge(*predecessor)) {
Vladimir Marko60584552015-09-03 13:35:12 +0000390 header->predecessors_[pred] = to_swap;
391 header->predecessors_[0] = predecessor;
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100392 break;
393 }
394 }
Nicolas Geoffray604c6e42014-09-17 12:08:44 +0100395 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100396
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100397 HInstruction* first_instruction = header->GetFirstInstruction();
David Brazdildee58d62016-04-07 09:54:26 +0000398 if (first_instruction != nullptr && first_instruction->IsSuspendCheck()) {
399 // Called from DeadBlockElimination. Update SuspendCheck pointer.
400 info->SetSuspendCheck(first_instruction->AsSuspendCheck());
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100401 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100402}
403
David Brazdilffee3d32015-07-06 11:48:53 +0100404void HGraph::ComputeTryBlockInformation() {
405 // Iterate in reverse post order to propagate try membership information from
406 // predecessors to their successors.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100407 for (HBasicBlock* block : GetReversePostOrder()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100408 if (block->IsEntryBlock() || block->IsCatchBlock()) {
409 // Catch blocks after simplification have only exceptional predecessors
410 // and hence are never in tries.
411 continue;
412 }
413
414 // Infer try membership from the first predecessor. Having simplified loops,
415 // the first predecessor can never be a back edge and therefore it must have
416 // been visited already and had its try membership set.
Vladimir Markoec7802a2015-10-01 20:57:57 +0100417 HBasicBlock* first_predecessor = block->GetPredecessors()[0];
David Brazdilffee3d32015-07-06 11:48:53 +0100418 DCHECK(!block->IsLoopHeader() || !block->GetLoopInformation()->IsBackEdge(*first_predecessor));
David Brazdilec16f792015-08-19 15:04:01 +0100419 const HTryBoundary* try_entry = first_predecessor->ComputeTryEntryOfSuccessors();
David Brazdil8a7c0fe2015-11-02 20:24:55 +0000420 if (try_entry != nullptr &&
421 (block->GetTryCatchInformation() == nullptr ||
422 try_entry != &block->GetTryCatchInformation()->GetTryEntry())) {
423 // We are either setting try block membership for the first time or it
424 // has changed.
David Brazdilec16f792015-08-19 15:04:01 +0100425 block->SetTryCatchInformation(new (arena_) TryCatchInformation(*try_entry));
426 }
David Brazdilffee3d32015-07-06 11:48:53 +0100427 }
428}
429
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100430void HGraph::SimplifyCFG() {
David Brazdildb51efb2015-11-06 01:36:20 +0000431// Simplify the CFG for future analysis, and code generation:
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100432 // (1): Split critical edges.
David Brazdildb51efb2015-11-06 01:36:20 +0000433 // (2): Simplify loops by having only one preheader.
Vladimir Markob7d8e8c2015-09-17 15:47:05 +0100434 // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
435 // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
436 for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
437 HBasicBlock* block = blocks_[block_id];
Nicolas Geoffrayf776b922015-04-15 18:22:45 +0100438 if (block == nullptr) continue;
David Brazdildb51efb2015-11-06 01:36:20 +0000439 if (block->GetSuccessors().size() > 1) {
440 // Only split normal-flow edges. We cannot split exceptional edges as they
441 // are synthesized (approximate real control flow), and we do not need to
442 // anyway. Moves that would be inserted there are performed by the runtime.
David Brazdild26a4112015-11-10 11:07:31 +0000443 ArrayRef<HBasicBlock* const> normal_successors = block->GetNormalSuccessors();
444 for (size_t j = 0, e = normal_successors.size(); j < e; ++j) {
445 HBasicBlock* successor = normal_successors[j];
David Brazdilffee3d32015-07-06 11:48:53 +0100446 DCHECK(!successor->IsCatchBlock());
David Brazdildb51efb2015-11-06 01:36:20 +0000447 if (successor == exit_block_) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000448 // (Throw/Return/ReturnVoid)->TryBoundary->Exit. Special case which we
449 // do not want to split because Goto->Exit is not allowed.
David Brazdildb51efb2015-11-06 01:36:20 +0000450 DCHECK(block->IsSingleTryBoundary());
David Brazdildb51efb2015-11-06 01:36:20 +0000451 } else if (successor->GetPredecessors().size() > 1) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100452 SplitCriticalEdge(block, successor);
David Brazdild26a4112015-11-10 11:07:31 +0000453 // SplitCriticalEdge could have invalidated the `normal_successors`
454 // ArrayRef. We must re-acquire it.
455 normal_successors = block->GetNormalSuccessors();
456 DCHECK_EQ(normal_successors[j]->GetSingleSuccessor(), successor);
457 DCHECK_EQ(e, normal_successors.size());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100458 }
459 }
460 }
461 if (block->IsLoopHeader()) {
462 SimplifyLoop(block);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000463 } else if (!block->IsEntryBlock() &&
464 block->GetFirstInstruction() != nullptr &&
465 block->GetFirstInstruction()->IsSuspendCheck()) {
466 // We are being called by the dead code elimiation pass, and what used to be
Nicolas Geoffray09aa1472016-01-19 10:52:54 +0000467 // a loop got dismantled. Just remove the suspend check.
468 block->RemoveInstruction(block->GetFirstInstruction());
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100469 }
470 }
471}
472
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000473GraphAnalysisResult HGraph::AnalyzeLoops() const {
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100474 // We iterate post order to ensure we visit inner loops before outer loops.
475 // `PopulateRecursive` needs this guarantee to know whether a natural loop
476 // contains an irreducible loop.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100477 for (HBasicBlock* block : GetPostOrder()) {
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100478 if (block->IsLoopHeader()) {
David Brazdilffee3d32015-07-06 11:48:53 +0100479 if (block->IsCatchBlock()) {
480 // TODO: Dealing with exceptional back edges could be tricky because
481 // they only approximate the real control flow. Bail out for now.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000482 return kAnalysisFailThrowCatchLoop;
David Brazdilffee3d32015-07-06 11:48:53 +0100483 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000484 block->GetLoopInformation()->Populate();
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100485 }
486 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000487 return kAnalysisSuccess;
488}
489
490void HLoopInformation::Dump(std::ostream& os) {
491 os << "header: " << header_->GetBlockId() << std::endl;
492 os << "pre header: " << GetPreHeader()->GetBlockId() << std::endl;
493 for (HBasicBlock* block : back_edges_) {
494 os << "back edge: " << block->GetBlockId() << std::endl;
495 }
496 for (HBasicBlock* block : header_->GetPredecessors()) {
497 os << "predecessor: " << block->GetBlockId() << std::endl;
498 }
499 for (uint32_t idx : blocks_.Indexes()) {
500 os << " in loop: " << idx << std::endl;
501 }
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100502}
503
David Brazdil8d5b8b22015-03-24 10:51:52 +0000504void HGraph::InsertConstant(HConstant* constant) {
David Brazdil86ea7ee2016-02-16 09:26:07 +0000505 // New constants are inserted before the SuspendCheck at the bottom of the
506 // entry block. Note that this method can be called from the graph builder and
507 // the entry block therefore may not end with SuspendCheck->Goto yet.
508 HInstruction* insert_before = nullptr;
509
510 HInstruction* gota = entry_block_->GetLastInstruction();
511 if (gota != nullptr && gota->IsGoto()) {
512 HInstruction* suspend_check = gota->GetPrevious();
513 if (suspend_check != nullptr && suspend_check->IsSuspendCheck()) {
514 insert_before = suspend_check;
515 } else {
516 insert_before = gota;
517 }
518 }
519
520 if (insert_before == nullptr) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000521 entry_block_->AddInstruction(constant);
David Brazdil86ea7ee2016-02-16 09:26:07 +0000522 } else {
523 entry_block_->InsertInstructionBefore(constant, insert_before);
David Brazdil46e2a392015-03-16 17:31:52 +0000524 }
525}
526
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600527HNullConstant* HGraph::GetNullConstant(uint32_t dex_pc) {
Nicolas Geoffray18e68732015-06-17 23:09:05 +0100528 // For simplicity, don't bother reviving the cached null constant if it is
529 // not null and not in a block. Otherwise, we need to clear the instruction
530 // id and/or any invariants the graph is assuming when adding new instructions.
531 if ((cached_null_constant_ == nullptr) || (cached_null_constant_->GetBlock() == nullptr)) {
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600532 cached_null_constant_ = new (arena_) HNullConstant(dex_pc);
David Brazdil4833f5a2015-12-16 10:37:39 +0000533 cached_null_constant_->SetReferenceTypeInfo(inexact_object_rti_);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000534 InsertConstant(cached_null_constant_);
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000535 }
David Brazdil4833f5a2015-12-16 10:37:39 +0000536 if (kIsDebugBuild) {
537 ScopedObjectAccess soa(Thread::Current());
538 DCHECK(cached_null_constant_->GetReferenceTypeInfo().IsValid());
539 }
Nicolas Geoffrayd6138ef2015-02-18 14:48:53 +0000540 return cached_null_constant_;
541}
542
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100543HCurrentMethod* HGraph::GetCurrentMethod() {
Nicolas Geoffrayf78848f2015-06-17 11:57:56 +0100544 // For simplicity, don't bother reviving the cached current method if it is
545 // not null and not in a block. Otherwise, we need to clear the instruction
546 // id and/or any invariants the graph is assuming when adding new instructions.
547 if ((cached_current_method_ == nullptr) || (cached_current_method_->GetBlock() == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700548 cached_current_method_ = new (arena_) HCurrentMethod(
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600549 Is64BitInstructionSet(instruction_set_) ? Primitive::kPrimLong : Primitive::kPrimInt,
550 entry_block_->GetDexPc());
Nicolas Geoffray76b1e172015-05-27 17:18:33 +0100551 if (entry_block_->GetFirstInstruction() == nullptr) {
552 entry_block_->AddInstruction(cached_current_method_);
553 } else {
554 entry_block_->InsertInstructionBefore(
555 cached_current_method_, entry_block_->GetFirstInstruction());
556 }
557 }
558 return cached_current_method_;
559}
560
Igor Murashkind01745e2017-04-05 16:40:31 -0700561const char* HGraph::GetMethodName() const {
562 const DexFile::MethodId& method_id = dex_file_.GetMethodId(method_idx_);
563 return dex_file_.GetMethodName(method_id);
564}
565
566std::string HGraph::PrettyMethod(bool with_signature) const {
567 return dex_file_.PrettyMethod(method_idx_, with_signature);
568}
569
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600570HConstant* HGraph::GetConstant(Primitive::Type type, int64_t value, uint32_t dex_pc) {
David Brazdil8d5b8b22015-03-24 10:51:52 +0000571 switch (type) {
572 case Primitive::Type::kPrimBoolean:
573 DCHECK(IsUint<1>(value));
574 FALLTHROUGH_INTENDED;
575 case Primitive::Type::kPrimByte:
576 case Primitive::Type::kPrimChar:
577 case Primitive::Type::kPrimShort:
578 case Primitive::Type::kPrimInt:
579 DCHECK(IsInt(Primitive::ComponentSize(type) * kBitsPerByte, value));
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600580 return GetIntConstant(static_cast<int32_t>(value), dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000581
582 case Primitive::Type::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +0600583 return GetLongConstant(value, dex_pc);
David Brazdil8d5b8b22015-03-24 10:51:52 +0000584
585 default:
586 LOG(FATAL) << "Unsupported constant type";
587 UNREACHABLE();
David Brazdil46e2a392015-03-16 17:31:52 +0000588 }
David Brazdil46e2a392015-03-16 17:31:52 +0000589}
590
Nicolas Geoffrayf213e052015-04-27 08:53:46 +0000591void HGraph::CacheFloatConstant(HFloatConstant* constant) {
592 int32_t value = bit_cast<int32_t, float>(constant->GetValue());
593 DCHECK(cached_float_constants_.find(value) == cached_float_constants_.end());
594 cached_float_constants_.Overwrite(value, constant);
595}
596
597void HGraph::CacheDoubleConstant(HDoubleConstant* constant) {
598 int64_t value = bit_cast<int64_t, double>(constant->GetValue());
599 DCHECK(cached_double_constants_.find(value) == cached_double_constants_.end());
600 cached_double_constants_.Overwrite(value, constant);
601}
602
Nicolas Geoffray276d9da2015-02-02 18:24:11 +0000603void HLoopInformation::Add(HBasicBlock* block) {
604 blocks_.SetBit(block->GetBlockId());
605}
606
David Brazdil46e2a392015-03-16 17:31:52 +0000607void HLoopInformation::Remove(HBasicBlock* block) {
608 blocks_.ClearBit(block->GetBlockId());
609}
610
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100611void HLoopInformation::PopulateRecursive(HBasicBlock* block) {
612 if (blocks_.IsBitSet(block->GetBlockId())) {
613 return;
614 }
615
616 blocks_.SetBit(block->GetBlockId());
617 block->SetInLoop(this);
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100618 if (block->IsLoopHeader()) {
619 // We're visiting loops in post-order, so inner loops must have been
620 // populated already.
621 DCHECK(block->GetLoopInformation()->IsPopulated());
622 if (block->GetLoopInformation()->IsIrreducible()) {
623 contains_irreducible_loop_ = true;
624 }
625 }
Vladimir Marko60584552015-09-03 13:35:12 +0000626 for (HBasicBlock* predecessor : block->GetPredecessors()) {
627 PopulateRecursive(predecessor);
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100628 }
629}
630
David Brazdilc2e8af92016-04-05 17:15:19 +0100631void HLoopInformation::PopulateIrreducibleRecursive(HBasicBlock* block, ArenaBitVector* finalized) {
632 size_t block_id = block->GetBlockId();
633
634 // If `block` is in `finalized`, we know its membership in the loop has been
635 // decided and it does not need to be revisited.
636 if (finalized->IsBitSet(block_id)) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000637 return;
638 }
639
David Brazdilc2e8af92016-04-05 17:15:19 +0100640 bool is_finalized = false;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000641 if (block->IsLoopHeader()) {
642 // If we hit a loop header in an irreducible loop, we first check if the
643 // pre header of that loop belongs to the currently analyzed loop. If it does,
644 // then we visit the back edges.
645 // Note that we cannot use GetPreHeader, as the loop may have not been populated
646 // yet.
647 HBasicBlock* pre_header = block->GetPredecessors()[0];
David Brazdilc2e8af92016-04-05 17:15:19 +0100648 PopulateIrreducibleRecursive(pre_header, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000649 if (blocks_.IsBitSet(pre_header->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000650 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100651 blocks_.SetBit(block_id);
652 finalized->SetBit(block_id);
653 is_finalized = true;
654
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000655 HLoopInformation* info = block->GetLoopInformation();
656 for (HBasicBlock* back_edge : info->GetBackEdges()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100657 PopulateIrreducibleRecursive(back_edge, finalized);
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000658 }
659 }
660 } else {
661 // Visit all predecessors. If one predecessor is part of the loop, this
662 // block is also part of this loop.
663 for (HBasicBlock* predecessor : block->GetPredecessors()) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100664 PopulateIrreducibleRecursive(predecessor, finalized);
665 if (!is_finalized && blocks_.IsBitSet(predecessor->GetBlockId())) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000666 block->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100667 blocks_.SetBit(block_id);
668 finalized->SetBit(block_id);
669 is_finalized = true;
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000670 }
671 }
672 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100673
674 // All predecessors have been recursively visited. Mark finalized if not marked yet.
675 if (!is_finalized) {
676 finalized->SetBit(block_id);
677 }
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000678}
679
680void HLoopInformation::Populate() {
David Brazdila4b8c212015-05-07 09:59:30 +0100681 DCHECK_EQ(blocks_.NumSetBits(), 0u) << "Loop information has already been populated";
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000682 // Populate this loop: starting with the back edge, recursively add predecessors
683 // that are not already part of that loop. Set the header as part of the loop
684 // to end the recursion.
685 // This is a recursive implementation of the algorithm described in
686 // "Advanced Compiler Design & Implementation" (Muchnick) p192.
David Brazdilc2e8af92016-04-05 17:15:19 +0100687 HGraph* graph = header_->GetGraph();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000688 blocks_.SetBit(header_->GetBlockId());
689 header_->SetInLoop(this);
David Brazdilc2e8af92016-04-05 17:15:19 +0100690
David Brazdil3f4a5222016-05-06 12:46:21 +0100691 bool is_irreducible_loop = HasBackEdgeNotDominatedByHeader();
David Brazdilc2e8af92016-04-05 17:15:19 +0100692
693 if (is_irreducible_loop) {
694 ArenaBitVector visited(graph->GetArena(),
695 graph->GetBlocks().size(),
696 /* expandable */ false,
697 kArenaAllocGraphBuilder);
David Brazdil5a620592016-05-05 11:27:03 +0100698 // Stop marking blocks at the loop header.
699 visited.SetBit(header_->GetBlockId());
700
David Brazdilc2e8af92016-04-05 17:15:19 +0100701 for (HBasicBlock* back_edge : GetBackEdges()) {
702 PopulateIrreducibleRecursive(back_edge, &visited);
703 }
704 } else {
705 for (HBasicBlock* back_edge : GetBackEdges()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000706 PopulateRecursive(back_edge);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100707 }
David Brazdila4b8c212015-05-07 09:59:30 +0100708 }
David Brazdilc2e8af92016-04-05 17:15:19 +0100709
Vladimir Markofd66c502016-04-18 15:37:01 +0100710 if (!is_irreducible_loop && graph->IsCompilingOsr()) {
711 // When compiling in OSR mode, all loops in the compiled method may be entered
712 // from the interpreter. We treat this OSR entry point just like an extra entry
713 // to an irreducible loop, so we need to mark the method's loops as irreducible.
714 // This does not apply to inlined loops which do not act as OSR entry points.
715 if (suspend_check_ == nullptr) {
716 // Just building the graph in OSR mode, this loop is not inlined. We never build an
717 // inner graph in OSR mode as we can do OSR transition only from the outer method.
718 is_irreducible_loop = true;
719 } else {
720 // Look at the suspend check's environment to determine if the loop was inlined.
721 DCHECK(suspend_check_->HasEnvironment());
722 if (!suspend_check_->GetEnvironment()->IsFromInlinedInvoke()) {
723 is_irreducible_loop = true;
724 }
725 }
726 }
727 if (is_irreducible_loop) {
David Brazdilc2e8af92016-04-05 17:15:19 +0100728 irreducible_ = true;
Nicolas Geoffrayd7c2fdc2016-05-10 14:35:34 +0100729 contains_irreducible_loop_ = true;
David Brazdilc2e8af92016-04-05 17:15:19 +0100730 graph->SetHasIrreducibleLoops(true);
731 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -0800732 graph->SetHasLoops(true);
David Brazdila4b8c212015-05-07 09:59:30 +0100733}
734
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100735HBasicBlock* HLoopInformation::GetPreHeader() const {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000736 HBasicBlock* block = header_->GetPredecessors()[0];
737 DCHECK(irreducible_ || (block == header_->GetDominator()));
738 return block;
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100739}
740
741bool HLoopInformation::Contains(const HBasicBlock& block) const {
742 return blocks_.IsBitSet(block.GetBlockId());
743}
744
745bool HLoopInformation::IsIn(const HLoopInformation& other) const {
746 return other.blocks_.IsBitSet(header_->GetBlockId());
747}
748
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800749bool HLoopInformation::IsDefinedOutOfTheLoop(HInstruction* instruction) const {
750 return !blocks_.IsBitSet(instruction->GetBlock()->GetBlockId());
Aart Bik73f1f3b2015-10-28 15:28:08 -0700751}
752
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100753size_t HLoopInformation::GetLifetimeEnd() const {
754 size_t last_position = 0;
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100755 for (HBasicBlock* back_edge : GetBackEdges()) {
756 last_position = std::max(back_edge->GetLifetimeEnd(), last_position);
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100757 }
758 return last_position;
759}
760
David Brazdil3f4a5222016-05-06 12:46:21 +0100761bool HLoopInformation::HasBackEdgeNotDominatedByHeader() const {
762 for (HBasicBlock* back_edge : GetBackEdges()) {
763 DCHECK(back_edge->GetDominator() != nullptr);
764 if (!header_->Dominates(back_edge)) {
765 return true;
766 }
767 }
768 return false;
769}
770
Anton Shaminf89381f2016-05-16 16:44:13 +0600771bool HLoopInformation::DominatesAllBackEdges(HBasicBlock* block) {
772 for (HBasicBlock* back_edge : GetBackEdges()) {
773 if (!block->Dominates(back_edge)) {
774 return false;
775 }
776 }
777 return true;
778}
779
David Sehrc757dec2016-11-04 15:48:34 -0700780
781bool HLoopInformation::HasExitEdge() const {
782 // Determine if this loop has at least one exit edge.
783 HBlocksInLoopReversePostOrderIterator it_loop(*this);
784 for (; !it_loop.Done(); it_loop.Advance()) {
785 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
786 if (!Contains(*successor)) {
787 return true;
788 }
789 }
790 }
791 return false;
792}
793
Nicolas Geoffray622d9c32014-05-12 16:11:02 +0100794bool HBasicBlock::Dominates(HBasicBlock* other) const {
795 // Walk up the dominator tree from `other`, to find out if `this`
796 // is an ancestor.
797 HBasicBlock* current = other;
798 while (current != nullptr) {
799 if (current == this) {
800 return true;
801 }
802 current = current->GetDominator();
803 }
804 return false;
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100805}
806
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100807static void UpdateInputsUsers(HInstruction* instruction) {
Vladimir Markoe9004912016-06-16 16:50:52 +0100808 HInputsRef inputs = instruction->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100809 for (size_t i = 0; i < inputs.size(); ++i) {
810 inputs[i]->AddUseAt(instruction, i);
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100811 }
812 // Environment should be created later.
813 DCHECK(!instruction->HasEnvironment());
814}
815
Roland Levillainccc07a92014-09-16 14:48:16 +0100816void HBasicBlock::ReplaceAndRemoveInstructionWith(HInstruction* initial,
817 HInstruction* replacement) {
818 DCHECK(initial->GetBlock() == this);
Mark Mendell805b3b52015-09-18 14:10:29 -0400819 if (initial->IsControlFlow()) {
820 // We can only replace a control flow instruction with another control flow instruction.
821 DCHECK(replacement->IsControlFlow());
822 DCHECK_EQ(replacement->GetId(), -1);
823 DCHECK_EQ(replacement->GetType(), Primitive::kPrimVoid);
824 DCHECK_EQ(initial->GetBlock(), this);
825 DCHECK_EQ(initial->GetType(), Primitive::kPrimVoid);
Vladimir Marko46817b82016-03-29 12:21:58 +0100826 DCHECK(initial->GetUses().empty());
827 DCHECK(initial->GetEnvUses().empty());
Mark Mendell805b3b52015-09-18 14:10:29 -0400828 replacement->SetBlock(this);
829 replacement->SetId(GetGraph()->GetNextInstructionId());
830 instructions_.InsertInstructionBefore(replacement, initial);
831 UpdateInputsUsers(replacement);
832 } else {
833 InsertInstructionBefore(replacement, initial);
834 initial->ReplaceWith(replacement);
835 }
Roland Levillainccc07a92014-09-16 14:48:16 +0100836 RemoveInstruction(initial);
837}
838
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100839static void Add(HInstructionList* instruction_list,
840 HBasicBlock* block,
841 HInstruction* instruction) {
Nicolas Geoffray787c3072014-03-17 10:20:19 +0000842 DCHECK(instruction->GetBlock() == nullptr);
Nicolas Geoffray43c86422014-03-18 11:58:24 +0000843 DCHECK_EQ(instruction->GetId(), -1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100844 instruction->SetBlock(block);
845 instruction->SetId(block->GetGraph()->GetNextInstructionId());
Nicolas Geoffray191c4b12014-10-07 14:14:27 +0100846 UpdateInputsUsers(instruction);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100847 instruction_list->AddInstruction(instruction);
848}
849
850void HBasicBlock::AddInstruction(HInstruction* instruction) {
851 Add(&instructions_, this, instruction);
852}
853
854void HBasicBlock::AddPhi(HPhi* phi) {
855 Add(&phis_, this, phi);
856}
857
David Brazdilc3d743f2015-04-22 13:40:50 +0100858void HBasicBlock::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
859 DCHECK(!cursor->IsPhi());
860 DCHECK(!instruction->IsPhi());
861 DCHECK_EQ(instruction->GetId(), -1);
862 DCHECK_NE(cursor->GetId(), -1);
863 DCHECK_EQ(cursor->GetBlock(), this);
864 DCHECK(!instruction->IsControlFlow());
865 instruction->SetBlock(this);
866 instruction->SetId(GetGraph()->GetNextInstructionId());
867 UpdateInputsUsers(instruction);
868 instructions_.InsertInstructionBefore(instruction, cursor);
869}
870
Guillaume "Vermeille" Sanchez2967ec62015-04-24 16:36:52 +0100871void HBasicBlock::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
872 DCHECK(!cursor->IsPhi());
873 DCHECK(!instruction->IsPhi());
874 DCHECK_EQ(instruction->GetId(), -1);
875 DCHECK_NE(cursor->GetId(), -1);
876 DCHECK_EQ(cursor->GetBlock(), this);
877 DCHECK(!instruction->IsControlFlow());
878 DCHECK(!cursor->IsControlFlow());
879 instruction->SetBlock(this);
880 instruction->SetId(GetGraph()->GetNextInstructionId());
881 UpdateInputsUsers(instruction);
882 instructions_.InsertInstructionAfter(instruction, cursor);
883}
884
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100885void HBasicBlock::InsertPhiAfter(HPhi* phi, HPhi* cursor) {
886 DCHECK_EQ(phi->GetId(), -1);
887 DCHECK_NE(cursor->GetId(), -1);
888 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100889 phi->SetBlock(this);
890 phi->SetId(GetGraph()->GetNextInstructionId());
891 UpdateInputsUsers(phi);
David Brazdilc3d743f2015-04-22 13:40:50 +0100892 phis_.InsertInstructionAfter(phi, cursor);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +0100893}
894
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100895static void Remove(HInstructionList* instruction_list,
896 HBasicBlock* block,
David Brazdil1abb4192015-02-17 18:33:36 +0000897 HInstruction* instruction,
898 bool ensure_safety) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100899 DCHECK_EQ(block, instruction->GetBlock());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100900 instruction->SetBlock(nullptr);
901 instruction_list->RemoveInstruction(instruction);
David Brazdil1abb4192015-02-17 18:33:36 +0000902 if (ensure_safety) {
Vladimir Marko46817b82016-03-29 12:21:58 +0100903 DCHECK(instruction->GetUses().empty());
904 DCHECK(instruction->GetEnvUses().empty());
David Brazdil1abb4192015-02-17 18:33:36 +0000905 RemoveAsUser(instruction);
906 }
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100907}
908
David Brazdil1abb4192015-02-17 18:33:36 +0000909void HBasicBlock::RemoveInstruction(HInstruction* instruction, bool ensure_safety) {
David Brazdilc7508e92015-04-27 13:28:57 +0100910 DCHECK(!instruction->IsPhi());
David Brazdil1abb4192015-02-17 18:33:36 +0000911 Remove(&instructions_, this, instruction, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100912}
913
David Brazdil1abb4192015-02-17 18:33:36 +0000914void HBasicBlock::RemovePhi(HPhi* phi, bool ensure_safety) {
915 Remove(&phis_, this, phi, ensure_safety);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100916}
917
David Brazdilc7508e92015-04-27 13:28:57 +0100918void HBasicBlock::RemoveInstructionOrPhi(HInstruction* instruction, bool ensure_safety) {
919 if (instruction->IsPhi()) {
920 RemovePhi(instruction->AsPhi(), ensure_safety);
921 } else {
922 RemoveInstruction(instruction, ensure_safety);
923 }
924}
925
Vladimir Marko71bf8092015-09-15 15:33:14 +0100926void HEnvironment::CopyFrom(const ArenaVector<HInstruction*>& locals) {
927 for (size_t i = 0; i < locals.size(); i++) {
928 HInstruction* instruction = locals[i];
Nicolas Geoffray8c0c91a2015-05-07 11:46:05 +0100929 SetRawEnvAt(i, instruction);
930 if (instruction != nullptr) {
931 instruction->AddEnvUseAt(this, i);
932 }
933 }
934}
935
David Brazdiled596192015-01-23 10:39:45 +0000936void HEnvironment::CopyFrom(HEnvironment* env) {
937 for (size_t i = 0; i < env->Size(); i++) {
938 HInstruction* instruction = env->GetInstructionAt(i);
939 SetRawEnvAt(i, instruction);
940 if (instruction != nullptr) {
941 instruction->AddEnvUseAt(this, i);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100942 }
David Brazdiled596192015-01-23 10:39:45 +0000943 }
944}
945
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700946void HEnvironment::CopyFromWithLoopPhiAdjustment(HEnvironment* env,
947 HBasicBlock* loop_header) {
948 DCHECK(loop_header->IsLoopHeader());
949 for (size_t i = 0; i < env->Size(); i++) {
950 HInstruction* instruction = env->GetInstructionAt(i);
951 SetRawEnvAt(i, instruction);
952 if (instruction == nullptr) {
953 continue;
954 }
955 if (instruction->IsLoopHeaderPhi() && (instruction->GetBlock() == loop_header)) {
956 // At the end of the loop pre-header, the corresponding value for instruction
957 // is the first input of the phi.
958 HInstruction* initial = instruction->AsPhi()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700959 SetRawEnvAt(i, initial);
960 initial->AddEnvUseAt(this, i);
961 } else {
962 instruction->AddEnvUseAt(this, i);
963 }
964 }
965}
966
David Brazdil1abb4192015-02-17 18:33:36 +0000967void HEnvironment::RemoveAsUserOfInput(size_t index) const {
Vladimir Marko46817b82016-03-29 12:21:58 +0100968 const HUserRecord<HEnvironment*>& env_use = vregs_[index];
969 HInstruction* user = env_use.GetInstruction();
970 auto before_env_use_node = env_use.GetBeforeUseNode();
971 user->env_uses_.erase_after(before_env_use_node);
972 user->FixUpUserRecordsAfterEnvUseRemoval(before_env_use_node);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100973}
974
Vladimir Marko5f7b58e2015-11-23 19:49:34 +0000975HInstruction::InstructionKind HInstruction::GetKind() const {
976 return GetKindInternal();
977}
978
Calin Juravle77520bc2015-01-12 18:45:46 +0000979HInstruction* HInstruction::GetNextDisregardingMoves() const {
980 HInstruction* next = GetNext();
981 while (next != nullptr && next->IsParallelMove()) {
982 next = next->GetNext();
983 }
984 return next;
985}
986
987HInstruction* HInstruction::GetPreviousDisregardingMoves() const {
988 HInstruction* previous = GetPrevious();
989 while (previous != nullptr && previous->IsParallelMove()) {
990 previous = previous->GetPrevious();
991 }
992 return previous;
993}
994
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +0100995void HInstructionList::AddInstruction(HInstruction* instruction) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +0000996 if (first_instruction_ == nullptr) {
997 DCHECK(last_instruction_ == nullptr);
998 first_instruction_ = last_instruction_ = instruction;
999 } else {
George Burgess IVa4b58ed2017-06-22 15:47:25 -07001000 DCHECK(last_instruction_ != nullptr);
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001001 last_instruction_->next_ = instruction;
1002 instruction->previous_ = last_instruction_;
1003 last_instruction_ = instruction;
1004 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001005}
1006
David Brazdilc3d743f2015-04-22 13:40:50 +01001007void HInstructionList::InsertInstructionBefore(HInstruction* instruction, HInstruction* cursor) {
1008 DCHECK(Contains(cursor));
1009 if (cursor == first_instruction_) {
1010 cursor->previous_ = instruction;
1011 instruction->next_ = cursor;
1012 first_instruction_ = instruction;
1013 } else {
1014 instruction->previous_ = cursor->previous_;
1015 instruction->next_ = cursor;
1016 cursor->previous_ = instruction;
1017 instruction->previous_->next_ = instruction;
1018 }
1019}
1020
1021void HInstructionList::InsertInstructionAfter(HInstruction* instruction, HInstruction* cursor) {
1022 DCHECK(Contains(cursor));
1023 if (cursor == last_instruction_) {
1024 cursor->next_ = instruction;
1025 instruction->previous_ = cursor;
1026 last_instruction_ = instruction;
1027 } else {
1028 instruction->next_ = cursor->next_;
1029 instruction->previous_ = cursor;
1030 cursor->next_ = instruction;
1031 instruction->next_->previous_ = instruction;
1032 }
1033}
1034
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001035void HInstructionList::RemoveInstruction(HInstruction* instruction) {
1036 if (instruction->previous_ != nullptr) {
1037 instruction->previous_->next_ = instruction->next_;
1038 }
1039 if (instruction->next_ != nullptr) {
1040 instruction->next_->previous_ = instruction->previous_;
1041 }
1042 if (instruction == first_instruction_) {
1043 first_instruction_ = instruction->next_;
1044 }
1045 if (instruction == last_instruction_) {
1046 last_instruction_ = instruction->previous_;
1047 }
1048}
1049
Roland Levillain6b469232014-09-25 10:10:38 +01001050bool HInstructionList::Contains(HInstruction* instruction) const {
1051 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1052 if (it.Current() == instruction) {
1053 return true;
1054 }
1055 }
1056 return false;
1057}
1058
Roland Levillainccc07a92014-09-16 14:48:16 +01001059bool HInstructionList::FoundBefore(const HInstruction* instruction1,
1060 const HInstruction* instruction2) const {
1061 DCHECK_EQ(instruction1->GetBlock(), instruction2->GetBlock());
1062 for (HInstructionIterator it(*this); !it.Done(); it.Advance()) {
1063 if (it.Current() == instruction1) {
1064 return true;
1065 }
1066 if (it.Current() == instruction2) {
1067 return false;
1068 }
1069 }
1070 LOG(FATAL) << "Did not find an order between two instructions of the same block.";
1071 return true;
1072}
1073
Roland Levillain6c82d402014-10-13 16:10:27 +01001074bool HInstruction::StrictlyDominates(HInstruction* other_instruction) const {
1075 if (other_instruction == this) {
1076 // An instruction does not strictly dominate itself.
1077 return false;
1078 }
Roland Levillainccc07a92014-09-16 14:48:16 +01001079 HBasicBlock* block = GetBlock();
1080 HBasicBlock* other_block = other_instruction->GetBlock();
1081 if (block != other_block) {
1082 return GetBlock()->Dominates(other_instruction->GetBlock());
1083 } else {
1084 // If both instructions are in the same block, ensure this
1085 // instruction comes before `other_instruction`.
1086 if (IsPhi()) {
1087 if (!other_instruction->IsPhi()) {
1088 // Phis appear before non phi-instructions so this instruction
1089 // dominates `other_instruction`.
1090 return true;
1091 } else {
1092 // There is no order among phis.
1093 LOG(FATAL) << "There is no dominance between phis of a same block.";
1094 return false;
1095 }
1096 } else {
1097 // `this` is not a phi.
1098 if (other_instruction->IsPhi()) {
1099 // Phis appear before non phi-instructions so this instruction
1100 // does not dominate `other_instruction`.
1101 return false;
1102 } else {
1103 // Check whether this instruction comes before
1104 // `other_instruction` in the instruction list.
1105 return block->GetInstructions().FoundBefore(this, other_instruction);
1106 }
1107 }
1108 }
1109}
1110
Vladimir Markocac5a7e2016-02-22 10:39:50 +00001111void HInstruction::RemoveEnvironment() {
1112 RemoveEnvironmentUses(this);
1113 environment_ = nullptr;
1114}
1115
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001116void HInstruction::ReplaceWith(HInstruction* other) {
Nicolas Geoffraya7062e02014-05-22 12:50:17 +01001117 DCHECK(other != nullptr);
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001118 // Note: fixup_end remains valid across splice_after().
1119 auto fixup_end = other->uses_.empty() ? other->uses_.begin() : ++other->uses_.begin();
1120 other->uses_.splice_after(other->uses_.before_begin(), uses_);
1121 other->FixUpUserRecordsAfterUseInsertion(fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001122
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001123 // Note: env_fixup_end remains valid across splice_after().
1124 auto env_fixup_end =
1125 other->env_uses_.empty() ? other->env_uses_.begin() : ++other->env_uses_.begin();
1126 other->env_uses_.splice_after(other->env_uses_.before_begin(), env_uses_);
1127 other->FixUpUserRecordsAfterEnvUseInsertion(env_fixup_end);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001128
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001129 DCHECK(uses_.empty());
1130 DCHECK(env_uses_.empty());
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001131}
1132
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001133void HInstruction::ReplaceUsesDominatedBy(HInstruction* dominator, HInstruction* replacement) {
1134 const HUseList<HInstruction*>& uses = GetUses();
1135 for (auto it = uses.begin(), end = uses.end(); it != end; /* ++it below */) {
1136 HInstruction* user = it->GetUser();
1137 size_t index = it->GetIndex();
1138 // Increment `it` now because `*it` may disappear thanks to user->ReplaceInput().
1139 ++it;
1140 if (dominator->StrictlyDominates(user)) {
1141 user->ReplaceInput(replacement, index);
1142 }
1143 }
1144}
1145
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001146void HInstruction::ReplaceInput(HInstruction* replacement, size_t index) {
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001147 HUserRecord<HInstruction*> input_use = InputRecordAt(index);
Vladimir Markoc6b56272016-04-20 18:45:25 +01001148 if (input_use.GetInstruction() == replacement) {
1149 // Nothing to do.
1150 return;
1151 }
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001152 HUseList<HInstruction*>::iterator before_use_node = input_use.GetBeforeUseNode();
Vladimir Marko3c19d3e2016-04-19 14:36:35 +01001153 // Note: fixup_end remains valid across splice_after().
1154 auto fixup_end =
1155 replacement->uses_.empty() ? replacement->uses_.begin() : ++replacement->uses_.begin();
1156 replacement->uses_.splice_after(replacement->uses_.before_begin(),
1157 input_use.GetInstruction()->uses_,
1158 before_use_node);
1159 replacement->FixUpUserRecordsAfterUseInsertion(fixup_end);
1160 input_use.GetInstruction()->FixUpUserRecordsAfterUseRemoval(before_use_node);
Nicolas Geoffray102cbed2014-10-15 18:31:05 +01001161}
1162
Nicolas Geoffray39468442014-09-02 15:17:15 +01001163size_t HInstruction::EnvironmentSize() const {
1164 return HasEnvironment() ? environment_->Size() : 0;
1165}
1166
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001167void HVariableInputSizeInstruction::AddInput(HInstruction* input) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001168 DCHECK(input->GetBlock() != nullptr);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001169 inputs_.push_back(HUserRecord<HInstruction*>(input));
1170 input->AddUseAt(this, inputs_.size() - 1);
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001171}
1172
Mingyao Yanga9dbe832016-12-15 12:02:53 -08001173void HVariableInputSizeInstruction::InsertInputAt(size_t index, HInstruction* input) {
1174 inputs_.insert(inputs_.begin() + index, HUserRecord<HInstruction*>(input));
1175 input->AddUseAt(this, index);
1176 // Update indexes in use nodes of inputs that have been pushed further back by the insert().
1177 for (size_t i = index + 1u, e = inputs_.size(); i < e; ++i) {
1178 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i - 1u);
1179 inputs_[i].GetUseNode()->SetIndex(i);
1180 }
1181}
1182
1183void HVariableInputSizeInstruction::RemoveInputAt(size_t index) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001184 RemoveAsUserOfInput(index);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001185 inputs_.erase(inputs_.begin() + index);
Vladimir Marko372f10e2016-05-17 16:30:10 +01001186 // Update indexes in use nodes of inputs that have been pulled forward by the erase().
1187 for (size_t i = index, e = inputs_.size(); i < e; ++i) {
1188 DCHECK_EQ(inputs_[i].GetUseNode()->GetIndex(), i + 1u);
1189 inputs_[i].GetUseNode()->SetIndex(i);
Nicolas Geoffray5d7b7f82015-04-28 00:52:43 +01001190 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001191}
1192
Igor Murashkind01745e2017-04-05 16:40:31 -07001193void HVariableInputSizeInstruction::RemoveAllInputs() {
1194 RemoveAsUserOfAllInputs();
1195 DCHECK(!HasNonEnvironmentUses());
1196
1197 inputs_.clear();
1198 DCHECK_EQ(0u, InputCount());
1199}
1200
Igor Murashkin6ef45672017-08-08 13:59:55 -07001201size_t HConstructorFence::RemoveConstructorFences(HInstruction* instruction) {
Igor Murashkind01745e2017-04-05 16:40:31 -07001202 DCHECK(instruction->GetBlock() != nullptr);
1203 // Removing constructor fences only makes sense for instructions with an object return type.
1204 DCHECK_EQ(Primitive::kPrimNot, instruction->GetType());
1205
Igor Murashkin6ef45672017-08-08 13:59:55 -07001206 // Return how many instructions were removed for statistic purposes.
1207 size_t remove_count = 0;
1208
Igor Murashkind01745e2017-04-05 16:40:31 -07001209 // Efficient implementation that simultaneously (in one pass):
1210 // * Scans the uses list for all constructor fences.
1211 // * Deletes that constructor fence from the uses list of `instruction`.
1212 // * Deletes `instruction` from the constructor fence's inputs.
1213 // * Deletes the constructor fence if it now has 0 inputs.
1214
1215 const HUseList<HInstruction*>& uses = instruction->GetUses();
1216 // Warning: Although this is "const", we might mutate the list when calling RemoveInputAt.
1217 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
1218 const HUseListNode<HInstruction*>& use_node = *it;
1219 HInstruction* const use_instruction = use_node.GetUser();
1220
1221 // Advance the iterator immediately once we fetch the use_node.
1222 // Warning: If the input is removed, the current iterator becomes invalid.
1223 ++it;
1224
1225 if (use_instruction->IsConstructorFence()) {
1226 HConstructorFence* ctor_fence = use_instruction->AsConstructorFence();
1227 size_t input_index = use_node.GetIndex();
1228
1229 // Process the candidate instruction for removal
1230 // from the graph.
1231
1232 // Constructor fence instructions are never
1233 // used by other instructions.
1234 //
1235 // If we wanted to make this more generic, it
1236 // could be a runtime if statement.
1237 DCHECK(!ctor_fence->HasUses());
1238
1239 // A constructor fence's return type is "kPrimVoid"
1240 // and therefore it can't have any environment uses.
1241 DCHECK(!ctor_fence->HasEnvironmentUses());
1242
1243 // Remove the inputs first, otherwise removing the instruction
1244 // will try to remove its uses while we are already removing uses
1245 // and this operation will fail.
1246 DCHECK_EQ(instruction, ctor_fence->InputAt(input_index));
1247
1248 // Removing the input will also remove the `use_node`.
1249 // (Do not look at `use_node` after this, it will be a dangling reference).
1250 ctor_fence->RemoveInputAt(input_index);
1251
1252 // Once all inputs are removed, the fence is considered dead and
1253 // is removed.
1254 if (ctor_fence->InputCount() == 0u) {
1255 ctor_fence->GetBlock()->RemoveInstruction(ctor_fence);
Igor Murashkin6ef45672017-08-08 13:59:55 -07001256 ++remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001257 }
1258 }
1259 }
1260
1261 if (kIsDebugBuild) {
1262 // Post-condition checks:
1263 // * None of the uses of `instruction` are a constructor fence.
1264 // * The `instruction` itself did not get removed from a block.
1265 for (const HUseListNode<HInstruction*>& use_node : instruction->GetUses()) {
1266 CHECK(!use_node.GetUser()->IsConstructorFence());
1267 }
1268 CHECK(instruction->GetBlock() != nullptr);
1269 }
Igor Murashkin6ef45672017-08-08 13:59:55 -07001270
1271 return remove_count;
Igor Murashkind01745e2017-04-05 16:40:31 -07001272}
1273
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001274HInstruction* HConstructorFence::GetAssociatedAllocation() {
1275 HInstruction* new_instance_inst = GetPrevious();
1276 // Check if the immediately preceding instruction is a new-instance/new-array.
1277 // Otherwise this fence is for protecting final fields.
1278 if (new_instance_inst != nullptr &&
1279 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
1280 // TODO: Need to update this code to handle multiple inputs.
1281 DCHECK_EQ(InputCount(), 1u);
1282 return new_instance_inst;
1283 } else {
1284 return nullptr;
1285 }
1286}
1287
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001288#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001289void H##name::Accept(HGraphVisitor* visitor) { \
1290 visitor->Visit##name(this); \
1291}
1292
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001293FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001294
1295#undef DEFINE_ACCEPT
1296
1297void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001298 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1299 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001300 if (block != nullptr) {
1301 VisitBasicBlock(block);
1302 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001303 }
1304}
1305
Roland Levillain633021e2014-10-01 14:12:25 +01001306void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001307 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1308 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001309 }
1310}
1311
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001312void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001313 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001314 it.Current()->Accept(this);
1315 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001316 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001317 it.Current()->Accept(this);
1318 }
1319}
1320
Mark Mendelle82549b2015-05-06 10:55:34 -04001321HConstant* HTypeConversion::TryStaticEvaluation() const {
1322 HGraph* graph = GetBlock()->GetGraph();
1323 if (GetInput()->IsIntConstant()) {
1324 int32_t value = GetInput()->AsIntConstant()->GetValue();
1325 switch (GetResultType()) {
1326 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001327 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001328 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001329 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001330 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001331 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001332 default:
1333 return nullptr;
1334 }
1335 } else if (GetInput()->IsLongConstant()) {
1336 int64_t value = GetInput()->AsLongConstant()->GetValue();
1337 switch (GetResultType()) {
1338 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001339 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001340 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001341 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001342 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001343 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001344 default:
1345 return nullptr;
1346 }
1347 } else if (GetInput()->IsFloatConstant()) {
1348 float value = GetInput()->AsFloatConstant()->GetValue();
1349 switch (GetResultType()) {
1350 case Primitive::kPrimInt:
1351 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001352 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001353 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001354 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001355 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001356 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1357 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001358 case Primitive::kPrimLong:
1359 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001360 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001361 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001362 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001363 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001364 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1365 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001366 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001367 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001368 default:
1369 return nullptr;
1370 }
1371 } else if (GetInput()->IsDoubleConstant()) {
1372 double value = GetInput()->AsDoubleConstant()->GetValue();
1373 switch (GetResultType()) {
1374 case Primitive::kPrimInt:
1375 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001376 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001377 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001378 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001379 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001380 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1381 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001382 case Primitive::kPrimLong:
1383 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001384 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001385 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001386 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001387 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001388 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1389 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001390 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001391 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001392 default:
1393 return nullptr;
1394 }
1395 }
1396 return nullptr;
1397}
1398
Roland Levillain9240d6a2014-10-20 16:47:04 +01001399HConstant* HUnaryOperation::TryStaticEvaluation() const {
1400 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001401 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001402 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001403 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001404 } else if (kEnableFloatingPointStaticEvaluation) {
1405 if (GetInput()->IsFloatConstant()) {
1406 return Evaluate(GetInput()->AsFloatConstant());
1407 } else if (GetInput()->IsDoubleConstant()) {
1408 return Evaluate(GetInput()->AsDoubleConstant());
1409 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001410 }
1411 return nullptr;
1412}
1413
1414HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001415 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1416 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001417 } else if (GetLeft()->IsLongConstant()) {
1418 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001419 // The binop(long, int) case is only valid for shifts and rotations.
1420 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001421 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1422 } else if (GetRight()->IsLongConstant()) {
1423 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001424 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001425 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001426 // The binop(null, null) case is only valid for equal and not-equal conditions.
1427 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001428 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001429 } else if (kEnableFloatingPointStaticEvaluation) {
1430 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1431 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1432 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1433 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1434 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001435 }
1436 return nullptr;
1437}
Dave Allison20dfc792014-06-16 20:44:29 -07001438
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001439HConstant* HBinaryOperation::GetConstantRight() const {
1440 if (GetRight()->IsConstant()) {
1441 return GetRight()->AsConstant();
1442 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1443 return GetLeft()->AsConstant();
1444 } else {
1445 return nullptr;
1446 }
1447}
1448
1449// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001450// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001451HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1452 HInstruction* most_constant_right = GetConstantRight();
1453 if (most_constant_right == nullptr) {
1454 return nullptr;
1455 } else if (most_constant_right == GetLeft()) {
1456 return GetRight();
1457 } else {
1458 return GetLeft();
1459 }
1460}
1461
Roland Levillain31dd3d62016-02-16 12:21:02 +00001462std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1463 switch (rhs) {
1464 case ComparisonBias::kNoBias:
1465 return os << "no_bias";
1466 case ComparisonBias::kGtBias:
1467 return os << "gt_bias";
1468 case ComparisonBias::kLtBias:
1469 return os << "lt_bias";
1470 default:
1471 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1472 UNREACHABLE();
1473 }
1474}
1475
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001476bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1477 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001478}
1479
Vladimir Marko372f10e2016-05-17 16:30:10 +01001480bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001481 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001482 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001483 if (!InstructionDataEquals(other)) return false;
1484 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001485 HConstInputsRef inputs = GetInputs();
1486 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001487 if (inputs.size() != other_inputs.size()) return false;
1488 for (size_t i = 0; i != inputs.size(); ++i) {
1489 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001490 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001491
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001492 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001493 return true;
1494}
1495
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001496std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1497#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1498 switch (rhs) {
1499 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1500 default:
1501 os << "Unknown instruction kind " << static_cast<int>(rhs);
1502 break;
1503 }
1504#undef DECLARE_CASE
1505 return os;
1506}
1507
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001508void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1509 if (do_checks) {
1510 DCHECK(!IsPhi());
1511 DCHECK(!IsControlFlow());
1512 DCHECK(CanBeMoved() ||
1513 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1514 IsShouldDeoptimizeFlag());
1515 DCHECK(!cursor->IsPhi());
1516 }
David Brazdild6c205e2016-06-07 14:20:52 +01001517
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001518 next_->previous_ = previous_;
1519 if (previous_ != nullptr) {
1520 previous_->next_ = next_;
1521 }
1522 if (block_->instructions_.first_instruction_ == this) {
1523 block_->instructions_.first_instruction_ = next_;
1524 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001525 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001526
1527 previous_ = cursor->previous_;
1528 if (previous_ != nullptr) {
1529 previous_->next_ = this;
1530 }
1531 next_ = cursor;
1532 cursor->previous_ = this;
1533 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001534
1535 if (block_->instructions_.first_instruction_ == cursor) {
1536 block_->instructions_.first_instruction_ = this;
1537 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001538}
1539
Vladimir Markofb337ea2015-11-25 15:25:10 +00001540void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1541 DCHECK(!CanThrow());
1542 DCHECK(!HasSideEffects());
1543 DCHECK(!HasEnvironmentUses());
1544 DCHECK(HasNonEnvironmentUses());
1545 DCHECK(!IsPhi()); // Makes no sense for Phi.
1546 DCHECK_EQ(InputCount(), 0u);
1547
1548 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001549 auto uses_it = GetUses().begin();
1550 auto uses_end = GetUses().end();
1551 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1552 ++uses_it;
1553 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1554 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001555 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001556 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001557 // This instruction has uses in two or more blocks. Find the common dominator.
1558 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001559 for (; uses_it != uses_end; ++uses_it) {
1560 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001561 }
1562 target_block = finder.Get();
1563 DCHECK(target_block != nullptr);
1564 }
1565 // Move to the first dominator not in a loop.
1566 while (target_block->IsInLoop()) {
1567 target_block = target_block->GetDominator();
1568 DCHECK(target_block != nullptr);
1569 }
1570
1571 // Find insertion position.
1572 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001573 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1574 if (use.GetUser()->GetBlock() == target_block &&
1575 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1576 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001577 }
1578 }
1579 if (insert_pos == nullptr) {
1580 // No user in `target_block`, insert before the control flow instruction.
1581 insert_pos = target_block->GetLastInstruction();
1582 DCHECK(insert_pos->IsControlFlow());
1583 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1584 if (insert_pos->IsIf()) {
1585 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1586 if (if_input == insert_pos->GetPrevious()) {
1587 insert_pos = if_input;
1588 }
1589 }
1590 }
1591 MoveBefore(insert_pos);
1592}
1593
David Brazdilfc6a86a2015-06-26 10:33:45 +00001594HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001595 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001596 DCHECK_EQ(cursor->GetBlock(), this);
1597
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001598 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1599 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001600 new_block->instructions_.first_instruction_ = cursor;
1601 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1602 instructions_.last_instruction_ = cursor->previous_;
1603 if (cursor->previous_ == nullptr) {
1604 instructions_.first_instruction_ = nullptr;
1605 } else {
1606 cursor->previous_->next_ = nullptr;
1607 cursor->previous_ = nullptr;
1608 }
1609
1610 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001611 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001612
Vladimir Marko60584552015-09-03 13:35:12 +00001613 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001614 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001615 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001616 new_block->successors_.swap(successors_);
1617 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001618 AddSuccessor(new_block);
1619
David Brazdil56e1acc2015-06-30 15:41:36 +01001620 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001621 return new_block;
1622}
1623
David Brazdild7558da2015-09-22 13:04:14 +01001624HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001625 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001626 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1627
1628 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1629
1630 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001631 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1632 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001633 new_block->predecessors_.swap(predecessors_);
1634 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001635 AddPredecessor(new_block);
1636
1637 GetGraph()->AddBlock(new_block);
1638 return new_block;
1639}
1640
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001641HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1642 DCHECK_EQ(cursor->GetBlock(), this);
1643
1644 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1645 cursor->GetDexPc());
1646 new_block->instructions_.first_instruction_ = cursor;
1647 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1648 instructions_.last_instruction_ = cursor->previous_;
1649 if (cursor->previous_ == nullptr) {
1650 instructions_.first_instruction_ = nullptr;
1651 } else {
1652 cursor->previous_->next_ = nullptr;
1653 cursor->previous_ = nullptr;
1654 }
1655
1656 new_block->instructions_.SetBlockOfInstructions(new_block);
1657
1658 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001659 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1660 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001661 new_block->successors_.swap(successors_);
1662 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001663
1664 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1665 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001666 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001667 new_block->dominated_blocks_.swap(dominated_blocks_);
1668 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001669 return new_block;
1670}
1671
1672HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001673 DCHECK(!cursor->IsControlFlow());
1674 DCHECK_NE(instructions_.last_instruction_, cursor);
1675 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001676
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001677 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1678 new_block->instructions_.first_instruction_ = cursor->GetNext();
1679 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1680 cursor->next_->previous_ = nullptr;
1681 cursor->next_ = nullptr;
1682 instructions_.last_instruction_ = cursor;
1683
1684 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001685 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001686 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001687 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001688 new_block->successors_.swap(successors_);
1689 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001690
Vladimir Marko60584552015-09-03 13:35:12 +00001691 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001692 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001693 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001694 new_block->dominated_blocks_.swap(dominated_blocks_);
1695 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001696 return new_block;
1697}
1698
David Brazdilec16f792015-08-19 15:04:01 +01001699const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001700 if (EndsWithTryBoundary()) {
1701 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1702 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001703 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001704 return try_boundary;
1705 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001706 DCHECK(IsTryBlock());
1707 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001708 return nullptr;
1709 }
David Brazdilec16f792015-08-19 15:04:01 +01001710 } else if (IsTryBlock()) {
1711 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001712 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001713 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001714 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001715}
1716
David Brazdild7558da2015-09-22 13:04:14 +01001717bool HBasicBlock::HasThrowingInstructions() const {
1718 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1719 if (it.Current()->CanThrow()) {
1720 return true;
1721 }
1722 }
1723 return false;
1724}
1725
David Brazdilfc6a86a2015-06-26 10:33:45 +00001726static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1727 return block.GetPhis().IsEmpty()
1728 && !block.GetInstructions().IsEmpty()
1729 && block.GetFirstInstruction() == block.GetLastInstruction();
1730}
1731
David Brazdil46e2a392015-03-16 17:31:52 +00001732bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001733 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1734}
1735
1736bool HBasicBlock::IsSingleTryBoundary() const {
1737 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001738}
1739
David Brazdil8d5b8b22015-03-24 10:51:52 +00001740bool HBasicBlock::EndsWithControlFlowInstruction() const {
1741 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1742}
1743
David Brazdilb2bd1c52015-03-25 11:17:37 +00001744bool HBasicBlock::EndsWithIf() const {
1745 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1746}
1747
David Brazdilffee3d32015-07-06 11:48:53 +01001748bool HBasicBlock::EndsWithTryBoundary() const {
1749 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1750}
1751
David Brazdilb2bd1c52015-03-25 11:17:37 +00001752bool HBasicBlock::HasSinglePhi() const {
1753 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1754}
1755
David Brazdild26a4112015-11-10 11:07:31 +00001756ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1757 if (EndsWithTryBoundary()) {
1758 // The normal-flow successor of HTryBoundary is always stored at index zero.
1759 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1760 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1761 } else {
1762 // All successors of blocks not ending with TryBoundary are normal.
1763 return ArrayRef<HBasicBlock* const>(successors_);
1764 }
1765}
1766
1767ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1768 if (EndsWithTryBoundary()) {
1769 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1770 } else {
1771 // Blocks not ending with TryBoundary do not have exceptional successors.
1772 return ArrayRef<HBasicBlock* const>();
1773 }
1774}
1775
David Brazdilffee3d32015-07-06 11:48:53 +01001776bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001777 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1778 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1779
1780 size_t length = handlers1.size();
1781 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001782 return false;
1783 }
1784
David Brazdilb618ade2015-07-29 10:31:29 +01001785 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001786 for (size_t i = 0; i < length; ++i) {
1787 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001788 return false;
1789 }
1790 }
1791 return true;
1792}
1793
David Brazdil2d7352b2015-04-20 14:52:42 +01001794size_t HInstructionList::CountSize() const {
1795 size_t size = 0;
1796 HInstruction* current = first_instruction_;
1797 for (; current != nullptr; current = current->GetNext()) {
1798 size++;
1799 }
1800 return size;
1801}
1802
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001803void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1804 for (HInstruction* current = first_instruction_;
1805 current != nullptr;
1806 current = current->GetNext()) {
1807 current->SetBlock(block);
1808 }
1809}
1810
1811void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1812 DCHECK(Contains(cursor));
1813 if (!instruction_list.IsEmpty()) {
1814 if (cursor == last_instruction_) {
1815 last_instruction_ = instruction_list.last_instruction_;
1816 } else {
1817 cursor->next_->previous_ = instruction_list.last_instruction_;
1818 }
1819 instruction_list.last_instruction_->next_ = cursor->next_;
1820 cursor->next_ = instruction_list.first_instruction_;
1821 instruction_list.first_instruction_->previous_ = cursor;
1822 }
1823}
1824
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001825void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1826 DCHECK(Contains(cursor));
1827 if (!instruction_list.IsEmpty()) {
1828 if (cursor == first_instruction_) {
1829 first_instruction_ = instruction_list.first_instruction_;
1830 } else {
1831 cursor->previous_->next_ = instruction_list.first_instruction_;
1832 }
1833 instruction_list.last_instruction_->next_ = cursor;
1834 instruction_list.first_instruction_->previous_ = cursor->previous_;
1835 cursor->previous_ = instruction_list.last_instruction_;
1836 }
1837}
1838
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001839void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001840 if (IsEmpty()) {
1841 first_instruction_ = instruction_list.first_instruction_;
1842 last_instruction_ = instruction_list.last_instruction_;
1843 } else {
1844 AddAfter(last_instruction_, instruction_list);
1845 }
1846}
1847
David Brazdil04ff4e82015-12-10 13:54:52 +00001848// Should be called on instructions in a dead block in post order. This method
1849// assumes `insn` has been removed from all users with the exception of catch
1850// phis because of missing exceptional edges in the graph. It removes the
1851// instruction from catch phi uses, together with inputs of other catch phis in
1852// the catch block at the same index, as these must be dead too.
1853static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1854 DCHECK(!insn->HasEnvironmentUses());
1855 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001856 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1857 size_t use_index = use.GetIndex();
1858 HBasicBlock* user_block = use.GetUser()->GetBlock();
1859 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001860 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1861 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1862 }
1863 }
1864}
1865
David Brazdil2d7352b2015-04-20 14:52:42 +01001866void HBasicBlock::DisconnectAndDelete() {
1867 // Dominators must be removed after all the blocks they dominate. This way
1868 // a loop header is removed last, a requirement for correct loop information
1869 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001870 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001871
David Brazdil9eeebf62016-03-24 11:18:15 +00001872 // The following steps gradually remove the block from all its dependants in
1873 // post order (b/27683071).
1874
1875 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1876 // We need to do this before step (4) which destroys the predecessor list.
1877 HBasicBlock* loop_update_start = this;
1878 if (IsLoopHeader()) {
1879 HLoopInformation* loop_info = GetLoopInformation();
1880 // All other blocks in this loop should have been removed because the header
1881 // was their dominator.
1882 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1883 DCHECK(!loop_info->IsIrreducible());
1884 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1885 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1886 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001887 }
1888
David Brazdil9eeebf62016-03-24 11:18:15 +00001889 // (2) Disconnect the block from its successors and update their phis.
1890 for (HBasicBlock* successor : successors_) {
1891 // Delete this block from the list of predecessors.
1892 size_t this_index = successor->GetPredecessorIndexOf(this);
1893 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1894
1895 // Check that `successor` has other predecessors, otherwise `this` is the
1896 // dominator of `successor` which violates the order DCHECKed at the top.
1897 DCHECK(!successor->predecessors_.empty());
1898
1899 // Remove this block's entries in the successor's phis. Skip exceptional
1900 // successors because catch phi inputs do not correspond to predecessor
1901 // blocks but throwing instructions. The inputs of the catch phis will be
1902 // updated in step (3).
1903 if (!successor->IsCatchBlock()) {
1904 if (successor->predecessors_.size() == 1u) {
1905 // The successor has just one predecessor left. Replace phis with the only
1906 // remaining input.
1907 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1908 HPhi* phi = phi_it.Current()->AsPhi();
1909 phi->ReplaceWith(phi->InputAt(1 - this_index));
1910 successor->RemovePhi(phi);
1911 }
1912 } else {
1913 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1914 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1915 }
1916 }
1917 }
1918 }
1919 successors_.clear();
1920
1921 // (3) Remove instructions and phis. Instructions should have no remaining uses
1922 // except in catch phis. If an instruction is used by a catch phi at `index`,
1923 // remove `index`-th input of all phis in the catch block since they are
1924 // guaranteed dead. Note that we may miss dead inputs this way but the
1925 // graph will always remain consistent.
1926 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1927 HInstruction* insn = it.Current();
1928 RemoveUsesOfDeadInstruction(insn);
1929 RemoveInstruction(insn);
1930 }
1931 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1932 HPhi* insn = it.Current()->AsPhi();
1933 RemoveUsesOfDeadInstruction(insn);
1934 RemovePhi(insn);
1935 }
1936
1937 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001938 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001939 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001940 // We should not see any back edges as they would have been removed by step (3).
1941 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1942
David Brazdil2d7352b2015-04-20 14:52:42 +01001943 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001944 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1945 // This block is the only normal-flow successor of the TryBoundary which
1946 // makes `predecessor` dead. Since DCE removes blocks in post order,
1947 // exception handlers of this TryBoundary were already visited and any
1948 // remaining handlers therefore must be live. We remove `predecessor` from
1949 // their list of predecessors.
1950 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1951 while (predecessor->GetSuccessors().size() > 1) {
1952 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1953 DCHECK(handler->IsCatchBlock());
1954 predecessor->RemoveSuccessor(handler);
1955 handler->RemovePredecessor(predecessor);
1956 }
1957 }
1958
David Brazdil2d7352b2015-04-20 14:52:42 +01001959 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04001960 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
1961 if (num_pred_successors == 1u) {
1962 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001963 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
1964 // successor. Replace those with a HGoto.
1965 DCHECK(last_instruction->IsIf() ||
1966 last_instruction->IsPackedSwitch() ||
1967 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001968 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001969 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04001970 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01001971 // The predecessor has no remaining successors and therefore must be dead.
1972 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00001973 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04001974 predecessor->RemoveInstruction(last_instruction);
1975 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001976 // There are multiple successors left. The removed block might be a successor
1977 // of a PackedSwitch which will be completely removed (perhaps replaced with
1978 // a Goto), or we are deleting a catch block from a TryBoundary. In either
1979 // case, leave `last_instruction` as is for now.
1980 DCHECK(last_instruction->IsPackedSwitch() ||
1981 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01001982 }
David Brazdil46e2a392015-03-16 17:31:52 +00001983 }
Vladimir Marko60584552015-09-03 13:35:12 +00001984 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01001985
David Brazdil9eeebf62016-03-24 11:18:15 +00001986 // (5) Remove the block from all loops it is included in. Skip the inner-most
1987 // loop if this is the loop header (see definition of `loop_update_start`)
1988 // because the loop header's predecessor list has been destroyed in step (4).
1989 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
1990 HLoopInformation* loop_info = it.Current();
1991 loop_info->Remove(this);
1992 if (loop_info->IsBackEdge(*this)) {
1993 // If this was the last back edge of the loop, we deliberately leave the
1994 // loop in an inconsistent state and will fail GraphChecker unless the
1995 // entire loop is removed during the pass.
1996 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01001997 }
1998 }
David Brazdil2d7352b2015-04-20 14:52:42 +01001999
David Brazdil9eeebf62016-03-24 11:18:15 +00002000 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002001 dominator_->RemoveDominatedBlock(this);
2002 SetDominator(nullptr);
2003
David Brazdil9eeebf62016-03-24 11:18:15 +00002004 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002005 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002006 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002007}
2008
Aart Bik6b69e0a2017-01-11 10:20:43 -08002009void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2010 DCHECK(EndsWithControlFlowInstruction());
2011 RemoveInstruction(GetLastInstruction());
2012 instructions_.Add(other->GetInstructions());
2013 other->instructions_.SetBlockOfInstructions(this);
2014 other->instructions_.Clear();
2015}
2016
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002017void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002018 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002019 DCHECK(ContainsElement(dominated_blocks_, other));
2020 DCHECK_EQ(GetSingleSuccessor(), other);
2021 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002022 DCHECK(other->GetPhis().IsEmpty());
2023
David Brazdil2d7352b2015-04-20 14:52:42 +01002024 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002025 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002026
David Brazdil2d7352b2015-04-20 14:52:42 +01002027 // Remove `other` from the loops it is included in.
2028 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2029 HLoopInformation* loop_info = it.Current();
2030 loop_info->Remove(other);
2031 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002032 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002033 }
2034 }
2035
2036 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002037 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002038 for (HBasicBlock* successor : other->GetSuccessors()) {
2039 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002040 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002041 successors_.swap(other->successors_);
2042 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002043
David Brazdil2d7352b2015-04-20 14:52:42 +01002044 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002045 RemoveDominatedBlock(other);
2046 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002047 dominated->SetDominator(this);
2048 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002049 dominated_blocks_.insert(
2050 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002051 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002052 other->dominator_ = nullptr;
2053
2054 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002055 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002056
2057 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002058 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002059 other->SetGraph(nullptr);
2060}
2061
2062void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2063 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002064 DCHECK(GetDominatedBlocks().empty());
2065 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002066 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002067 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002068 DCHECK(other->GetPhis().IsEmpty());
2069 DCHECK(!other->IsInLoop());
2070
2071 // Move instructions from `other` to `this`.
2072 instructions_.Add(other->GetInstructions());
2073 other->instructions_.SetBlockOfInstructions(this);
2074
2075 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002076 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002077 for (HBasicBlock* successor : other->GetSuccessors()) {
2078 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002079 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002080 successors_.swap(other->successors_);
2081 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002082
2083 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002084 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002085 dominated->SetDominator(this);
2086 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002087 dominated_blocks_.insert(
2088 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002089 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002090 other->dominator_ = nullptr;
2091 other->graph_ = nullptr;
2092}
2093
2094void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002095 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002096 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002097 predecessor->ReplaceSuccessor(this, other);
2098 }
Vladimir Marko60584552015-09-03 13:35:12 +00002099 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002100 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002101 successor->ReplacePredecessor(this, other);
2102 }
Vladimir Marko60584552015-09-03 13:35:12 +00002103 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2104 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002105 }
2106 GetDominator()->ReplaceDominatedBlock(this, other);
2107 other->SetDominator(GetDominator());
2108 dominator_ = nullptr;
2109 graph_ = nullptr;
2110}
2111
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002112void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002113 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002114 DCHECK(block->GetSuccessors().empty());
2115 DCHECK(block->GetPredecessors().empty());
2116 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002117 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002118 DCHECK(block->GetInstructions().IsEmpty());
2119 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002120
David Brazdilc7af85d2015-05-26 12:05:55 +01002121 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002122 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002123 }
2124
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002125 RemoveElement(reverse_post_order_, block);
2126 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002127 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002128}
2129
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002130void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2131 HBasicBlock* reference,
2132 bool replace_if_back_edge) {
2133 if (block->IsLoopHeader()) {
2134 // Clear the information of which blocks are contained in that loop. Since the
2135 // information is stored as a bit vector based on block ids, we have to update
2136 // it, as those block ids were specific to the callee graph and we are now adding
2137 // these blocks to the caller graph.
2138 block->GetLoopInformation()->ClearAllBlocks();
2139 }
2140
2141 // If not already in a loop, update the loop information.
2142 if (!block->IsInLoop()) {
2143 block->SetLoopInformation(reference->GetLoopInformation());
2144 }
2145
2146 // If the block is in a loop, update all its outward loops.
2147 HLoopInformation* loop_info = block->GetLoopInformation();
2148 if (loop_info != nullptr) {
2149 for (HLoopInformationOutwardIterator loop_it(*block);
2150 !loop_it.Done();
2151 loop_it.Advance()) {
2152 loop_it.Current()->Add(block);
2153 }
2154 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2155 loop_info->ReplaceBackEdge(reference, block);
2156 }
2157 }
2158
2159 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2160 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2161 ? reference->GetTryCatchInformation()
2162 : nullptr;
2163 block->SetTryCatchInformation(try_catch_info);
2164}
2165
Calin Juravle2e768302015-07-28 14:41:11 +00002166HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002167 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002168 // Update the environments in this graph to have the invoke's environment
2169 // as parent.
2170 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002171 // Skip the entry block, we do not need to update the entry's suspend check.
2172 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002173 for (HInstructionIterator instr_it(block->GetInstructions());
2174 !instr_it.Done();
2175 instr_it.Advance()) {
2176 HInstruction* current = instr_it.Current();
2177 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002178 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002179 current->GetEnvironment()->SetAndCopyParentChain(
2180 outer_graph->GetArena(), invoke->GetEnvironment());
2181 }
2182 }
2183 }
2184 }
2185 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002186
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002187 if (HasBoundsChecks()) {
2188 outer_graph->SetHasBoundsChecks(true);
2189 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002190 if (HasLoops()) {
2191 outer_graph->SetHasLoops(true);
2192 }
2193 if (HasIrreducibleLoops()) {
2194 outer_graph->SetHasIrreducibleLoops(true);
2195 }
2196 if (HasTryCatch()) {
2197 outer_graph->SetHasTryCatch(true);
2198 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002199 if (HasSIMD()) {
2200 outer_graph->SetHasSIMD(true);
2201 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002202
Calin Juravle2e768302015-07-28 14:41:11 +00002203 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002204 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002205 // Inliner already made sure we don't inline methods that always throw.
2206 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002207 // Simple case of an entry block, a body block, and an exit block.
2208 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002209 HBasicBlock* body = GetBlocks()[1];
2210 DCHECK(GetBlocks()[0]->IsEntryBlock());
2211 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002212 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002213 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002214 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002215
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002216 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2217 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002218 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002219
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002220 // Replace the invoke with the return value of the inlined graph.
2221 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002222 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002223 } else {
2224 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002225 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002226
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002227 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002228 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002229 // Need to inline multiple blocks. We split `invoke`'s block
2230 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002231 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002232 // with the second half.
2233 ArenaAllocator* allocator = outer_graph->GetArena();
2234 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002235 // Note that we split before the invoke only to simplify polymorphic inlining.
2236 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002237
Vladimir Markoec7802a2015-10-01 20:57:57 +01002238 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002239 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002240 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002241 exit_block_->ReplaceWith(to);
2242
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002243 // Update the meta information surrounding blocks:
2244 // (1) the graph they are now in,
2245 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002246 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002247 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002248 // Note that we do not need to update catch phi inputs because they
2249 // correspond to the register file of the outer method which the inlinee
2250 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002251
2252 // We don't add the entry block, the exit block, and the first block, which
2253 // has been merged with `at`.
2254 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2255
2256 // We add the `to` block.
2257 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002258 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002259 + kNumberOfNewBlocksInCaller;
2260
2261 // Find the location of `at` in the outer graph's reverse post order. The new
2262 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002263 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002264 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2265
David Brazdil95177982015-10-30 12:56:58 -05002266 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2267 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002268 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002269 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002270 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002271 DCHECK(current->GetGraph() == this);
2272 current->SetGraph(outer_graph);
2273 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002274 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002275 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002276 }
2277 }
2278
David Brazdil95177982015-10-30 12:56:58 -05002279 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002280 to->SetGraph(outer_graph);
2281 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002282 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002283 // Only `to` can become a back edge, as the inlined blocks
2284 // are predecessors of `to`.
2285 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002286
David Brazdil3f523062016-02-29 16:53:33 +00002287 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002288 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2289 // to now get the outer graph exit block as successor. Note that the inliner
2290 // currently doesn't support inlining methods with try/catch.
2291 HPhi* return_value_phi = nullptr;
2292 bool rerun_dominance = false;
2293 bool rerun_loop_analysis = false;
2294 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2295 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002296 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002297 if (last->IsThrow()) {
2298 DCHECK(!at->IsTryBlock());
2299 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2300 --pred;
2301 // We need to re-run dominance information, as the exit block now has
2302 // a new dominator.
2303 rerun_dominance = true;
2304 if (predecessor->GetLoopInformation() != nullptr) {
2305 // The exit block and blocks post dominated by the exit block do not belong
2306 // to any loop. Because we do not compute the post dominators, we need to re-run
2307 // loop analysis to get the loop information correct.
2308 rerun_loop_analysis = true;
2309 }
2310 } else {
2311 if (last->IsReturnVoid()) {
2312 DCHECK(return_value == nullptr);
2313 DCHECK(return_value_phi == nullptr);
2314 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002315 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002316 if (return_value_phi != nullptr) {
2317 return_value_phi->AddInput(last->InputAt(0));
2318 } else if (return_value == nullptr) {
2319 return_value = last->InputAt(0);
2320 } else {
2321 // There will be multiple returns.
2322 return_value_phi = new (allocator) HPhi(
2323 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2324 to->AddPhi(return_value_phi);
2325 return_value_phi->AddInput(return_value);
2326 return_value_phi->AddInput(last->InputAt(0));
2327 return_value = return_value_phi;
2328 }
David Brazdil3f523062016-02-29 16:53:33 +00002329 }
2330 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2331 predecessor->RemoveInstruction(last);
2332 }
2333 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002334 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002335 DCHECK(!outer_graph->HasIrreducibleLoops())
2336 << "Recomputing loop information in graphs with irreducible loops "
2337 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002338 outer_graph->ClearLoopInformation();
2339 outer_graph->ClearDominanceInformation();
2340 outer_graph->BuildDominatorTree();
2341 } else if (rerun_dominance) {
2342 outer_graph->ClearDominanceInformation();
2343 outer_graph->ComputeDominanceInformation();
2344 }
David Brazdil3f523062016-02-29 16:53:33 +00002345 }
David Brazdil05144f42015-04-16 15:18:00 +01002346
2347 // Walk over the entry block and:
2348 // - Move constants from the entry block to the outer_graph's entry block,
2349 // - Replace HParameterValue instructions with their real value.
2350 // - Remove suspend checks, that hold an environment.
2351 // We must do this after the other blocks have been inlined, otherwise ids of
2352 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002353 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002354 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2355 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002356 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002357 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002358 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002359 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002360 replacement = outer_graph->GetIntConstant(
2361 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002362 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002363 replacement = outer_graph->GetLongConstant(
2364 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002365 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002366 replacement = outer_graph->GetFloatConstant(
2367 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002368 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002369 replacement = outer_graph->GetDoubleConstant(
2370 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002371 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002372 if (kIsDebugBuild
2373 && invoke->IsInvokeStaticOrDirect()
2374 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2375 // Ensure we do not use the last input of `invoke`, as it
2376 // contains a clinit check which is not an actual argument.
2377 size_t last_input_index = invoke->InputCount() - 1;
2378 DCHECK(parameter_index != last_input_index);
2379 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002380 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002381 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002382 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002383 } else {
2384 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2385 entry_block_->RemoveInstruction(current);
2386 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002387 if (replacement != nullptr) {
2388 current->ReplaceWith(replacement);
2389 // If the current is the return value then we need to update the latter.
2390 if (current == return_value) {
2391 DCHECK_EQ(entry_block_, return_value->GetBlock());
2392 return_value = replacement;
2393 }
2394 }
2395 }
2396
Calin Juravle2e768302015-07-28 14:41:11 +00002397 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002398}
2399
Mingyao Yang3584bce2015-05-19 16:01:59 -07002400/*
2401 * Loop will be transformed to:
2402 * old_pre_header
2403 * |
2404 * if_block
2405 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002406 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002407 * \ /
2408 * new_pre_header
2409 * |
2410 * header
2411 */
2412void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2413 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002414 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002415
Aart Bik3fc7f352015-11-20 22:03:03 -08002416 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002417 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002418 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2419 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002420 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2421 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002422 AddBlock(true_block);
2423 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002424 AddBlock(new_pre_header);
2425
Aart Bik3fc7f352015-11-20 22:03:03 -08002426 header->ReplacePredecessor(old_pre_header, new_pre_header);
2427 old_pre_header->successors_.clear();
2428 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002429
Aart Bik3fc7f352015-11-20 22:03:03 -08002430 old_pre_header->AddSuccessor(if_block);
2431 if_block->AddSuccessor(true_block); // True successor
2432 if_block->AddSuccessor(false_block); // False successor
2433 true_block->AddSuccessor(new_pre_header);
2434 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002435
Aart Bik3fc7f352015-11-20 22:03:03 -08002436 old_pre_header->dominated_blocks_.push_back(if_block);
2437 if_block->SetDominator(old_pre_header);
2438 if_block->dominated_blocks_.push_back(true_block);
2439 true_block->SetDominator(if_block);
2440 if_block->dominated_blocks_.push_back(false_block);
2441 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002442 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002443 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002444 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002445 header->SetDominator(new_pre_header);
2446
Aart Bik3fc7f352015-11-20 22:03:03 -08002447 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002448 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002449 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002450 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002451 reverse_post_order_[index_of_header++] = true_block;
2452 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002453 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002454
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002455 // The pre_header can never be a back edge of a loop.
2456 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2457 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2458 UpdateLoopAndTryInformationOfNewBlock(
2459 if_block, old_pre_header, /* replace_if_back_edge */ false);
2460 UpdateLoopAndTryInformationOfNewBlock(
2461 true_block, old_pre_header, /* replace_if_back_edge */ false);
2462 UpdateLoopAndTryInformationOfNewBlock(
2463 false_block, old_pre_header, /* replace_if_back_edge */ false);
2464 UpdateLoopAndTryInformationOfNewBlock(
2465 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002466}
2467
Aart Bikf8f5a162017-02-06 15:35:29 -08002468HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2469 HBasicBlock* body,
2470 HBasicBlock* exit) {
2471 DCHECK(header->IsLoopHeader());
2472 HLoopInformation* loop = header->GetLoopInformation();
2473
2474 // Add new loop blocks.
2475 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2476 HBasicBlock* new_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2477 HBasicBlock* new_body = new (arena_) HBasicBlock(this, header->GetDexPc());
2478 AddBlock(new_pre_header);
2479 AddBlock(new_header);
2480 AddBlock(new_body);
2481
2482 // Set up control flow.
2483 header->ReplaceSuccessor(exit, new_pre_header);
2484 new_pre_header->AddSuccessor(new_header);
2485 new_header->AddSuccessor(exit);
2486 new_header->AddSuccessor(new_body);
2487 new_body->AddSuccessor(new_header);
2488
2489 // Set up dominators.
2490 header->ReplaceDominatedBlock(exit, new_pre_header);
2491 new_pre_header->SetDominator(header);
2492 new_pre_header->dominated_blocks_.push_back(new_header);
2493 new_header->SetDominator(new_pre_header);
2494 new_header->dominated_blocks_.push_back(new_body);
2495 new_body->SetDominator(new_header);
2496 new_header->dominated_blocks_.push_back(exit);
2497 exit->SetDominator(new_header);
2498
2499 // Fix reverse post order.
2500 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2501 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2502 reverse_post_order_[++index_of_header] = new_pre_header;
2503 reverse_post_order_[++index_of_header] = new_header;
2504 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2505 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2506 reverse_post_order_[index_of_body] = new_body;
2507
Aart Bikb07d1bc2017-04-05 10:03:15 -07002508 // Add gotos and suspend check (client must add conditional in header).
Aart Bikf8f5a162017-02-06 15:35:29 -08002509 new_pre_header->AddInstruction(new (arena_) HGoto());
2510 HSuspendCheck* suspend_check = new (arena_) HSuspendCheck(header->GetDexPc());
2511 new_header->AddInstruction(suspend_check);
2512 new_body->AddInstruction(new (arena_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002513 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2514 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002515
2516 // Update loop information.
2517 new_header->AddBackEdge(new_body);
2518 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2519 new_header->GetLoopInformation()->Populate();
2520 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2521 HLoopInformationOutwardIterator it(*new_header);
2522 for (it.Advance(); !it.Done(); it.Advance()) {
2523 it.Current()->Add(new_pre_header);
2524 it.Current()->Add(new_header);
2525 it.Current()->Add(new_body);
2526 }
2527 return new_pre_header;
2528}
2529
David Brazdilf5552582015-12-27 13:36:12 +00002530static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002531 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002532 if (rti.IsValid()) {
2533 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2534 << " upper_bound_rti: " << upper_bound_rti
2535 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002536 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2537 << " upper_bound_rti: " << upper_bound_rti
2538 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002539 }
2540}
2541
Calin Juravle2e768302015-07-28 14:41:11 +00002542void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2543 if (kIsDebugBuild) {
2544 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2545 ScopedObjectAccess soa(Thread::Current());
2546 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2547 if (IsBoundType()) {
2548 // Having the test here spares us from making the method virtual just for
2549 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002550 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002551 }
2552 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002553 reference_type_handle_ = rti.GetTypeHandle();
2554 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002555}
2556
David Brazdilf5552582015-12-27 13:36:12 +00002557void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2558 if (kIsDebugBuild) {
2559 ScopedObjectAccess soa(Thread::Current());
2560 DCHECK(upper_bound.IsValid());
2561 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2562 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2563 }
2564 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002565 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002566}
2567
Vladimir Markoa1de9182016-02-25 11:37:38 +00002568ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002569 if (kIsDebugBuild) {
2570 ScopedObjectAccess soa(Thread::Current());
2571 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002572 if (!is_exact) {
2573 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2574 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2575 }
Calin Juravle2e768302015-07-28 14:41:11 +00002576 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002577 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002578}
2579
Calin Juravleacf735c2015-02-12 15:25:22 +00002580std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2581 ScopedObjectAccess soa(Thread::Current());
2582 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002583 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002584 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002585 << " is_exact=" << rhs.IsExact()
2586 << " ]";
2587 return os;
2588}
2589
Mark Mendellc4701932015-04-10 13:18:51 -04002590bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2591 // For now, assume that instructions in different blocks may use the
2592 // environment.
2593 // TODO: Use the control flow to decide if this is true.
2594 if (GetBlock() != other->GetBlock()) {
2595 return true;
2596 }
2597
2598 // We know that we are in the same block. Walk from 'this' to 'other',
2599 // checking to see if there is any instruction with an environment.
2600 HInstruction* current = this;
2601 for (; current != other && current != nullptr; current = current->GetNext()) {
2602 // This is a conservative check, as the instruction result may not be in
2603 // the referenced environment.
2604 if (current->HasEnvironment()) {
2605 return true;
2606 }
2607 }
2608
2609 // We should have been called with 'this' before 'other' in the block.
2610 // Just confirm this.
2611 DCHECK(current != nullptr);
2612 return false;
2613}
2614
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002615void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002616 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2617 IntrinsicSideEffects side_effects,
2618 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002619 intrinsic_ = intrinsic;
2620 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002621
Aart Bik5d75afe2015-12-14 11:57:01 -08002622 // Adjust method's side effects from intrinsic table.
2623 switch (side_effects) {
2624 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2625 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2626 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2627 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2628 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002629
2630 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2631 opt.SetDoesNotNeedDexCache();
2632 opt.SetDoesNotNeedEnvironment();
2633 } else {
2634 // If we need an environment, that means there will be a call, which can trigger GC.
2635 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2636 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002637 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002638 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002639}
2640
David Brazdil6de19382016-01-08 17:37:10 +00002641bool HNewInstance::IsStringAlloc() const {
2642 ScopedObjectAccess soa(Thread::Current());
2643 return GetReferenceTypeInfo().IsStringClass();
2644}
2645
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002646bool HInvoke::NeedsEnvironment() const {
2647 if (!IsIntrinsic()) {
2648 return true;
2649 }
2650 IntrinsicOptimizations opt(*this);
2651 return !opt.GetDoesNotNeedEnvironment();
2652}
2653
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002654const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2655 ArtMethod* caller = GetEnvironment()->GetMethod();
2656 ScopedObjectAccess soa(Thread::Current());
2657 // `caller` is null for a top-level graph representing a method whose declaring
2658 // class was not resolved.
2659 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2660}
2661
Vladimir Markodc151b22015-10-15 18:02:30 +01002662bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002663 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002664 return false;
2665 }
2666 if (!IsIntrinsic()) {
2667 return true;
2668 }
2669 IntrinsicOptimizations opt(*this);
2670 return !opt.GetDoesNotNeedDexCache();
2671}
2672
Vladimir Markof64242a2015-12-01 14:58:23 +00002673std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2674 switch (rhs) {
2675 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002676 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002677 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002678 return os << "Recursive";
2679 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2680 return os << "BootImageLinkTimePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002681 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
Vladimir Marko19d7d502017-05-24 13:04:14 +01002682 return os << "DirectAddress";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002683 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2684 return os << "BssEntry";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002685 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2686 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002687 default:
2688 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2689 UNREACHABLE();
2690 }
2691}
2692
Vladimir Markofbb184a2015-11-13 14:47:00 +00002693std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2694 switch (rhs) {
2695 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2696 return os << "explicit";
2697 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2698 return os << "implicit";
2699 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2700 return os << "none";
2701 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002702 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2703 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002704 }
2705}
2706
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002707bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2708 const HLoadClass* other_load_class = other->AsLoadClass();
2709 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2710 // names rather than type indexes. However, we shall also have to re-think the hash code.
2711 if (type_index_ != other_load_class->type_index_ ||
2712 GetPackedFields() != other_load_class->GetPackedFields()) {
2713 return false;
2714 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002715 switch (GetLoadKind()) {
2716 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002717 case LoadKind::kJitTableAddress: {
2718 ScopedObjectAccess soa(Thread::Current());
2719 return GetClass().Get() == other_load_class->GetClass().Get();
2720 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002721 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002722 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002723 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002724 }
2725}
2726
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002727void HLoadClass::SetLoadKind(LoadKind load_kind) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002728 SetPackedField<LoadKindField>(load_kind);
2729
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002730 if (load_kind != LoadKind::kRuntimeCall &&
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002731 load_kind != LoadKind::kReferrersClass) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002732 RemoveAsUserOfInput(0u);
2733 SetRawInputAt(0u, nullptr);
2734 }
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002735
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002736 if (!NeedsEnvironment()) {
2737 RemoveEnvironment();
2738 SetSideEffects(SideEffects::None());
2739 }
2740}
2741
2742std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2743 switch (rhs) {
2744 case HLoadClass::LoadKind::kReferrersClass:
2745 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002746 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2747 return os << "BootImageLinkTimePcRelative";
2748 case HLoadClass::LoadKind::kBootImageAddress:
2749 return os << "BootImageAddress";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002750 case HLoadClass::LoadKind::kBssEntry:
2751 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002752 case HLoadClass::LoadKind::kJitTableAddress:
2753 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002754 case HLoadClass::LoadKind::kRuntimeCall:
2755 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002756 default:
2757 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2758 UNREACHABLE();
2759 }
2760}
2761
Vladimir Marko372f10e2016-05-17 16:30:10 +01002762bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2763 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002764 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2765 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002766 if (string_index_ != other_load_string->string_index_ ||
2767 GetPackedFields() != other_load_string->GetPackedFields()) {
2768 return false;
2769 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002770 switch (GetLoadKind()) {
2771 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002772 case LoadKind::kJitTableAddress: {
2773 ScopedObjectAccess soa(Thread::Current());
2774 return GetString().Get() == other_load_string->GetString().Get();
2775 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002776 default:
2777 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002778 }
2779}
2780
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002781void HLoadString::SetLoadKind(LoadKind load_kind) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002782 // Once sharpened, the load kind should not be changed again.
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002783 DCHECK_EQ(GetLoadKind(), LoadKind::kRuntimeCall);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002784 SetPackedField<LoadKindField>(load_kind);
2785
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002786 if (load_kind != LoadKind::kRuntimeCall) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002787 RemoveAsUserOfInput(0u);
2788 SetRawInputAt(0u, nullptr);
2789 }
2790 if (!NeedsEnvironment()) {
2791 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002792 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002793 }
2794}
2795
2796std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2797 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002798 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2799 return os << "BootImageLinkTimePcRelative";
2800 case HLoadString::LoadKind::kBootImageAddress:
2801 return os << "BootImageAddress";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002802 case HLoadString::LoadKind::kBssEntry:
2803 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002804 case HLoadString::LoadKind::kJitTableAddress:
2805 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002806 case HLoadString::LoadKind::kRuntimeCall:
2807 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002808 default:
2809 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2810 UNREACHABLE();
2811 }
2812}
2813
Mark Mendellc4701932015-04-10 13:18:51 -04002814void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002815 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2816 HEnvironment* user = use.GetUser();
2817 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002818 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002819 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002820}
2821
Roland Levillainc9b21f82016-03-23 16:36:59 +00002822// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002823HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2824 ArenaAllocator* allocator = GetArena();
2825
2826 if (cond->IsCondition() &&
2827 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2828 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2829 HInstruction* lhs = cond->InputAt(0);
2830 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002831 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002832 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2833 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2834 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2835 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2836 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2837 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2838 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2839 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2840 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2841 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2842 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002843 default:
2844 LOG(FATAL) << "Unexpected condition";
2845 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002846 }
2847 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2848 return replacement;
2849 } else if (cond->IsIntConstant()) {
2850 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002851 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002852 return GetIntConstant(1);
2853 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002854 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002855 return GetIntConstant(0);
2856 }
2857 } else {
2858 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2859 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2860 return replacement;
2861 }
2862}
2863
Roland Levillainc9285912015-12-18 10:38:42 +00002864std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2865 os << "["
2866 << " source=" << rhs.GetSource()
2867 << " destination=" << rhs.GetDestination()
2868 << " type=" << rhs.GetType()
2869 << " instruction=";
2870 if (rhs.GetInstruction() != nullptr) {
2871 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2872 } else {
2873 os << "null";
2874 }
2875 os << " ]";
2876 return os;
2877}
2878
Roland Levillain86503782016-02-11 19:07:30 +00002879std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2880 switch (rhs) {
2881 case TypeCheckKind::kUnresolvedCheck:
2882 return os << "unresolved_check";
2883 case TypeCheckKind::kExactCheck:
2884 return os << "exact_check";
2885 case TypeCheckKind::kClassHierarchyCheck:
2886 return os << "class_hierarchy_check";
2887 case TypeCheckKind::kAbstractClassCheck:
2888 return os << "abstract_class_check";
2889 case TypeCheckKind::kInterfaceCheck:
2890 return os << "interface_check";
2891 case TypeCheckKind::kArrayObjectCheck:
2892 return os << "array_object_check";
2893 case TypeCheckKind::kArrayCheck:
2894 return os << "array_check";
2895 default:
2896 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2897 UNREACHABLE();
2898 }
2899}
2900
Andreas Gampe26de38b2016-07-27 17:53:11 -07002901std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2902 switch (kind) {
2903 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002904 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002905 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002906 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002907 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002908 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002909 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002910 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002911 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002912 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002913
2914 default:
2915 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
2916 UNREACHABLE();
2917 }
2918}
2919
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002920} // namespace art