blob: e34d4a2be6c76ba64ab9034f139dbdb5d4bb74e4 [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 Murashkindd018df2017-08-09 10:38:31 -07001274void HConstructorFence::Merge(HConstructorFence* other) {
1275 // Do not delete yourself from the graph.
1276 DCHECK(this != other);
1277 // Don't try to merge with an instruction not associated with a block.
1278 DCHECK(other->GetBlock() != nullptr);
1279 // A constructor fence's return type is "kPrimVoid"
1280 // and therefore it cannot have any environment uses.
1281 DCHECK(!other->HasEnvironmentUses());
1282
1283 auto has_input = [](HInstruction* haystack, HInstruction* needle) {
1284 // Check if `haystack` has `needle` as any of its inputs.
1285 for (size_t input_count = 0; input_count < haystack->InputCount(); ++input_count) {
1286 if (haystack->InputAt(input_count) == needle) {
1287 return true;
1288 }
1289 }
1290 return false;
1291 };
1292
1293 // Add any inputs from `other` into `this` if it wasn't already an input.
1294 for (size_t input_count = 0; input_count < other->InputCount(); ++input_count) {
1295 HInstruction* other_input = other->InputAt(input_count);
1296 if (!has_input(this, other_input)) {
1297 AddInput(other_input);
1298 }
1299 }
1300
1301 other->GetBlock()->RemoveInstruction(other);
1302}
1303
1304HInstruction* HConstructorFence::GetAssociatedAllocation(bool ignore_inputs) {
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001305 HInstruction* new_instance_inst = GetPrevious();
1306 // Check if the immediately preceding instruction is a new-instance/new-array.
1307 // Otherwise this fence is for protecting final fields.
1308 if (new_instance_inst != nullptr &&
1309 (new_instance_inst->IsNewInstance() || new_instance_inst->IsNewArray())) {
Igor Murashkindd018df2017-08-09 10:38:31 -07001310 if (ignore_inputs) {
1311 // If inputs are ignored, simply check if the predecessor is
1312 // *any* HNewInstance/HNewArray.
1313 //
1314 // Inputs are normally only ignored for prepare_for_register_allocation,
1315 // at which point *any* prior HNewInstance/Array can be considered
1316 // associated.
1317 return new_instance_inst;
1318 } else {
1319 // Normal case: There must be exactly 1 input and the previous instruction
1320 // must be that input.
1321 if (InputCount() == 1u && InputAt(0) == new_instance_inst) {
1322 return new_instance_inst;
1323 }
1324 }
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001325 }
Igor Murashkindd018df2017-08-09 10:38:31 -07001326 return nullptr;
Igor Murashkin79d8fa72017-04-18 09:37:23 -07001327}
1328
Nicolas Geoffray360231a2014-10-08 21:07:48 +01001329#define DEFINE_ACCEPT(name, super) \
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001330void H##name::Accept(HGraphVisitor* visitor) { \
1331 visitor->Visit##name(this); \
1332}
1333
Vladimir Marko5f7b58e2015-11-23 19:49:34 +00001334FOR_EACH_CONCRETE_INSTRUCTION(DEFINE_ACCEPT)
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001335
1336#undef DEFINE_ACCEPT
1337
1338void HGraphVisitor::VisitInsertionOrder() {
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001339 const ArenaVector<HBasicBlock*>& blocks = graph_->GetBlocks();
1340 for (HBasicBlock* block : blocks) {
David Brazdil46e2a392015-03-16 17:31:52 +00001341 if (block != nullptr) {
1342 VisitBasicBlock(block);
1343 }
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001344 }
1345}
1346
Roland Levillain633021e2014-10-01 14:12:25 +01001347void HGraphVisitor::VisitReversePostOrder() {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001348 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1349 VisitBasicBlock(block);
Roland Levillain633021e2014-10-01 14:12:25 +01001350 }
1351}
1352
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001353void HGraphVisitor::VisitBasicBlock(HBasicBlock* block) {
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001354 for (HInstructionIterator it(block->GetPhis()); !it.Done(); it.Advance()) {
Nicolas Geoffrayc32e7702014-04-24 12:43:16 +01001355 it.Current()->Accept(this);
1356 }
Nicolas Geoffrayf635e632014-05-14 09:43:38 +01001357 for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
Nicolas Geoffray818f2102014-02-18 16:43:35 +00001358 it.Current()->Accept(this);
1359 }
1360}
1361
Mark Mendelle82549b2015-05-06 10:55:34 -04001362HConstant* HTypeConversion::TryStaticEvaluation() const {
1363 HGraph* graph = GetBlock()->GetGraph();
1364 if (GetInput()->IsIntConstant()) {
1365 int32_t value = GetInput()->AsIntConstant()->GetValue();
1366 switch (GetResultType()) {
1367 case Primitive::kPrimLong:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001368 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001369 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001370 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001371 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001372 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001373 default:
1374 return nullptr;
1375 }
1376 } else if (GetInput()->IsLongConstant()) {
1377 int64_t value = GetInput()->AsLongConstant()->GetValue();
1378 switch (GetResultType()) {
1379 case Primitive::kPrimInt:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001380 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001381 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001382 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001383 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001384 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001385 default:
1386 return nullptr;
1387 }
1388 } else if (GetInput()->IsFloatConstant()) {
1389 float value = GetInput()->AsFloatConstant()->GetValue();
1390 switch (GetResultType()) {
1391 case Primitive::kPrimInt:
1392 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001393 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001394 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001395 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001396 if (value <= kPrimIntMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001397 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1398 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001399 case Primitive::kPrimLong:
1400 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001401 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001402 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001403 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001404 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001405 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1406 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001407 case Primitive::kPrimDouble:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001408 return graph->GetDoubleConstant(static_cast<double>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001409 default:
1410 return nullptr;
1411 }
1412 } else if (GetInput()->IsDoubleConstant()) {
1413 double value = GetInput()->AsDoubleConstant()->GetValue();
1414 switch (GetResultType()) {
1415 case Primitive::kPrimInt:
1416 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001417 return graph->GetIntConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001418 if (value >= kPrimIntMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001419 return graph->GetIntConstant(kPrimIntMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001420 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001421 return graph->GetIntConstant(kPrimIntMin, GetDexPc());
1422 return graph->GetIntConstant(static_cast<int32_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001423 case Primitive::kPrimLong:
1424 if (std::isnan(value))
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001425 return graph->GetLongConstant(0, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001426 if (value >= kPrimLongMax)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001427 return graph->GetLongConstant(kPrimLongMax, GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001428 if (value <= kPrimLongMin)
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001429 return graph->GetLongConstant(kPrimLongMin, GetDexPc());
1430 return graph->GetLongConstant(static_cast<int64_t>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001431 case Primitive::kPrimFloat:
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001432 return graph->GetFloatConstant(static_cast<float>(value), GetDexPc());
Mark Mendelle82549b2015-05-06 10:55:34 -04001433 default:
1434 return nullptr;
1435 }
1436 }
1437 return nullptr;
1438}
1439
Roland Levillain9240d6a2014-10-20 16:47:04 +01001440HConstant* HUnaryOperation::TryStaticEvaluation() const {
1441 if (GetInput()->IsIntConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001442 return Evaluate(GetInput()->AsIntConstant());
Roland Levillain9240d6a2014-10-20 16:47:04 +01001443 } else if (GetInput()->IsLongConstant()) {
Roland Levillain9867bc72015-08-05 10:21:34 +01001444 return Evaluate(GetInput()->AsLongConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001445 } else if (kEnableFloatingPointStaticEvaluation) {
1446 if (GetInput()->IsFloatConstant()) {
1447 return Evaluate(GetInput()->AsFloatConstant());
1448 } else if (GetInput()->IsDoubleConstant()) {
1449 return Evaluate(GetInput()->AsDoubleConstant());
1450 }
Roland Levillain9240d6a2014-10-20 16:47:04 +01001451 }
1452 return nullptr;
1453}
1454
1455HConstant* HBinaryOperation::TryStaticEvaluation() const {
Roland Levillaine53bd812016-02-24 14:54:18 +00001456 if (GetLeft()->IsIntConstant() && GetRight()->IsIntConstant()) {
1457 return Evaluate(GetLeft()->AsIntConstant(), GetRight()->AsIntConstant());
Roland Levillain9867bc72015-08-05 10:21:34 +01001458 } else if (GetLeft()->IsLongConstant()) {
1459 if (GetRight()->IsIntConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001460 // The binop(long, int) case is only valid for shifts and rotations.
1461 DCHECK(IsShl() || IsShr() || IsUShr() || IsRor()) << DebugName();
Roland Levillain9867bc72015-08-05 10:21:34 +01001462 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsIntConstant());
1463 } else if (GetRight()->IsLongConstant()) {
1464 return Evaluate(GetLeft()->AsLongConstant(), GetRight()->AsLongConstant());
Nicolas Geoffray9ee66182015-01-16 12:35:40 +00001465 }
Vladimir Marko9e23df52015-11-10 17:14:35 +00001466 } else if (GetLeft()->IsNullConstant() && GetRight()->IsNullConstant()) {
Roland Levillaine53bd812016-02-24 14:54:18 +00001467 // The binop(null, null) case is only valid for equal and not-equal conditions.
1468 DCHECK(IsEqual() || IsNotEqual()) << DebugName();
Vladimir Marko9e23df52015-11-10 17:14:35 +00001469 return Evaluate(GetLeft()->AsNullConstant(), GetRight()->AsNullConstant());
Roland Levillain31dd3d62016-02-16 12:21:02 +00001470 } else if (kEnableFloatingPointStaticEvaluation) {
1471 if (GetLeft()->IsFloatConstant() && GetRight()->IsFloatConstant()) {
1472 return Evaluate(GetLeft()->AsFloatConstant(), GetRight()->AsFloatConstant());
1473 } else if (GetLeft()->IsDoubleConstant() && GetRight()->IsDoubleConstant()) {
1474 return Evaluate(GetLeft()->AsDoubleConstant(), GetRight()->AsDoubleConstant());
1475 }
Roland Levillain556c3d12014-09-18 15:25:07 +01001476 }
1477 return nullptr;
1478}
Dave Allison20dfc792014-06-16 20:44:29 -07001479
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001480HConstant* HBinaryOperation::GetConstantRight() const {
1481 if (GetRight()->IsConstant()) {
1482 return GetRight()->AsConstant();
1483 } else if (IsCommutative() && GetLeft()->IsConstant()) {
1484 return GetLeft()->AsConstant();
1485 } else {
1486 return nullptr;
1487 }
1488}
1489
1490// If `GetConstantRight()` returns one of the input, this returns the other
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001491// one. Otherwise it returns null.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001492HInstruction* HBinaryOperation::GetLeastConstantLeft() const {
1493 HInstruction* most_constant_right = GetConstantRight();
1494 if (most_constant_right == nullptr) {
1495 return nullptr;
1496 } else if (most_constant_right == GetLeft()) {
1497 return GetRight();
1498 } else {
1499 return GetLeft();
1500 }
1501}
1502
Roland Levillain31dd3d62016-02-16 12:21:02 +00001503std::ostream& operator<<(std::ostream& os, const ComparisonBias& rhs) {
1504 switch (rhs) {
1505 case ComparisonBias::kNoBias:
1506 return os << "no_bias";
1507 case ComparisonBias::kGtBias:
1508 return os << "gt_bias";
1509 case ComparisonBias::kLtBias:
1510 return os << "lt_bias";
1511 default:
1512 LOG(FATAL) << "Unknown ComparisonBias: " << static_cast<int>(rhs);
1513 UNREACHABLE();
1514 }
1515}
1516
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001517bool HCondition::IsBeforeWhenDisregardMoves(HInstruction* instruction) const {
1518 return this == instruction->GetPreviousDisregardingMoves();
Nicolas Geoffray18efde52014-09-22 15:51:11 +01001519}
1520
Vladimir Marko372f10e2016-05-17 16:30:10 +01001521bool HInstruction::Equals(const HInstruction* other) const {
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001522 if (!InstructionTypeEquals(other)) return false;
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001523 DCHECK_EQ(GetKind(), other->GetKind());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001524 if (!InstructionDataEquals(other)) return false;
1525 if (GetType() != other->GetType()) return false;
Vladimir Markoe9004912016-06-16 16:50:52 +01001526 HConstInputsRef inputs = GetInputs();
1527 HConstInputsRef other_inputs = other->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +01001528 if (inputs.size() != other_inputs.size()) return false;
1529 for (size_t i = 0; i != inputs.size(); ++i) {
1530 if (inputs[i] != other_inputs[i]) return false;
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001531 }
Vladimir Marko372f10e2016-05-17 16:30:10 +01001532
Nicolas Geoffrayd31cf3d2014-09-08 17:30:24 +01001533 DCHECK_EQ(ComputeHashCode(), other->ComputeHashCode());
Nicolas Geoffray065bf772014-09-03 14:51:22 +01001534 return true;
1535}
1536
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001537std::ostream& operator<<(std::ostream& os, const HInstruction::InstructionKind& rhs) {
1538#define DECLARE_CASE(type, super) case HInstruction::k##type: os << #type; break;
1539 switch (rhs) {
1540 FOR_EACH_INSTRUCTION(DECLARE_CASE)
1541 default:
1542 os << "Unknown instruction kind " << static_cast<int>(rhs);
1543 break;
1544 }
1545#undef DECLARE_CASE
1546 return os;
1547}
1548
Alexandre Rames22aa54b2016-10-18 09:32:29 +01001549void HInstruction::MoveBefore(HInstruction* cursor, bool do_checks) {
1550 if (do_checks) {
1551 DCHECK(!IsPhi());
1552 DCHECK(!IsControlFlow());
1553 DCHECK(CanBeMoved() ||
1554 // HShouldDeoptimizeFlag can only be moved by CHAGuardOptimization.
1555 IsShouldDeoptimizeFlag());
1556 DCHECK(!cursor->IsPhi());
1557 }
David Brazdild6c205e2016-06-07 14:20:52 +01001558
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001559 next_->previous_ = previous_;
1560 if (previous_ != nullptr) {
1561 previous_->next_ = next_;
1562 }
1563 if (block_->instructions_.first_instruction_ == this) {
1564 block_->instructions_.first_instruction_ = next_;
1565 }
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001566 DCHECK_NE(block_->instructions_.last_instruction_, this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001567
1568 previous_ = cursor->previous_;
1569 if (previous_ != nullptr) {
1570 previous_->next_ = this;
1571 }
1572 next_ = cursor;
1573 cursor->previous_ = this;
1574 block_ = cursor->block_;
Nicolas Geoffray82091da2015-01-26 10:02:45 +00001575
1576 if (block_->instructions_.first_instruction_ == cursor) {
1577 block_->instructions_.first_instruction_ = this;
1578 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001579}
1580
Vladimir Markofb337ea2015-11-25 15:25:10 +00001581void HInstruction::MoveBeforeFirstUserAndOutOfLoops() {
1582 DCHECK(!CanThrow());
1583 DCHECK(!HasSideEffects());
1584 DCHECK(!HasEnvironmentUses());
1585 DCHECK(HasNonEnvironmentUses());
1586 DCHECK(!IsPhi()); // Makes no sense for Phi.
1587 DCHECK_EQ(InputCount(), 0u);
1588
1589 // Find the target block.
Vladimir Marko46817b82016-03-29 12:21:58 +01001590 auto uses_it = GetUses().begin();
1591 auto uses_end = GetUses().end();
1592 HBasicBlock* target_block = uses_it->GetUser()->GetBlock();
1593 ++uses_it;
1594 while (uses_it != uses_end && uses_it->GetUser()->GetBlock() == target_block) {
1595 ++uses_it;
Vladimir Markofb337ea2015-11-25 15:25:10 +00001596 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001597 if (uses_it != uses_end) {
Vladimir Markofb337ea2015-11-25 15:25:10 +00001598 // This instruction has uses in two or more blocks. Find the common dominator.
1599 CommonDominator finder(target_block);
Vladimir Marko46817b82016-03-29 12:21:58 +01001600 for (; uses_it != uses_end; ++uses_it) {
1601 finder.Update(uses_it->GetUser()->GetBlock());
Vladimir Markofb337ea2015-11-25 15:25:10 +00001602 }
1603 target_block = finder.Get();
1604 DCHECK(target_block != nullptr);
1605 }
1606 // Move to the first dominator not in a loop.
1607 while (target_block->IsInLoop()) {
1608 target_block = target_block->GetDominator();
1609 DCHECK(target_block != nullptr);
1610 }
1611
1612 // Find insertion position.
1613 HInstruction* insert_pos = nullptr;
Vladimir Marko46817b82016-03-29 12:21:58 +01001614 for (const HUseListNode<HInstruction*>& use : GetUses()) {
1615 if (use.GetUser()->GetBlock() == target_block &&
1616 (insert_pos == nullptr || use.GetUser()->StrictlyDominates(insert_pos))) {
1617 insert_pos = use.GetUser();
Vladimir Markofb337ea2015-11-25 15:25:10 +00001618 }
1619 }
1620 if (insert_pos == nullptr) {
1621 // No user in `target_block`, insert before the control flow instruction.
1622 insert_pos = target_block->GetLastInstruction();
1623 DCHECK(insert_pos->IsControlFlow());
1624 // Avoid splitting HCondition from HIf to prevent unnecessary materialization.
1625 if (insert_pos->IsIf()) {
1626 HInstruction* if_input = insert_pos->AsIf()->InputAt(0);
1627 if (if_input == insert_pos->GetPrevious()) {
1628 insert_pos = if_input;
1629 }
1630 }
1631 }
1632 MoveBefore(insert_pos);
1633}
1634
David Brazdilfc6a86a2015-06-26 10:33:45 +00001635HBasicBlock* HBasicBlock::SplitBefore(HInstruction* cursor) {
David Brazdil9bc43612015-11-05 21:25:24 +00001636 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdilfc6a86a2015-06-26 10:33:45 +00001637 DCHECK_EQ(cursor->GetBlock(), this);
1638
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001639 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1640 cursor->GetDexPc());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001641 new_block->instructions_.first_instruction_ = cursor;
1642 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1643 instructions_.last_instruction_ = cursor->previous_;
1644 if (cursor->previous_ == nullptr) {
1645 instructions_.first_instruction_ = nullptr;
1646 } else {
1647 cursor->previous_->next_ = nullptr;
1648 cursor->previous_ = nullptr;
1649 }
1650
1651 new_block->instructions_.SetBlockOfInstructions(new_block);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06001652 AddInstruction(new (GetGraph()->GetArena()) HGoto(new_block->GetDexPc()));
David Brazdilfc6a86a2015-06-26 10:33:45 +00001653
Vladimir Marko60584552015-09-03 13:35:12 +00001654 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001655 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
David Brazdilfc6a86a2015-06-26 10:33:45 +00001656 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001657 new_block->successors_.swap(successors_);
1658 DCHECK(successors_.empty());
David Brazdilfc6a86a2015-06-26 10:33:45 +00001659 AddSuccessor(new_block);
1660
David Brazdil56e1acc2015-06-30 15:41:36 +01001661 GetGraph()->AddBlock(new_block);
David Brazdilfc6a86a2015-06-26 10:33:45 +00001662 return new_block;
1663}
1664
David Brazdild7558da2015-09-22 13:04:14 +01001665HBasicBlock* HBasicBlock::CreateImmediateDominator() {
David Brazdil9bc43612015-11-05 21:25:24 +00001666 DCHECK(!graph_->IsInSsaForm()) << "Support for SSA form not implemented.";
David Brazdild7558da2015-09-22 13:04:14 +01001667 DCHECK(!IsCatchBlock()) << "Support for updating try/catch information not implemented.";
1668
1669 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1670
1671 for (HBasicBlock* predecessor : GetPredecessors()) {
David Brazdild7558da2015-09-22 13:04:14 +01001672 predecessor->successors_[predecessor->GetSuccessorIndexOf(this)] = new_block;
1673 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001674 new_block->predecessors_.swap(predecessors_);
1675 DCHECK(predecessors_.empty());
David Brazdild7558da2015-09-22 13:04:14 +01001676 AddPredecessor(new_block);
1677
1678 GetGraph()->AddBlock(new_block);
1679 return new_block;
1680}
1681
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001682HBasicBlock* HBasicBlock::SplitBeforeForInlining(HInstruction* cursor) {
1683 DCHECK_EQ(cursor->GetBlock(), this);
1684
1685 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(),
1686 cursor->GetDexPc());
1687 new_block->instructions_.first_instruction_ = cursor;
1688 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1689 instructions_.last_instruction_ = cursor->previous_;
1690 if (cursor->previous_ == nullptr) {
1691 instructions_.first_instruction_ = nullptr;
1692 } else {
1693 cursor->previous_->next_ = nullptr;
1694 cursor->previous_ = nullptr;
1695 }
1696
1697 new_block->instructions_.SetBlockOfInstructions(new_block);
1698
1699 for (HBasicBlock* successor : GetSuccessors()) {
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001700 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
1701 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001702 new_block->successors_.swap(successors_);
1703 DCHECK(successors_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001704
1705 for (HBasicBlock* dominated : GetDominatedBlocks()) {
1706 dominated->dominator_ = new_block;
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001707 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001708 new_block->dominated_blocks_.swap(dominated_blocks_);
1709 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001710 return new_block;
1711}
1712
1713HBasicBlock* HBasicBlock::SplitAfterForInlining(HInstruction* cursor) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001714 DCHECK(!cursor->IsControlFlow());
1715 DCHECK_NE(instructions_.last_instruction_, cursor);
1716 DCHECK_EQ(cursor->GetBlock(), this);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00001717
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001718 HBasicBlock* new_block = new (GetGraph()->GetArena()) HBasicBlock(GetGraph(), GetDexPc());
1719 new_block->instructions_.first_instruction_ = cursor->GetNext();
1720 new_block->instructions_.last_instruction_ = instructions_.last_instruction_;
1721 cursor->next_->previous_ = nullptr;
1722 cursor->next_ = nullptr;
1723 instructions_.last_instruction_ = cursor;
1724
1725 new_block->instructions_.SetBlockOfInstructions(new_block);
Vladimir Marko60584552015-09-03 13:35:12 +00001726 for (HBasicBlock* successor : GetSuccessors()) {
Vladimir Marko60584552015-09-03 13:35:12 +00001727 successor->predecessors_[successor->GetPredecessorIndexOf(this)] = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001728 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001729 new_block->successors_.swap(successors_);
1730 DCHECK(successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001731
Vladimir Marko60584552015-09-03 13:35:12 +00001732 for (HBasicBlock* dominated : GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001733 dominated->dominator_ = new_block;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001734 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00001735 new_block->dominated_blocks_.swap(dominated_blocks_);
1736 DCHECK(dominated_blocks_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001737 return new_block;
1738}
1739
David Brazdilec16f792015-08-19 15:04:01 +01001740const HTryBoundary* HBasicBlock::ComputeTryEntryOfSuccessors() const {
David Brazdilffee3d32015-07-06 11:48:53 +01001741 if (EndsWithTryBoundary()) {
1742 HTryBoundary* try_boundary = GetLastInstruction()->AsTryBoundary();
1743 if (try_boundary->IsEntry()) {
David Brazdilec16f792015-08-19 15:04:01 +01001744 DCHECK(!IsTryBlock());
David Brazdilffee3d32015-07-06 11:48:53 +01001745 return try_boundary;
1746 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001747 DCHECK(IsTryBlock());
1748 DCHECK(try_catch_information_->GetTryEntry().HasSameExceptionHandlersAs(*try_boundary));
David Brazdilffee3d32015-07-06 11:48:53 +01001749 return nullptr;
1750 }
David Brazdilec16f792015-08-19 15:04:01 +01001751 } else if (IsTryBlock()) {
1752 return &try_catch_information_->GetTryEntry();
David Brazdilffee3d32015-07-06 11:48:53 +01001753 } else {
David Brazdilec16f792015-08-19 15:04:01 +01001754 return nullptr;
David Brazdilffee3d32015-07-06 11:48:53 +01001755 }
David Brazdilfc6a86a2015-06-26 10:33:45 +00001756}
1757
David Brazdild7558da2015-09-22 13:04:14 +01001758bool HBasicBlock::HasThrowingInstructions() const {
1759 for (HInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1760 if (it.Current()->CanThrow()) {
1761 return true;
1762 }
1763 }
1764 return false;
1765}
1766
David Brazdilfc6a86a2015-06-26 10:33:45 +00001767static bool HasOnlyOneInstruction(const HBasicBlock& block) {
1768 return block.GetPhis().IsEmpty()
1769 && !block.GetInstructions().IsEmpty()
1770 && block.GetFirstInstruction() == block.GetLastInstruction();
1771}
1772
David Brazdil46e2a392015-03-16 17:31:52 +00001773bool HBasicBlock::IsSingleGoto() const {
David Brazdilfc6a86a2015-06-26 10:33:45 +00001774 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsGoto();
1775}
1776
1777bool HBasicBlock::IsSingleTryBoundary() const {
1778 return HasOnlyOneInstruction(*this) && GetLastInstruction()->IsTryBoundary();
David Brazdil46e2a392015-03-16 17:31:52 +00001779}
1780
David Brazdil8d5b8b22015-03-24 10:51:52 +00001781bool HBasicBlock::EndsWithControlFlowInstruction() const {
1782 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsControlFlow();
1783}
1784
David Brazdilb2bd1c52015-03-25 11:17:37 +00001785bool HBasicBlock::EndsWithIf() const {
1786 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsIf();
1787}
1788
David Brazdilffee3d32015-07-06 11:48:53 +01001789bool HBasicBlock::EndsWithTryBoundary() const {
1790 return !GetInstructions().IsEmpty() && GetLastInstruction()->IsTryBoundary();
1791}
1792
David Brazdilb2bd1c52015-03-25 11:17:37 +00001793bool HBasicBlock::HasSinglePhi() const {
1794 return !GetPhis().IsEmpty() && GetFirstPhi()->GetNext() == nullptr;
1795}
1796
David Brazdild26a4112015-11-10 11:07:31 +00001797ArrayRef<HBasicBlock* const> HBasicBlock::GetNormalSuccessors() const {
1798 if (EndsWithTryBoundary()) {
1799 // The normal-flow successor of HTryBoundary is always stored at index zero.
1800 DCHECK_EQ(successors_[0], GetLastInstruction()->AsTryBoundary()->GetNormalFlowSuccessor());
1801 return ArrayRef<HBasicBlock* const>(successors_).SubArray(0u, 1u);
1802 } else {
1803 // All successors of blocks not ending with TryBoundary are normal.
1804 return ArrayRef<HBasicBlock* const>(successors_);
1805 }
1806}
1807
1808ArrayRef<HBasicBlock* const> HBasicBlock::GetExceptionalSuccessors() const {
1809 if (EndsWithTryBoundary()) {
1810 return GetLastInstruction()->AsTryBoundary()->GetExceptionHandlers();
1811 } else {
1812 // Blocks not ending with TryBoundary do not have exceptional successors.
1813 return ArrayRef<HBasicBlock* const>();
1814 }
1815}
1816
David Brazdilffee3d32015-07-06 11:48:53 +01001817bool HTryBoundary::HasSameExceptionHandlersAs(const HTryBoundary& other) const {
David Brazdild26a4112015-11-10 11:07:31 +00001818 ArrayRef<HBasicBlock* const> handlers1 = GetExceptionHandlers();
1819 ArrayRef<HBasicBlock* const> handlers2 = other.GetExceptionHandlers();
1820
1821 size_t length = handlers1.size();
1822 if (length != handlers2.size()) {
David Brazdilffee3d32015-07-06 11:48:53 +01001823 return false;
1824 }
1825
David Brazdilb618ade2015-07-29 10:31:29 +01001826 // Exception handlers need to be stored in the same order.
David Brazdild26a4112015-11-10 11:07:31 +00001827 for (size_t i = 0; i < length; ++i) {
1828 if (handlers1[i] != handlers2[i]) {
David Brazdilffee3d32015-07-06 11:48:53 +01001829 return false;
1830 }
1831 }
1832 return true;
1833}
1834
David Brazdil2d7352b2015-04-20 14:52:42 +01001835size_t HInstructionList::CountSize() const {
1836 size_t size = 0;
1837 HInstruction* current = first_instruction_;
1838 for (; current != nullptr; current = current->GetNext()) {
1839 size++;
1840 }
1841 return size;
1842}
1843
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001844void HInstructionList::SetBlockOfInstructions(HBasicBlock* block) const {
1845 for (HInstruction* current = first_instruction_;
1846 current != nullptr;
1847 current = current->GetNext()) {
1848 current->SetBlock(block);
1849 }
1850}
1851
1852void HInstructionList::AddAfter(HInstruction* cursor, const HInstructionList& instruction_list) {
1853 DCHECK(Contains(cursor));
1854 if (!instruction_list.IsEmpty()) {
1855 if (cursor == last_instruction_) {
1856 last_instruction_ = instruction_list.last_instruction_;
1857 } else {
1858 cursor->next_->previous_ = instruction_list.last_instruction_;
1859 }
1860 instruction_list.last_instruction_->next_ = cursor->next_;
1861 cursor->next_ = instruction_list.first_instruction_;
1862 instruction_list.first_instruction_->previous_ = cursor;
1863 }
1864}
1865
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00001866void HInstructionList::AddBefore(HInstruction* cursor, const HInstructionList& instruction_list) {
1867 DCHECK(Contains(cursor));
1868 if (!instruction_list.IsEmpty()) {
1869 if (cursor == first_instruction_) {
1870 first_instruction_ = instruction_list.first_instruction_;
1871 } else {
1872 cursor->previous_->next_ = instruction_list.first_instruction_;
1873 }
1874 instruction_list.last_instruction_->next_ = cursor;
1875 instruction_list.first_instruction_->previous_ = cursor->previous_;
1876 cursor->previous_ = instruction_list.last_instruction_;
1877 }
1878}
1879
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00001880void HInstructionList::Add(const HInstructionList& instruction_list) {
David Brazdil46e2a392015-03-16 17:31:52 +00001881 if (IsEmpty()) {
1882 first_instruction_ = instruction_list.first_instruction_;
1883 last_instruction_ = instruction_list.last_instruction_;
1884 } else {
1885 AddAfter(last_instruction_, instruction_list);
1886 }
1887}
1888
David Brazdil04ff4e82015-12-10 13:54:52 +00001889// Should be called on instructions in a dead block in post order. This method
1890// assumes `insn` has been removed from all users with the exception of catch
1891// phis because of missing exceptional edges in the graph. It removes the
1892// instruction from catch phi uses, together with inputs of other catch phis in
1893// the catch block at the same index, as these must be dead too.
1894static void RemoveUsesOfDeadInstruction(HInstruction* insn) {
1895 DCHECK(!insn->HasEnvironmentUses());
1896 while (insn->HasNonEnvironmentUses()) {
Vladimir Marko46817b82016-03-29 12:21:58 +01001897 const HUseListNode<HInstruction*>& use = insn->GetUses().front();
1898 size_t use_index = use.GetIndex();
1899 HBasicBlock* user_block = use.GetUser()->GetBlock();
1900 DCHECK(use.GetUser()->IsPhi() && user_block->IsCatchBlock());
David Brazdil04ff4e82015-12-10 13:54:52 +00001901 for (HInstructionIterator phi_it(user_block->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1902 phi_it.Current()->AsPhi()->RemoveInputAt(use_index);
1903 }
1904 }
1905}
1906
David Brazdil2d7352b2015-04-20 14:52:42 +01001907void HBasicBlock::DisconnectAndDelete() {
1908 // Dominators must be removed after all the blocks they dominate. This way
1909 // a loop header is removed last, a requirement for correct loop information
1910 // iteration.
Vladimir Marko60584552015-09-03 13:35:12 +00001911 DCHECK(dominated_blocks_.empty());
David Brazdil46e2a392015-03-16 17:31:52 +00001912
David Brazdil9eeebf62016-03-24 11:18:15 +00001913 // The following steps gradually remove the block from all its dependants in
1914 // post order (b/27683071).
1915
1916 // (1) Store a basic block that we'll use in step (5) to find loops to be updated.
1917 // We need to do this before step (4) which destroys the predecessor list.
1918 HBasicBlock* loop_update_start = this;
1919 if (IsLoopHeader()) {
1920 HLoopInformation* loop_info = GetLoopInformation();
1921 // All other blocks in this loop should have been removed because the header
1922 // was their dominator.
1923 // Note that we do not remove `this` from `loop_info` as it is unreachable.
1924 DCHECK(!loop_info->IsIrreducible());
1925 DCHECK_EQ(loop_info->GetBlocks().NumSetBits(), 1u);
1926 DCHECK_EQ(static_cast<uint32_t>(loop_info->GetBlocks().GetHighestBitSet()), GetBlockId());
1927 loop_update_start = loop_info->GetPreHeader();
David Brazdil2d7352b2015-04-20 14:52:42 +01001928 }
1929
David Brazdil9eeebf62016-03-24 11:18:15 +00001930 // (2) Disconnect the block from its successors and update their phis.
1931 for (HBasicBlock* successor : successors_) {
1932 // Delete this block from the list of predecessors.
1933 size_t this_index = successor->GetPredecessorIndexOf(this);
1934 successor->predecessors_.erase(successor->predecessors_.begin() + this_index);
1935
1936 // Check that `successor` has other predecessors, otherwise `this` is the
1937 // dominator of `successor` which violates the order DCHECKed at the top.
1938 DCHECK(!successor->predecessors_.empty());
1939
1940 // Remove this block's entries in the successor's phis. Skip exceptional
1941 // successors because catch phi inputs do not correspond to predecessor
1942 // blocks but throwing instructions. The inputs of the catch phis will be
1943 // updated in step (3).
1944 if (!successor->IsCatchBlock()) {
1945 if (successor->predecessors_.size() == 1u) {
1946 // The successor has just one predecessor left. Replace phis with the only
1947 // remaining input.
1948 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1949 HPhi* phi = phi_it.Current()->AsPhi();
1950 phi->ReplaceWith(phi->InputAt(1 - this_index));
1951 successor->RemovePhi(phi);
1952 }
1953 } else {
1954 for (HInstructionIterator phi_it(successor->GetPhis()); !phi_it.Done(); phi_it.Advance()) {
1955 phi_it.Current()->AsPhi()->RemoveInputAt(this_index);
1956 }
1957 }
1958 }
1959 }
1960 successors_.clear();
1961
1962 // (3) Remove instructions and phis. Instructions should have no remaining uses
1963 // except in catch phis. If an instruction is used by a catch phi at `index`,
1964 // remove `index`-th input of all phis in the catch block since they are
1965 // guaranteed dead. Note that we may miss dead inputs this way but the
1966 // graph will always remain consistent.
1967 for (HBackwardInstructionIterator it(GetInstructions()); !it.Done(); it.Advance()) {
1968 HInstruction* insn = it.Current();
1969 RemoveUsesOfDeadInstruction(insn);
1970 RemoveInstruction(insn);
1971 }
1972 for (HInstructionIterator it(GetPhis()); !it.Done(); it.Advance()) {
1973 HPhi* insn = it.Current()->AsPhi();
1974 RemoveUsesOfDeadInstruction(insn);
1975 RemovePhi(insn);
1976 }
1977
1978 // (4) Disconnect the block from its predecessors and update their
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001979 // control-flow instructions.
Vladimir Marko60584552015-09-03 13:35:12 +00001980 for (HBasicBlock* predecessor : predecessors_) {
David Brazdil9eeebf62016-03-24 11:18:15 +00001981 // We should not see any back edges as they would have been removed by step (3).
1982 DCHECK(!IsInLoop() || !GetLoopInformation()->IsBackEdge(*predecessor));
1983
David Brazdil2d7352b2015-04-20 14:52:42 +01001984 HInstruction* last_instruction = predecessor->GetLastInstruction();
David Brazdil8a7c0fe2015-11-02 20:24:55 +00001985 if (last_instruction->IsTryBoundary() && !IsCatchBlock()) {
1986 // This block is the only normal-flow successor of the TryBoundary which
1987 // makes `predecessor` dead. Since DCE removes blocks in post order,
1988 // exception handlers of this TryBoundary were already visited and any
1989 // remaining handlers therefore must be live. We remove `predecessor` from
1990 // their list of predecessors.
1991 DCHECK_EQ(last_instruction->AsTryBoundary()->GetNormalFlowSuccessor(), this);
1992 while (predecessor->GetSuccessors().size() > 1) {
1993 HBasicBlock* handler = predecessor->GetSuccessors()[1];
1994 DCHECK(handler->IsCatchBlock());
1995 predecessor->RemoveSuccessor(handler);
1996 handler->RemovePredecessor(predecessor);
1997 }
1998 }
1999
David Brazdil2d7352b2015-04-20 14:52:42 +01002000 predecessor->RemoveSuccessor(this);
Mark Mendellfe57faa2015-09-18 09:26:15 -04002001 uint32_t num_pred_successors = predecessor->GetSuccessors().size();
2002 if (num_pred_successors == 1u) {
2003 // If we have one successor after removing one, then we must have
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002004 // had an HIf, HPackedSwitch or HTryBoundary, as they have more than one
2005 // successor. Replace those with a HGoto.
2006 DCHECK(last_instruction->IsIf() ||
2007 last_instruction->IsPackedSwitch() ||
2008 (last_instruction->IsTryBoundary() && IsCatchBlock()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002009 predecessor->RemoveInstruction(last_instruction);
Yevgeny Rouban3ecfd652015-09-07 17:57:00 +06002010 predecessor->AddInstruction(new (graph_->GetArena()) HGoto(last_instruction->GetDexPc()));
Mark Mendellfe57faa2015-09-18 09:26:15 -04002011 } else if (num_pred_successors == 0u) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002012 // The predecessor has no remaining successors and therefore must be dead.
2013 // We deliberately leave it without a control-flow instruction so that the
David Brazdilbadd8262016-02-02 16:28:56 +00002014 // GraphChecker fails unless it is not removed during the pass too.
Mark Mendellfe57faa2015-09-18 09:26:15 -04002015 predecessor->RemoveInstruction(last_instruction);
2016 } else {
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002017 // There are multiple successors left. The removed block might be a successor
2018 // of a PackedSwitch which will be completely removed (perhaps replaced with
2019 // a Goto), or we are deleting a catch block from a TryBoundary. In either
2020 // case, leave `last_instruction` as is for now.
2021 DCHECK(last_instruction->IsPackedSwitch() ||
2022 (last_instruction->IsTryBoundary() && IsCatchBlock()));
David Brazdil2d7352b2015-04-20 14:52:42 +01002023 }
David Brazdil46e2a392015-03-16 17:31:52 +00002024 }
Vladimir Marko60584552015-09-03 13:35:12 +00002025 predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002026
David Brazdil9eeebf62016-03-24 11:18:15 +00002027 // (5) Remove the block from all loops it is included in. Skip the inner-most
2028 // loop if this is the loop header (see definition of `loop_update_start`)
2029 // because the loop header's predecessor list has been destroyed in step (4).
2030 for (HLoopInformationOutwardIterator it(*loop_update_start); !it.Done(); it.Advance()) {
2031 HLoopInformation* loop_info = it.Current();
2032 loop_info->Remove(this);
2033 if (loop_info->IsBackEdge(*this)) {
2034 // If this was the last back edge of the loop, we deliberately leave the
2035 // loop in an inconsistent state and will fail GraphChecker unless the
2036 // entire loop is removed during the pass.
2037 loop_info->RemoveBackEdge(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002038 }
2039 }
David Brazdil2d7352b2015-04-20 14:52:42 +01002040
David Brazdil9eeebf62016-03-24 11:18:15 +00002041 // (6) Disconnect from the dominator.
David Brazdil2d7352b2015-04-20 14:52:42 +01002042 dominator_->RemoveDominatedBlock(this);
2043 SetDominator(nullptr);
2044
David Brazdil9eeebf62016-03-24 11:18:15 +00002045 // (7) Delete from the graph, update reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002046 graph_->DeleteDeadEmptyBlock(this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002047 SetGraph(nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002048}
2049
Aart Bik6b69e0a2017-01-11 10:20:43 -08002050void HBasicBlock::MergeInstructionsWith(HBasicBlock* other) {
2051 DCHECK(EndsWithControlFlowInstruction());
2052 RemoveInstruction(GetLastInstruction());
2053 instructions_.Add(other->GetInstructions());
2054 other->instructions_.SetBlockOfInstructions(this);
2055 other->instructions_.Clear();
2056}
2057
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002058void HBasicBlock::MergeWith(HBasicBlock* other) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002059 DCHECK_EQ(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002060 DCHECK(ContainsElement(dominated_blocks_, other));
2061 DCHECK_EQ(GetSingleSuccessor(), other);
2062 DCHECK_EQ(other->GetSinglePredecessor(), this);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002063 DCHECK(other->GetPhis().IsEmpty());
2064
David Brazdil2d7352b2015-04-20 14:52:42 +01002065 // Move instructions from `other` to `this`.
Aart Bik6b69e0a2017-01-11 10:20:43 -08002066 MergeInstructionsWith(other);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002067
David Brazdil2d7352b2015-04-20 14:52:42 +01002068 // Remove `other` from the loops it is included in.
2069 for (HLoopInformationOutwardIterator it(*other); !it.Done(); it.Advance()) {
2070 HLoopInformation* loop_info = it.Current();
2071 loop_info->Remove(other);
2072 if (loop_info->IsBackEdge(*other)) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01002073 loop_info->ReplaceBackEdge(other, this);
David Brazdil2d7352b2015-04-20 14:52:42 +01002074 }
2075 }
2076
2077 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002078 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002079 for (HBasicBlock* successor : other->GetSuccessors()) {
2080 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002081 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002082 successors_.swap(other->successors_);
2083 DCHECK(other->successors_.empty());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002084
David Brazdil2d7352b2015-04-20 14:52:42 +01002085 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002086 RemoveDominatedBlock(other);
2087 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002088 dominated->SetDominator(this);
2089 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002090 dominated_blocks_.insert(
2091 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002092 other->dominated_blocks_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002093 other->dominator_ = nullptr;
2094
2095 // Clear the list of predecessors of `other` in preparation of deleting it.
Vladimir Marko60584552015-09-03 13:35:12 +00002096 other->predecessors_.clear();
David Brazdil2d7352b2015-04-20 14:52:42 +01002097
2098 // Delete `other` from the graph. The function updates reverse post order.
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002099 graph_->DeleteDeadEmptyBlock(other);
David Brazdil2d7352b2015-04-20 14:52:42 +01002100 other->SetGraph(nullptr);
2101}
2102
2103void HBasicBlock::MergeWithInlined(HBasicBlock* other) {
2104 DCHECK_NE(GetGraph(), other->GetGraph());
Vladimir Marko60584552015-09-03 13:35:12 +00002105 DCHECK(GetDominatedBlocks().empty());
2106 DCHECK(GetSuccessors().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002107 DCHECK(!EndsWithControlFlowInstruction());
Vladimir Marko60584552015-09-03 13:35:12 +00002108 DCHECK(other->GetSinglePredecessor()->IsEntryBlock());
David Brazdil2d7352b2015-04-20 14:52:42 +01002109 DCHECK(other->GetPhis().IsEmpty());
2110 DCHECK(!other->IsInLoop());
2111
2112 // Move instructions from `other` to `this`.
2113 instructions_.Add(other->GetInstructions());
2114 other->instructions_.SetBlockOfInstructions(this);
2115
2116 // Update links to the successors of `other`.
Vladimir Marko60584552015-09-03 13:35:12 +00002117 successors_.clear();
Vladimir Marko661b69b2016-11-09 14:11:37 +00002118 for (HBasicBlock* successor : other->GetSuccessors()) {
2119 successor->predecessors_[successor->GetPredecessorIndexOf(other)] = this;
David Brazdil2d7352b2015-04-20 14:52:42 +01002120 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002121 successors_.swap(other->successors_);
2122 DCHECK(other->successors_.empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002123
2124 // Update the dominator tree.
Vladimir Marko60584552015-09-03 13:35:12 +00002125 for (HBasicBlock* dominated : other->GetDominatedBlocks()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002126 dominated->SetDominator(this);
2127 }
Vladimir Marko661b69b2016-11-09 14:11:37 +00002128 dominated_blocks_.insert(
2129 dominated_blocks_.end(), other->dominated_blocks_.begin(), other->dominated_blocks_.end());
Vladimir Marko60584552015-09-03 13:35:12 +00002130 other->dominated_blocks_.clear();
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002131 other->dominator_ = nullptr;
2132 other->graph_ = nullptr;
2133}
2134
2135void HBasicBlock::ReplaceWith(HBasicBlock* other) {
Vladimir Marko60584552015-09-03 13:35:12 +00002136 while (!GetPredecessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002137 HBasicBlock* predecessor = GetPredecessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002138 predecessor->ReplaceSuccessor(this, other);
2139 }
Vladimir Marko60584552015-09-03 13:35:12 +00002140 while (!GetSuccessors().empty()) {
Vladimir Markoec7802a2015-10-01 20:57:57 +01002141 HBasicBlock* successor = GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002142 successor->ReplacePredecessor(this, other);
2143 }
Vladimir Marko60584552015-09-03 13:35:12 +00002144 for (HBasicBlock* dominated : GetDominatedBlocks()) {
2145 other->AddDominatedBlock(dominated);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002146 }
2147 GetDominator()->ReplaceDominatedBlock(this, other);
2148 other->SetDominator(GetDominator());
2149 dominator_ = nullptr;
2150 graph_ = nullptr;
2151}
2152
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002153void HGraph::DeleteDeadEmptyBlock(HBasicBlock* block) {
David Brazdil2d7352b2015-04-20 14:52:42 +01002154 DCHECK_EQ(block->GetGraph(), this);
Vladimir Marko60584552015-09-03 13:35:12 +00002155 DCHECK(block->GetSuccessors().empty());
2156 DCHECK(block->GetPredecessors().empty());
2157 DCHECK(block->GetDominatedBlocks().empty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002158 DCHECK(block->GetDominator() == nullptr);
David Brazdil8a7c0fe2015-11-02 20:24:55 +00002159 DCHECK(block->GetInstructions().IsEmpty());
2160 DCHECK(block->GetPhis().IsEmpty());
David Brazdil2d7352b2015-04-20 14:52:42 +01002161
David Brazdilc7af85d2015-05-26 12:05:55 +01002162 if (block->IsExitBlock()) {
Serguei Katkov7ba99662016-03-02 16:25:36 +06002163 SetExitBlock(nullptr);
David Brazdilc7af85d2015-05-26 12:05:55 +01002164 }
2165
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002166 RemoveElement(reverse_post_order_, block);
2167 blocks_[block->GetBlockId()] = nullptr;
David Brazdil86ea7ee2016-02-16 09:26:07 +00002168 block->SetGraph(nullptr);
David Brazdil2d7352b2015-04-20 14:52:42 +01002169}
2170
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002171void HGraph::UpdateLoopAndTryInformationOfNewBlock(HBasicBlock* block,
2172 HBasicBlock* reference,
2173 bool replace_if_back_edge) {
2174 if (block->IsLoopHeader()) {
2175 // Clear the information of which blocks are contained in that loop. Since the
2176 // information is stored as a bit vector based on block ids, we have to update
2177 // it, as those block ids were specific to the callee graph and we are now adding
2178 // these blocks to the caller graph.
2179 block->GetLoopInformation()->ClearAllBlocks();
2180 }
2181
2182 // If not already in a loop, update the loop information.
2183 if (!block->IsInLoop()) {
2184 block->SetLoopInformation(reference->GetLoopInformation());
2185 }
2186
2187 // If the block is in a loop, update all its outward loops.
2188 HLoopInformation* loop_info = block->GetLoopInformation();
2189 if (loop_info != nullptr) {
2190 for (HLoopInformationOutwardIterator loop_it(*block);
2191 !loop_it.Done();
2192 loop_it.Advance()) {
2193 loop_it.Current()->Add(block);
2194 }
2195 if (replace_if_back_edge && loop_info->IsBackEdge(*reference)) {
2196 loop_info->ReplaceBackEdge(reference, block);
2197 }
2198 }
2199
2200 // Copy TryCatchInformation if `reference` is a try block, not if it is a catch block.
2201 TryCatchInformation* try_catch_info = reference->IsTryBlock()
2202 ? reference->GetTryCatchInformation()
2203 : nullptr;
2204 block->SetTryCatchInformation(try_catch_info);
2205}
2206
Calin Juravle2e768302015-07-28 14:41:11 +00002207HInstruction* HGraph::InlineInto(HGraph* outer_graph, HInvoke* invoke) {
David Brazdilc7af85d2015-05-26 12:05:55 +01002208 DCHECK(HasExitBlock()) << "Unimplemented scenario";
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002209 // Update the environments in this graph to have the invoke's environment
2210 // as parent.
2211 {
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002212 // Skip the entry block, we do not need to update the entry's suspend check.
2213 for (HBasicBlock* block : GetReversePostOrderSkipEntryBlock()) {
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002214 for (HInstructionIterator instr_it(block->GetInstructions());
2215 !instr_it.Done();
2216 instr_it.Advance()) {
2217 HInstruction* current = instr_it.Current();
2218 if (current->NeedsEnvironment()) {
David Brazdildee58d62016-04-07 09:54:26 +00002219 DCHECK(current->HasEnvironment());
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002220 current->GetEnvironment()->SetAndCopyParentChain(
2221 outer_graph->GetArena(), invoke->GetEnvironment());
2222 }
2223 }
2224 }
2225 }
2226 outer_graph->UpdateMaximumNumberOfOutVRegs(GetMaximumNumberOfOutVRegs());
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002227
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002228 if (HasBoundsChecks()) {
2229 outer_graph->SetHasBoundsChecks(true);
2230 }
Mingyao Yang69d75ff2017-02-07 13:06:06 -08002231 if (HasLoops()) {
2232 outer_graph->SetHasLoops(true);
2233 }
2234 if (HasIrreducibleLoops()) {
2235 outer_graph->SetHasIrreducibleLoops(true);
2236 }
2237 if (HasTryCatch()) {
2238 outer_graph->SetHasTryCatch(true);
2239 }
Aart Bikb13c65b2017-03-21 20:14:07 -07002240 if (HasSIMD()) {
2241 outer_graph->SetHasSIMD(true);
2242 }
Nicolas Geoffrayd23eeef2015-05-18 22:31:29 +01002243
Calin Juravle2e768302015-07-28 14:41:11 +00002244 HInstruction* return_value = nullptr;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002245 if (GetBlocks().size() == 3) {
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002246 // Inliner already made sure we don't inline methods that always throw.
2247 DCHECK(!GetBlocks()[1]->GetLastInstruction()->IsThrow());
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002248 // Simple case of an entry block, a body block, and an exit block.
2249 // Put the body block's instruction into `invoke`'s block.
Vladimir Markoec7802a2015-10-01 20:57:57 +01002250 HBasicBlock* body = GetBlocks()[1];
2251 DCHECK(GetBlocks()[0]->IsEntryBlock());
2252 DCHECK(GetBlocks()[2]->IsExitBlock());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002253 DCHECK(!body->IsExitBlock());
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002254 DCHECK(!body->IsInLoop());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002255 HInstruction* last = body->GetLastInstruction();
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002256
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002257 // Note that we add instructions before the invoke only to simplify polymorphic inlining.
2258 invoke->GetBlock()->instructions_.AddBefore(invoke, body->GetInstructions());
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002259 body->GetInstructions().SetBlockOfInstructions(invoke->GetBlock());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002260
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002261 // Replace the invoke with the return value of the inlined graph.
2262 if (last->IsReturn()) {
Calin Juravle2e768302015-07-28 14:41:11 +00002263 return_value = last->InputAt(0);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002264 } else {
2265 DCHECK(last->IsReturnVoid());
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002266 }
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002267
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002268 invoke->GetBlock()->RemoveInstruction(last);
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002269 } else {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002270 // Need to inline multiple blocks. We split `invoke`'s block
2271 // into two blocks, merge the first block of the inlined graph into
Nicolas Geoffraybe31ff92015-02-04 14:52:20 +00002272 // the first half, and replace the exit block of the inlined graph
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002273 // with the second half.
2274 ArenaAllocator* allocator = outer_graph->GetArena();
2275 HBasicBlock* at = invoke->GetBlock();
Nicolas Geoffray916cc1d2016-02-18 11:12:31 +00002276 // Note that we split before the invoke only to simplify polymorphic inlining.
2277 HBasicBlock* to = at->SplitBeforeForInlining(invoke);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002278
Vladimir Markoec7802a2015-10-01 20:57:57 +01002279 HBasicBlock* first = entry_block_->GetSuccessors()[0];
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002280 DCHECK(!first->IsInLoop());
David Brazdil2d7352b2015-04-20 14:52:42 +01002281 at->MergeWithInlined(first);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002282 exit_block_->ReplaceWith(to);
2283
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002284 // Update the meta information surrounding blocks:
2285 // (1) the graph they are now in,
2286 // (2) the reverse post order of that graph,
Nicolas Geoffray788f2f02016-01-22 12:41:38 +00002287 // (3) their potential loop information, inner and outer,
David Brazdil95177982015-10-30 12:56:58 -05002288 // (4) try block membership.
David Brazdil59a850e2015-11-10 13:04:30 +00002289 // Note that we do not need to update catch phi inputs because they
2290 // correspond to the register file of the outer method which the inlinee
2291 // cannot modify.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002292
2293 // We don't add the entry block, the exit block, and the first block, which
2294 // has been merged with `at`.
2295 static constexpr int kNumberOfSkippedBlocksInCallee = 3;
2296
2297 // We add the `to` block.
2298 static constexpr int kNumberOfNewBlocksInCaller = 1;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002299 size_t blocks_added = (reverse_post_order_.size() - kNumberOfSkippedBlocksInCallee)
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002300 + kNumberOfNewBlocksInCaller;
2301
2302 // Find the location of `at` in the outer graph's reverse post order. The new
2303 // blocks will be added after it.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002304 size_t index_of_at = IndexOfElement(outer_graph->reverse_post_order_, at);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002305 MakeRoomFor(&outer_graph->reverse_post_order_, blocks_added, index_of_at);
2306
David Brazdil95177982015-10-30 12:56:58 -05002307 // Do a reverse post order of the blocks in the callee and do (1), (2), (3)
2308 // and (4) to the blocks that apply.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01002309 for (HBasicBlock* current : GetReversePostOrder()) {
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002310 if (current != exit_block_ && current != entry_block_ && current != first) {
David Brazdil95177982015-10-30 12:56:58 -05002311 DCHECK(current->GetTryCatchInformation() == nullptr);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002312 DCHECK(current->GetGraph() == this);
2313 current->SetGraph(outer_graph);
2314 outer_graph->AddBlock(current);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002315 outer_graph->reverse_post_order_[++index_of_at] = current;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002316 UpdateLoopAndTryInformationOfNewBlock(current, at, /* replace_if_back_edge */ false);
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002317 }
2318 }
2319
David Brazdil95177982015-10-30 12:56:58 -05002320 // Do (1), (2), (3) and (4) to `to`.
Nicolas Geoffray276d9da2015-02-02 18:24:11 +00002321 to->SetGraph(outer_graph);
2322 outer_graph->AddBlock(to);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002323 outer_graph->reverse_post_order_[++index_of_at] = to;
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002324 // Only `to` can become a back edge, as the inlined blocks
2325 // are predecessors of `to`.
2326 UpdateLoopAndTryInformationOfNewBlock(to, at, /* replace_if_back_edge */ true);
Nicolas Geoffray7c5367b2014-12-17 10:13:46 +00002327
David Brazdil3f523062016-02-29 16:53:33 +00002328 // Update all predecessors of the exit block (now the `to` block)
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002329 // to not `HReturn` but `HGoto` instead. Special case throwing blocks
2330 // to now get the outer graph exit block as successor. Note that the inliner
2331 // currently doesn't support inlining methods with try/catch.
2332 HPhi* return_value_phi = nullptr;
2333 bool rerun_dominance = false;
2334 bool rerun_loop_analysis = false;
2335 for (size_t pred = 0; pred < to->GetPredecessors().size(); ++pred) {
2336 HBasicBlock* predecessor = to->GetPredecessors()[pred];
David Brazdil3f523062016-02-29 16:53:33 +00002337 HInstruction* last = predecessor->GetLastInstruction();
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002338 if (last->IsThrow()) {
2339 DCHECK(!at->IsTryBlock());
2340 predecessor->ReplaceSuccessor(to, outer_graph->GetExitBlock());
2341 --pred;
2342 // We need to re-run dominance information, as the exit block now has
2343 // a new dominator.
2344 rerun_dominance = true;
2345 if (predecessor->GetLoopInformation() != nullptr) {
2346 // The exit block and blocks post dominated by the exit block do not belong
2347 // to any loop. Because we do not compute the post dominators, we need to re-run
2348 // loop analysis to get the loop information correct.
2349 rerun_loop_analysis = true;
2350 }
2351 } else {
2352 if (last->IsReturnVoid()) {
2353 DCHECK(return_value == nullptr);
2354 DCHECK(return_value_phi == nullptr);
2355 } else {
David Brazdil3f523062016-02-29 16:53:33 +00002356 DCHECK(last->IsReturn());
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002357 if (return_value_phi != nullptr) {
2358 return_value_phi->AddInput(last->InputAt(0));
2359 } else if (return_value == nullptr) {
2360 return_value = last->InputAt(0);
2361 } else {
2362 // There will be multiple returns.
2363 return_value_phi = new (allocator) HPhi(
2364 allocator, kNoRegNumber, 0, HPhi::ToPhiType(invoke->GetType()), to->GetDexPc());
2365 to->AddPhi(return_value_phi);
2366 return_value_phi->AddInput(return_value);
2367 return_value_phi->AddInput(last->InputAt(0));
2368 return_value = return_value_phi;
2369 }
David Brazdil3f523062016-02-29 16:53:33 +00002370 }
2371 predecessor->AddInstruction(new (allocator) HGoto(last->GetDexPc()));
2372 predecessor->RemoveInstruction(last);
2373 }
2374 }
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002375 if (rerun_loop_analysis) {
Nicolas Geoffray1eede6a2017-03-02 16:14:53 +00002376 DCHECK(!outer_graph->HasIrreducibleLoops())
2377 << "Recomputing loop information in graphs with irreducible loops "
2378 << "is unsupported, as it could lead to loop header changes";
Nicolas Geoffrayfdb7d632017-02-08 15:07:18 +00002379 outer_graph->ClearLoopInformation();
2380 outer_graph->ClearDominanceInformation();
2381 outer_graph->BuildDominatorTree();
2382 } else if (rerun_dominance) {
2383 outer_graph->ClearDominanceInformation();
2384 outer_graph->ComputeDominanceInformation();
2385 }
David Brazdil3f523062016-02-29 16:53:33 +00002386 }
David Brazdil05144f42015-04-16 15:18:00 +01002387
2388 // Walk over the entry block and:
2389 // - Move constants from the entry block to the outer_graph's entry block,
2390 // - Replace HParameterValue instructions with their real value.
2391 // - Remove suspend checks, that hold an environment.
2392 // We must do this after the other blocks have been inlined, otherwise ids of
2393 // constants could overlap with the inner graph.
Roland Levillain4c0eb422015-04-24 16:43:49 +01002394 size_t parameter_index = 0;
David Brazdil05144f42015-04-16 15:18:00 +01002395 for (HInstructionIterator it(entry_block_->GetInstructions()); !it.Done(); it.Advance()) {
2396 HInstruction* current = it.Current();
Calin Juravle214bbcd2015-10-20 14:54:07 +01002397 HInstruction* replacement = nullptr;
David Brazdil05144f42015-04-16 15:18:00 +01002398 if (current->IsNullConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002399 replacement = outer_graph->GetNullConstant(current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002400 } else if (current->IsIntConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002401 replacement = outer_graph->GetIntConstant(
2402 current->AsIntConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002403 } else if (current->IsLongConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002404 replacement = outer_graph->GetLongConstant(
2405 current->AsLongConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002406 } else if (current->IsFloatConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002407 replacement = outer_graph->GetFloatConstant(
2408 current->AsFloatConstant()->GetValue(), current->GetDexPc());
Nicolas Geoffrayf213e052015-04-27 08:53:46 +00002409 } else if (current->IsDoubleConstant()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002410 replacement = outer_graph->GetDoubleConstant(
2411 current->AsDoubleConstant()->GetValue(), current->GetDexPc());
David Brazdil05144f42015-04-16 15:18:00 +01002412 } else if (current->IsParameterValue()) {
Roland Levillain4c0eb422015-04-24 16:43:49 +01002413 if (kIsDebugBuild
2414 && invoke->IsInvokeStaticOrDirect()
2415 && invoke->AsInvokeStaticOrDirect()->IsStaticWithExplicitClinitCheck()) {
2416 // Ensure we do not use the last input of `invoke`, as it
2417 // contains a clinit check which is not an actual argument.
2418 size_t last_input_index = invoke->InputCount() - 1;
2419 DCHECK(parameter_index != last_input_index);
2420 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002421 replacement = invoke->InputAt(parameter_index++);
Nicolas Geoffray76b1e172015-05-27 17:18:33 +01002422 } else if (current->IsCurrentMethod()) {
Calin Juravle214bbcd2015-10-20 14:54:07 +01002423 replacement = outer_graph->GetCurrentMethod();
David Brazdil05144f42015-04-16 15:18:00 +01002424 } else {
2425 DCHECK(current->IsGoto() || current->IsSuspendCheck());
2426 entry_block_->RemoveInstruction(current);
2427 }
Calin Juravle214bbcd2015-10-20 14:54:07 +01002428 if (replacement != nullptr) {
2429 current->ReplaceWith(replacement);
2430 // If the current is the return value then we need to update the latter.
2431 if (current == return_value) {
2432 DCHECK_EQ(entry_block_, return_value->GetBlock());
2433 return_value = replacement;
2434 }
2435 }
2436 }
2437
Calin Juravle2e768302015-07-28 14:41:11 +00002438 return return_value;
Nicolas Geoffraye53798a2014-12-01 10:31:54 +00002439}
2440
Mingyao Yang3584bce2015-05-19 16:01:59 -07002441/*
2442 * Loop will be transformed to:
2443 * old_pre_header
2444 * |
2445 * if_block
2446 * / \
Aart Bik3fc7f352015-11-20 22:03:03 -08002447 * true_block false_block
Mingyao Yang3584bce2015-05-19 16:01:59 -07002448 * \ /
2449 * new_pre_header
2450 * |
2451 * header
2452 */
2453void HGraph::TransformLoopHeaderForBCE(HBasicBlock* header) {
2454 DCHECK(header->IsLoopHeader());
Aart Bik3fc7f352015-11-20 22:03:03 -08002455 HBasicBlock* old_pre_header = header->GetDominator();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002456
Aart Bik3fc7f352015-11-20 22:03:03 -08002457 // Need extra block to avoid critical edge.
Mingyao Yang3584bce2015-05-19 16:01:59 -07002458 HBasicBlock* if_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Aart Bik3fc7f352015-11-20 22:03:03 -08002459 HBasicBlock* true_block = new (arena_) HBasicBlock(this, header->GetDexPc());
2460 HBasicBlock* false_block = new (arena_) HBasicBlock(this, header->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -07002461 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2462 AddBlock(if_block);
Aart Bik3fc7f352015-11-20 22:03:03 -08002463 AddBlock(true_block);
2464 AddBlock(false_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002465 AddBlock(new_pre_header);
2466
Aart Bik3fc7f352015-11-20 22:03:03 -08002467 header->ReplacePredecessor(old_pre_header, new_pre_header);
2468 old_pre_header->successors_.clear();
2469 old_pre_header->dominated_blocks_.clear();
Mingyao Yang3584bce2015-05-19 16:01:59 -07002470
Aart Bik3fc7f352015-11-20 22:03:03 -08002471 old_pre_header->AddSuccessor(if_block);
2472 if_block->AddSuccessor(true_block); // True successor
2473 if_block->AddSuccessor(false_block); // False successor
2474 true_block->AddSuccessor(new_pre_header);
2475 false_block->AddSuccessor(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002476
Aart Bik3fc7f352015-11-20 22:03:03 -08002477 old_pre_header->dominated_blocks_.push_back(if_block);
2478 if_block->SetDominator(old_pre_header);
2479 if_block->dominated_blocks_.push_back(true_block);
2480 true_block->SetDominator(if_block);
2481 if_block->dominated_blocks_.push_back(false_block);
2482 false_block->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002483 if_block->dominated_blocks_.push_back(new_pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002484 new_pre_header->SetDominator(if_block);
Vladimir Marko60584552015-09-03 13:35:12 +00002485 new_pre_header->dominated_blocks_.push_back(header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002486 header->SetDominator(new_pre_header);
2487
Aart Bik3fc7f352015-11-20 22:03:03 -08002488 // Fix reverse post order.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002489 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002490 MakeRoomFor(&reverse_post_order_, 4, index_of_header - 1);
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002491 reverse_post_order_[index_of_header++] = if_block;
Aart Bik3fc7f352015-11-20 22:03:03 -08002492 reverse_post_order_[index_of_header++] = true_block;
2493 reverse_post_order_[index_of_header++] = false_block;
Vladimir Markofa6b93c2015-09-15 10:15:55 +01002494 reverse_post_order_[index_of_header++] = new_pre_header;
Mingyao Yang3584bce2015-05-19 16:01:59 -07002495
Nicolas Geoffraya1d8ddf2016-02-29 11:46:58 +00002496 // The pre_header can never be a back edge of a loop.
2497 DCHECK((old_pre_header->GetLoopInformation() == nullptr) ||
2498 !old_pre_header->GetLoopInformation()->IsBackEdge(*old_pre_header));
2499 UpdateLoopAndTryInformationOfNewBlock(
2500 if_block, old_pre_header, /* replace_if_back_edge */ false);
2501 UpdateLoopAndTryInformationOfNewBlock(
2502 true_block, old_pre_header, /* replace_if_back_edge */ false);
2503 UpdateLoopAndTryInformationOfNewBlock(
2504 false_block, old_pre_header, /* replace_if_back_edge */ false);
2505 UpdateLoopAndTryInformationOfNewBlock(
2506 new_pre_header, old_pre_header, /* replace_if_back_edge */ false);
Mingyao Yang3584bce2015-05-19 16:01:59 -07002507}
2508
Aart Bikf8f5a162017-02-06 15:35:29 -08002509HBasicBlock* HGraph::TransformLoopForVectorization(HBasicBlock* header,
2510 HBasicBlock* body,
2511 HBasicBlock* exit) {
2512 DCHECK(header->IsLoopHeader());
2513 HLoopInformation* loop = header->GetLoopInformation();
2514
2515 // Add new loop blocks.
2516 HBasicBlock* new_pre_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2517 HBasicBlock* new_header = new (arena_) HBasicBlock(this, header->GetDexPc());
2518 HBasicBlock* new_body = new (arena_) HBasicBlock(this, header->GetDexPc());
2519 AddBlock(new_pre_header);
2520 AddBlock(new_header);
2521 AddBlock(new_body);
2522
2523 // Set up control flow.
2524 header->ReplaceSuccessor(exit, new_pre_header);
2525 new_pre_header->AddSuccessor(new_header);
2526 new_header->AddSuccessor(exit);
2527 new_header->AddSuccessor(new_body);
2528 new_body->AddSuccessor(new_header);
2529
2530 // Set up dominators.
2531 header->ReplaceDominatedBlock(exit, new_pre_header);
2532 new_pre_header->SetDominator(header);
2533 new_pre_header->dominated_blocks_.push_back(new_header);
2534 new_header->SetDominator(new_pre_header);
2535 new_header->dominated_blocks_.push_back(new_body);
2536 new_body->SetDominator(new_header);
2537 new_header->dominated_blocks_.push_back(exit);
2538 exit->SetDominator(new_header);
2539
2540 // Fix reverse post order.
2541 size_t index_of_header = IndexOfElement(reverse_post_order_, header);
2542 MakeRoomFor(&reverse_post_order_, 2, index_of_header);
2543 reverse_post_order_[++index_of_header] = new_pre_header;
2544 reverse_post_order_[++index_of_header] = new_header;
2545 size_t index_of_body = IndexOfElement(reverse_post_order_, body);
2546 MakeRoomFor(&reverse_post_order_, 1, index_of_body - 1);
2547 reverse_post_order_[index_of_body] = new_body;
2548
Aart Bikb07d1bc2017-04-05 10:03:15 -07002549 // Add gotos and suspend check (client must add conditional in header).
Aart Bikf8f5a162017-02-06 15:35:29 -08002550 new_pre_header->AddInstruction(new (arena_) HGoto());
2551 HSuspendCheck* suspend_check = new (arena_) HSuspendCheck(header->GetDexPc());
2552 new_header->AddInstruction(suspend_check);
2553 new_body->AddInstruction(new (arena_) HGoto());
Aart Bikb07d1bc2017-04-05 10:03:15 -07002554 suspend_check->CopyEnvironmentFromWithLoopPhiAdjustment(
2555 loop->GetSuspendCheck()->GetEnvironment(), header);
Aart Bikf8f5a162017-02-06 15:35:29 -08002556
2557 // Update loop information.
2558 new_header->AddBackEdge(new_body);
2559 new_header->GetLoopInformation()->SetSuspendCheck(suspend_check);
2560 new_header->GetLoopInformation()->Populate();
2561 new_pre_header->SetLoopInformation(loop->GetPreHeader()->GetLoopInformation()); // outward
2562 HLoopInformationOutwardIterator it(*new_header);
2563 for (it.Advance(); !it.Done(); it.Advance()) {
2564 it.Current()->Add(new_pre_header);
2565 it.Current()->Add(new_header);
2566 it.Current()->Add(new_body);
2567 }
2568 return new_pre_header;
2569}
2570
David Brazdilf5552582015-12-27 13:36:12 +00002571static void CheckAgainstUpperBound(ReferenceTypeInfo rti, ReferenceTypeInfo upper_bound_rti)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002572 REQUIRES_SHARED(Locks::mutator_lock_) {
David Brazdilf5552582015-12-27 13:36:12 +00002573 if (rti.IsValid()) {
2574 DCHECK(upper_bound_rti.IsSupertypeOf(rti))
2575 << " upper_bound_rti: " << upper_bound_rti
2576 << " rti: " << rti;
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002577 DCHECK(!upper_bound_rti.GetTypeHandle()->CannotBeAssignedFromOtherTypes() || rti.IsExact())
2578 << " upper_bound_rti: " << upper_bound_rti
2579 << " rti: " << rti;
David Brazdilf5552582015-12-27 13:36:12 +00002580 }
2581}
2582
Calin Juravle2e768302015-07-28 14:41:11 +00002583void HInstruction::SetReferenceTypeInfo(ReferenceTypeInfo rti) {
2584 if (kIsDebugBuild) {
2585 DCHECK_EQ(GetType(), Primitive::kPrimNot);
2586 ScopedObjectAccess soa(Thread::Current());
2587 DCHECK(rti.IsValid()) << "Invalid RTI for " << DebugName();
2588 if (IsBoundType()) {
2589 // Having the test here spares us from making the method virtual just for
2590 // the sake of a DCHECK.
David Brazdilf5552582015-12-27 13:36:12 +00002591 CheckAgainstUpperBound(rti, AsBoundType()->GetUpperBound());
Calin Juravle2e768302015-07-28 14:41:11 +00002592 }
2593 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002594 reference_type_handle_ = rti.GetTypeHandle();
2595 SetPackedFlag<kFlagReferenceTypeIsExact>(rti.IsExact());
Calin Juravle2e768302015-07-28 14:41:11 +00002596}
2597
David Brazdilf5552582015-12-27 13:36:12 +00002598void HBoundType::SetUpperBound(const ReferenceTypeInfo& upper_bound, bool can_be_null) {
2599 if (kIsDebugBuild) {
2600 ScopedObjectAccess soa(Thread::Current());
2601 DCHECK(upper_bound.IsValid());
2602 DCHECK(!upper_bound_.IsValid()) << "Upper bound should only be set once.";
2603 CheckAgainstUpperBound(GetReferenceTypeInfo(), upper_bound);
2604 }
2605 upper_bound_ = upper_bound;
Vladimir Markoa1de9182016-02-25 11:37:38 +00002606 SetPackedFlag<kFlagUpperCanBeNull>(can_be_null);
David Brazdilf5552582015-12-27 13:36:12 +00002607}
2608
Vladimir Markoa1de9182016-02-25 11:37:38 +00002609ReferenceTypeInfo ReferenceTypeInfo::Create(TypeHandle type_handle, bool is_exact) {
Calin Juravle2e768302015-07-28 14:41:11 +00002610 if (kIsDebugBuild) {
2611 ScopedObjectAccess soa(Thread::Current());
2612 DCHECK(IsValidHandle(type_handle));
Nicolas Geoffray18401b72016-03-11 13:35:51 +00002613 if (!is_exact) {
2614 DCHECK(!type_handle->CannotBeAssignedFromOtherTypes())
2615 << "Callers of ReferenceTypeInfo::Create should ensure is_exact is properly computed";
2616 }
Calin Juravle2e768302015-07-28 14:41:11 +00002617 }
Vladimir Markoa1de9182016-02-25 11:37:38 +00002618 return ReferenceTypeInfo(type_handle, is_exact);
Calin Juravle2e768302015-07-28 14:41:11 +00002619}
2620
Calin Juravleacf735c2015-02-12 15:25:22 +00002621std::ostream& operator<<(std::ostream& os, const ReferenceTypeInfo& rhs) {
2622 ScopedObjectAccess soa(Thread::Current());
2623 os << "["
Calin Juravle2e768302015-07-28 14:41:11 +00002624 << " is_valid=" << rhs.IsValid()
David Sehr709b0702016-10-13 09:12:37 -07002625 << " type=" << (!rhs.IsValid() ? "?" : mirror::Class::PrettyClass(rhs.GetTypeHandle().Get()))
Calin Juravleacf735c2015-02-12 15:25:22 +00002626 << " is_exact=" << rhs.IsExact()
2627 << " ]";
2628 return os;
2629}
2630
Mark Mendellc4701932015-04-10 13:18:51 -04002631bool HInstruction::HasAnyEnvironmentUseBefore(HInstruction* other) {
2632 // For now, assume that instructions in different blocks may use the
2633 // environment.
2634 // TODO: Use the control flow to decide if this is true.
2635 if (GetBlock() != other->GetBlock()) {
2636 return true;
2637 }
2638
2639 // We know that we are in the same block. Walk from 'this' to 'other',
2640 // checking to see if there is any instruction with an environment.
2641 HInstruction* current = this;
2642 for (; current != other && current != nullptr; current = current->GetNext()) {
2643 // This is a conservative check, as the instruction result may not be in
2644 // the referenced environment.
2645 if (current->HasEnvironment()) {
2646 return true;
2647 }
2648 }
2649
2650 // We should have been called with 'this' before 'other' in the block.
2651 // Just confirm this.
2652 DCHECK(current != nullptr);
2653 return false;
2654}
2655
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002656void HInvoke::SetIntrinsic(Intrinsics intrinsic,
Aart Bik5d75afe2015-12-14 11:57:01 -08002657 IntrinsicNeedsEnvironmentOrCache needs_env_or_cache,
2658 IntrinsicSideEffects side_effects,
2659 IntrinsicExceptions exceptions) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002660 intrinsic_ = intrinsic;
2661 IntrinsicOptimizations opt(this);
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002662
Aart Bik5d75afe2015-12-14 11:57:01 -08002663 // Adjust method's side effects from intrinsic table.
2664 switch (side_effects) {
2665 case kNoSideEffects: SetSideEffects(SideEffects::None()); break;
2666 case kReadSideEffects: SetSideEffects(SideEffects::AllReads()); break;
2667 case kWriteSideEffects: SetSideEffects(SideEffects::AllWrites()); break;
2668 case kAllSideEffects: SetSideEffects(SideEffects::AllExceptGCDependency()); break;
2669 }
Nicolas Geoffraya3eca2d2016-01-12 16:03:16 +00002670
2671 if (needs_env_or_cache == kNoEnvironmentOrCache) {
2672 opt.SetDoesNotNeedDexCache();
2673 opt.SetDoesNotNeedEnvironment();
2674 } else {
2675 // If we need an environment, that means there will be a call, which can trigger GC.
2676 SetSideEffects(GetSideEffects().Union(SideEffects::CanTriggerGC()));
2677 }
Aart Bik5d75afe2015-12-14 11:57:01 -08002678 // Adjust method's exception status from intrinsic table.
Aart Bik09e8d5f2016-01-22 16:49:55 -08002679 SetCanThrow(exceptions == kCanThrow);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002680}
2681
David Brazdil6de19382016-01-08 17:37:10 +00002682bool HNewInstance::IsStringAlloc() const {
2683 ScopedObjectAccess soa(Thread::Current());
2684 return GetReferenceTypeInfo().IsStringClass();
2685}
2686
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002687bool HInvoke::NeedsEnvironment() const {
2688 if (!IsIntrinsic()) {
2689 return true;
2690 }
2691 IntrinsicOptimizations opt(*this);
2692 return !opt.GetDoesNotNeedEnvironment();
2693}
2694
Nicolas Geoffray5d37c152017-01-12 13:25:19 +00002695const DexFile& HInvokeStaticOrDirect::GetDexFileForPcRelativeDexCache() const {
2696 ArtMethod* caller = GetEnvironment()->GetMethod();
2697 ScopedObjectAccess soa(Thread::Current());
2698 // `caller` is null for a top-level graph representing a method whose declaring
2699 // class was not resolved.
2700 return caller == nullptr ? GetBlock()->GetGraph()->GetDexFile() : *caller->GetDexFile();
2701}
2702
Vladimir Markodc151b22015-10-15 18:02:30 +01002703bool HInvokeStaticOrDirect::NeedsDexCacheOfDeclaringClass() const {
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002704 if (GetMethodLoadKind() != MethodLoadKind::kRuntimeCall) {
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01002705 return false;
2706 }
2707 if (!IsIntrinsic()) {
2708 return true;
2709 }
2710 IntrinsicOptimizations opt(*this);
2711 return !opt.GetDoesNotNeedDexCache();
2712}
2713
Vladimir Markof64242a2015-12-01 14:58:23 +00002714std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::MethodLoadKind rhs) {
2715 switch (rhs) {
2716 case HInvokeStaticOrDirect::MethodLoadKind::kStringInit:
Vladimir Marko65979462017-05-19 17:25:12 +01002717 return os << "StringInit";
Vladimir Markof64242a2015-12-01 14:58:23 +00002718 case HInvokeStaticOrDirect::MethodLoadKind::kRecursive:
Vladimir Marko65979462017-05-19 17:25:12 +01002719 return os << "Recursive";
2720 case HInvokeStaticOrDirect::MethodLoadKind::kBootImageLinkTimePcRelative:
2721 return os << "BootImageLinkTimePcRelative";
Vladimir Markof64242a2015-12-01 14:58:23 +00002722 case HInvokeStaticOrDirect::MethodLoadKind::kDirectAddress:
Vladimir Marko19d7d502017-05-24 13:04:14 +01002723 return os << "DirectAddress";
Vladimir Marko0eb882b2017-05-15 13:39:18 +01002724 case HInvokeStaticOrDirect::MethodLoadKind::kBssEntry:
2725 return os << "BssEntry";
Vladimir Markoe7197bf2017-06-02 17:00:23 +01002726 case HInvokeStaticOrDirect::MethodLoadKind::kRuntimeCall:
2727 return os << "RuntimeCall";
Vladimir Markof64242a2015-12-01 14:58:23 +00002728 default:
2729 LOG(FATAL) << "Unknown MethodLoadKind: " << static_cast<int>(rhs);
2730 UNREACHABLE();
2731 }
2732}
2733
Vladimir Markofbb184a2015-11-13 14:47:00 +00002734std::ostream& operator<<(std::ostream& os, HInvokeStaticOrDirect::ClinitCheckRequirement rhs) {
2735 switch (rhs) {
2736 case HInvokeStaticOrDirect::ClinitCheckRequirement::kExplicit:
2737 return os << "explicit";
2738 case HInvokeStaticOrDirect::ClinitCheckRequirement::kImplicit:
2739 return os << "implicit";
2740 case HInvokeStaticOrDirect::ClinitCheckRequirement::kNone:
2741 return os << "none";
2742 default:
Vladimir Markof64242a2015-12-01 14:58:23 +00002743 LOG(FATAL) << "Unknown ClinitCheckRequirement: " << static_cast<int>(rhs);
2744 UNREACHABLE();
Vladimir Markofbb184a2015-11-13 14:47:00 +00002745 }
2746}
2747
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002748bool HLoadClass::InstructionDataEquals(const HInstruction* other) const {
2749 const HLoadClass* other_load_class = other->AsLoadClass();
2750 // TODO: To allow GVN for HLoadClass from different dex files, we should compare the type
2751 // names rather than type indexes. However, we shall also have to re-think the hash code.
2752 if (type_index_ != other_load_class->type_index_ ||
2753 GetPackedFields() != other_load_class->GetPackedFields()) {
2754 return false;
2755 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002756 switch (GetLoadKind()) {
2757 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002758 case LoadKind::kJitTableAddress: {
2759 ScopedObjectAccess soa(Thread::Current());
2760 return GetClass().Get() == other_load_class->GetClass().Get();
2761 }
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002762 default:
Vladimir Marko48886c22017-01-06 11:45:47 +00002763 DCHECK(HasTypeReference(GetLoadKind()));
Nicolas Geoffray9b1583e2016-12-13 13:43:31 +00002764 return IsSameDexFile(GetDexFile(), other_load_class->GetDexFile());
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002765 }
2766}
2767
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002768void HLoadClass::SetLoadKind(LoadKind load_kind) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002769 SetPackedField<LoadKindField>(load_kind);
2770
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002771 if (load_kind != LoadKind::kRuntimeCall &&
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002772 load_kind != LoadKind::kReferrersClass) {
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002773 RemoveAsUserOfInput(0u);
2774 SetRawInputAt(0u, nullptr);
2775 }
Nicolas Geoffray83c8e272017-01-31 14:36:37 +00002776
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002777 if (!NeedsEnvironment()) {
2778 RemoveEnvironment();
2779 SetSideEffects(SideEffects::None());
2780 }
2781}
2782
2783std::ostream& operator<<(std::ostream& os, HLoadClass::LoadKind rhs) {
2784 switch (rhs) {
2785 case HLoadClass::LoadKind::kReferrersClass:
2786 return os << "ReferrersClass";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002787 case HLoadClass::LoadKind::kBootImageLinkTimePcRelative:
2788 return os << "BootImageLinkTimePcRelative";
2789 case HLoadClass::LoadKind::kBootImageAddress:
2790 return os << "BootImageAddress";
Vladimir Marko6bec91c2017-01-09 15:03:12 +00002791 case HLoadClass::LoadKind::kBssEntry:
2792 return os << "BssEntry";
Nicolas Geoffray22384ae2016-12-12 22:33:36 +00002793 case HLoadClass::LoadKind::kJitTableAddress:
2794 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002795 case HLoadClass::LoadKind::kRuntimeCall:
2796 return os << "RuntimeCall";
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002797 default:
2798 LOG(FATAL) << "Unknown HLoadClass::LoadKind: " << static_cast<int>(rhs);
2799 UNREACHABLE();
2800 }
2801}
2802
Vladimir Marko372f10e2016-05-17 16:30:10 +01002803bool HLoadString::InstructionDataEquals(const HInstruction* other) const {
2804 const HLoadString* other_load_string = other->AsLoadString();
Vladimir Markodbb7f5b2016-03-30 13:23:58 +01002805 // TODO: To allow GVN for HLoadString from different dex files, we should compare the strings
2806 // rather than their indexes. However, we shall also have to re-think the hash code.
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002807 if (string_index_ != other_load_string->string_index_ ||
2808 GetPackedFields() != other_load_string->GetPackedFields()) {
2809 return false;
2810 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002811 switch (GetLoadKind()) {
2812 case LoadKind::kBootImageAddress:
Nicolas Geoffray1ea9efc2017-01-16 22:57:39 +00002813 case LoadKind::kJitTableAddress: {
2814 ScopedObjectAccess soa(Thread::Current());
2815 return GetString().Get() == other_load_string->GetString().Get();
2816 }
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002817 default:
2818 return IsSameDexFile(GetDexFile(), other_load_string->GetDexFile());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002819 }
2820}
2821
Nicolas Geoffrayf0acfe72017-01-09 20:54:52 +00002822void HLoadString::SetLoadKind(LoadKind load_kind) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002823 // Once sharpened, the load kind should not be changed again.
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002824 DCHECK_EQ(GetLoadKind(), LoadKind::kRuntimeCall);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002825 SetPackedField<LoadKindField>(load_kind);
2826
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002827 if (load_kind != LoadKind::kRuntimeCall) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002828 RemoveAsUserOfInput(0u);
2829 SetRawInputAt(0u, nullptr);
2830 }
2831 if (!NeedsEnvironment()) {
2832 RemoveEnvironment();
Vladimir Markoace7a002016-04-05 11:18:49 +01002833 SetSideEffects(SideEffects::None());
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002834 }
2835}
2836
2837std::ostream& operator<<(std::ostream& os, HLoadString::LoadKind rhs) {
2838 switch (rhs) {
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002839 case HLoadString::LoadKind::kBootImageLinkTimePcRelative:
2840 return os << "BootImageLinkTimePcRelative";
2841 case HLoadString::LoadKind::kBootImageAddress:
2842 return os << "BootImageAddress";
Vladimir Markoaad75c62016-10-03 08:46:48 +00002843 case HLoadString::LoadKind::kBssEntry:
2844 return os << "BssEntry";
Mingyao Yangbe44dcf2016-11-30 14:17:32 -08002845 case HLoadString::LoadKind::kJitTableAddress:
2846 return os << "JitTableAddress";
Vladimir Marko847e6ce2017-06-02 13:55:07 +01002847 case HLoadString::LoadKind::kRuntimeCall:
2848 return os << "RuntimeCall";
Vladimir Markocac5a7e2016-02-22 10:39:50 +00002849 default:
2850 LOG(FATAL) << "Unknown HLoadString::LoadKind: " << static_cast<int>(rhs);
2851 UNREACHABLE();
2852 }
2853}
2854
Mark Mendellc4701932015-04-10 13:18:51 -04002855void HInstruction::RemoveEnvironmentUsers() {
Vladimir Marko46817b82016-03-29 12:21:58 +01002856 for (const HUseListNode<HEnvironment*>& use : GetEnvUses()) {
2857 HEnvironment* user = use.GetUser();
2858 user->SetRawEnvAt(use.GetIndex(), nullptr);
Mark Mendellc4701932015-04-10 13:18:51 -04002859 }
Vladimir Marko46817b82016-03-29 12:21:58 +01002860 env_uses_.clear();
Mark Mendellc4701932015-04-10 13:18:51 -04002861}
2862
Roland Levillainc9b21f82016-03-23 16:36:59 +00002863// Returns an instruction with the opposite Boolean value from 'cond'.
Mark Mendellf6529172015-11-17 11:16:56 -05002864HInstruction* HGraph::InsertOppositeCondition(HInstruction* cond, HInstruction* cursor) {
2865 ArenaAllocator* allocator = GetArena();
2866
2867 if (cond->IsCondition() &&
2868 !Primitive::IsFloatingPointType(cond->InputAt(0)->GetType())) {
2869 // Can't reverse floating point conditions. We have to use HBooleanNot in that case.
2870 HInstruction* lhs = cond->InputAt(0);
2871 HInstruction* rhs = cond->InputAt(1);
David Brazdil5c004852015-11-23 09:44:52 +00002872 HInstruction* replacement = nullptr;
Mark Mendellf6529172015-11-17 11:16:56 -05002873 switch (cond->AsCondition()->GetOppositeCondition()) { // get *opposite*
2874 case kCondEQ: replacement = new (allocator) HEqual(lhs, rhs); break;
2875 case kCondNE: replacement = new (allocator) HNotEqual(lhs, rhs); break;
2876 case kCondLT: replacement = new (allocator) HLessThan(lhs, rhs); break;
2877 case kCondLE: replacement = new (allocator) HLessThanOrEqual(lhs, rhs); break;
2878 case kCondGT: replacement = new (allocator) HGreaterThan(lhs, rhs); break;
2879 case kCondGE: replacement = new (allocator) HGreaterThanOrEqual(lhs, rhs); break;
2880 case kCondB: replacement = new (allocator) HBelow(lhs, rhs); break;
2881 case kCondBE: replacement = new (allocator) HBelowOrEqual(lhs, rhs); break;
2882 case kCondA: replacement = new (allocator) HAbove(lhs, rhs); break;
2883 case kCondAE: replacement = new (allocator) HAboveOrEqual(lhs, rhs); break;
David Brazdil5c004852015-11-23 09:44:52 +00002884 default:
2885 LOG(FATAL) << "Unexpected condition";
2886 UNREACHABLE();
Mark Mendellf6529172015-11-17 11:16:56 -05002887 }
2888 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2889 return replacement;
2890 } else if (cond->IsIntConstant()) {
2891 HIntConstant* int_const = cond->AsIntConstant();
Roland Levillain1a653882016-03-18 18:05:57 +00002892 if (int_const->IsFalse()) {
Mark Mendellf6529172015-11-17 11:16:56 -05002893 return GetIntConstant(1);
2894 } else {
Roland Levillain1a653882016-03-18 18:05:57 +00002895 DCHECK(int_const->IsTrue()) << int_const->GetValue();
Mark Mendellf6529172015-11-17 11:16:56 -05002896 return GetIntConstant(0);
2897 }
2898 } else {
2899 HInstruction* replacement = new (allocator) HBooleanNot(cond);
2900 cursor->GetBlock()->InsertInstructionBefore(replacement, cursor);
2901 return replacement;
2902 }
2903}
2904
Roland Levillainc9285912015-12-18 10:38:42 +00002905std::ostream& operator<<(std::ostream& os, const MoveOperands& rhs) {
2906 os << "["
2907 << " source=" << rhs.GetSource()
2908 << " destination=" << rhs.GetDestination()
2909 << " type=" << rhs.GetType()
2910 << " instruction=";
2911 if (rhs.GetInstruction() != nullptr) {
2912 os << rhs.GetInstruction()->DebugName() << ' ' << rhs.GetInstruction()->GetId();
2913 } else {
2914 os << "null";
2915 }
2916 os << " ]";
2917 return os;
2918}
2919
Roland Levillain86503782016-02-11 19:07:30 +00002920std::ostream& operator<<(std::ostream& os, TypeCheckKind rhs) {
2921 switch (rhs) {
2922 case TypeCheckKind::kUnresolvedCheck:
2923 return os << "unresolved_check";
2924 case TypeCheckKind::kExactCheck:
2925 return os << "exact_check";
2926 case TypeCheckKind::kClassHierarchyCheck:
2927 return os << "class_hierarchy_check";
2928 case TypeCheckKind::kAbstractClassCheck:
2929 return os << "abstract_class_check";
2930 case TypeCheckKind::kInterfaceCheck:
2931 return os << "interface_check";
2932 case TypeCheckKind::kArrayObjectCheck:
2933 return os << "array_object_check";
2934 case TypeCheckKind::kArrayCheck:
2935 return os << "array_check";
2936 default:
2937 LOG(FATAL) << "Unknown TypeCheckKind: " << static_cast<int>(rhs);
2938 UNREACHABLE();
2939 }
2940}
2941
Andreas Gampe26de38b2016-07-27 17:53:11 -07002942std::ostream& operator<<(std::ostream& os, const MemBarrierKind& kind) {
2943 switch (kind) {
2944 case MemBarrierKind::kAnyStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002945 return os << "AnyStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002946 case MemBarrierKind::kLoadAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002947 return os << "LoadAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002948 case MemBarrierKind::kStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002949 return os << "StoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002950 case MemBarrierKind::kAnyAny:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002951 return os << "AnyAny";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002952 case MemBarrierKind::kNTStoreStore:
Andreas Gampe75d2df22016-07-27 21:25:41 -07002953 return os << "NTStoreStore";
Andreas Gampe26de38b2016-07-27 17:53:11 -07002954
2955 default:
2956 LOG(FATAL) << "Unknown MemBarrierKind: " << static_cast<int>(kind);
2957 UNREACHABLE();
2958 }
2959}
2960
Nicolas Geoffray818f2102014-02-18 16:43:35 +00002961} // namespace art