blob: 7dff696e32bc0c27ddf6ff4166cd35442a9426fe [file] [log] [blame]
Mingyao Yang8df69d42015-10-22 15:40:58 -07001/*
2 * Copyright (C) 2015 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 */
16
17#include "load_store_elimination.h"
Aart Bik96fd51d2016-11-28 11:22:35 -080018
Vladimir Marko009d1662017-10-10 13:21:15 +010019#include "base/array_ref.h"
20#include "base/scoped_arena_allocator.h"
21#include "base/scoped_arena_containers.h"
Aart Bik96fd51d2016-11-28 11:22:35 -080022#include "escape.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070023#include "load_store_analysis.h"
Mingyao Yang8df69d42015-10-22 15:40:58 -070024#include "side_effects_analysis.h"
25
26#include <iostream>
27
28namespace art {
29
Mingyao Yang8df69d42015-10-22 15:40:58 -070030// An unknown heap value. Loads with such a value in the heap location cannot be eliminated.
Mingyao Yangfb8464a2015-11-02 10:56:59 -080031// A heap location can be set to kUnknownHeapValue when:
32// - initially set a value.
33// - killed due to aliasing, merging, invocation, or loop side effects.
Mingyao Yang8df69d42015-10-22 15:40:58 -070034static HInstruction* const kUnknownHeapValue =
35 reinterpret_cast<HInstruction*>(static_cast<uintptr_t>(-1));
Mingyao Yangfb8464a2015-11-02 10:56:59 -080036
Mingyao Yang8df69d42015-10-22 15:40:58 -070037// Default heap value after an allocation.
Mingyao Yangfb8464a2015-11-02 10:56:59 -080038// A heap location can be set to that value right after an allocation.
Mingyao Yang8df69d42015-10-22 15:40:58 -070039static HInstruction* const kDefaultHeapValue =
40 reinterpret_cast<HInstruction*>(static_cast<uintptr_t>(-2));
41
Mingyao Yangc62b7ec2017-10-25 16:42:15 -070042// Use HGraphDelegateVisitor for which all VisitInvokeXXX() delegate to VisitInvoke().
43class LSEVisitor : public HGraphDelegateVisitor {
Mingyao Yang8df69d42015-10-22 15:40:58 -070044 public:
45 LSEVisitor(HGraph* graph,
46 const HeapLocationCollector& heap_locations_collector,
Igor Murashkin6ef45672017-08-08 13:59:55 -070047 const SideEffectsAnalysis& side_effects,
48 OptimizingCompilerStats* stats)
Mingyao Yangc62b7ec2017-10-25 16:42:15 -070049 : HGraphDelegateVisitor(graph, stats),
Mingyao Yang8df69d42015-10-22 15:40:58 -070050 heap_location_collector_(heap_locations_collector),
51 side_effects_(side_effects),
Vladimir Marko009d1662017-10-10 13:21:15 +010052 allocator_(graph->GetArenaStack()),
Mingyao Yang8df69d42015-10-22 15:40:58 -070053 heap_values_for_(graph->GetBlocks().size(),
Vladimir Marko009d1662017-10-10 13:21:15 +010054 ScopedArenaVector<HInstruction*>(heap_locations_collector.
55 GetNumberOfHeapLocations(),
56 kUnknownHeapValue,
57 allocator_.Adapter(kArenaAllocLSE)),
58 allocator_.Adapter(kArenaAllocLSE)),
59 removed_loads_(allocator_.Adapter(kArenaAllocLSE)),
60 substitute_instructions_for_loads_(allocator_.Adapter(kArenaAllocLSE)),
61 possibly_removed_stores_(allocator_.Adapter(kArenaAllocLSE)),
62 singleton_new_instances_(allocator_.Adapter(kArenaAllocLSE)),
63 singleton_new_arrays_(allocator_.Adapter(kArenaAllocLSE)) {
Mingyao Yang8df69d42015-10-22 15:40:58 -070064 }
65
66 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080067 // Populate the heap_values array for this block.
Mingyao Yang8df69d42015-10-22 15:40:58 -070068 // TODO: try to reuse the heap_values array from one predecessor if possible.
69 if (block->IsLoopHeader()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080070 HandleLoopSideEffects(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -070071 } else {
72 MergePredecessorValues(block);
73 }
74 HGraphVisitor::VisitBasicBlock(block);
75 }
76
77 // Remove recorded instructions that should be eliminated.
78 void RemoveInstructions() {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080079 size_t size = removed_loads_.size();
80 DCHECK_EQ(size, substitute_instructions_for_loads_.size());
Mingyao Yang8df69d42015-10-22 15:40:58 -070081 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080082 HInstruction* load = removed_loads_[i];
83 DCHECK(load != nullptr);
84 DCHECK(load->IsInstanceFieldGet() ||
85 load->IsStaticFieldGet() ||
86 load->IsArrayGet());
87 HInstruction* substitute = substitute_instructions_for_loads_[i];
88 DCHECK(substitute != nullptr);
89 // Keep tracing substitute till one that's not removed.
90 HInstruction* sub_sub = FindSubstitute(substitute);
91 while (sub_sub != substitute) {
92 substitute = sub_sub;
93 sub_sub = FindSubstitute(substitute);
Mingyao Yang8df69d42015-10-22 15:40:58 -070094 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -080095 load->ReplaceWith(substitute);
96 load->GetBlock()->RemoveInstruction(load);
Mingyao Yang8df69d42015-10-22 15:40:58 -070097 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -080098
99 // At this point, stores in possibly_removed_stores_ can be safely removed.
Mingyao Yang86974902017-03-01 14:03:51 -0800100 for (HInstruction* store : possibly_removed_stores_) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800101 DCHECK(store->IsInstanceFieldSet() || store->IsStaticFieldSet() || store->IsArraySet());
102 store->GetBlock()->RemoveInstruction(store);
103 }
104
Igor Murashkind01745e2017-04-05 16:40:31 -0700105 // Eliminate singleton-classified instructions:
106 // * - Constructor fences (they never escape this thread).
107 // * - Allocations (if they are unused).
Mingyao Yang86974902017-03-01 14:03:51 -0800108 for (HInstruction* new_instance : singleton_new_instances_) {
Igor Murashkin6ef45672017-08-08 13:59:55 -0700109 size_t removed = HConstructorFence::RemoveConstructorFences(new_instance);
110 MaybeRecordStat(stats_,
111 MethodCompilationStat::kConstructorFenceRemovedLSE,
112 removed);
Igor Murashkind01745e2017-04-05 16:40:31 -0700113
Mingyao Yang062157f2016-03-02 10:15:36 -0800114 if (!new_instance->HasNonEnvironmentUses()) {
115 new_instance->RemoveEnvironmentUsers();
116 new_instance->GetBlock()->RemoveInstruction(new_instance);
117 }
118 }
Mingyao Yang86974902017-03-01 14:03:51 -0800119 for (HInstruction* new_array : singleton_new_arrays_) {
Igor Murashkin6ef45672017-08-08 13:59:55 -0700120 size_t removed = HConstructorFence::RemoveConstructorFences(new_array);
121 MaybeRecordStat(stats_,
122 MethodCompilationStat::kConstructorFenceRemovedLSE,
123 removed);
Igor Murashkind01745e2017-04-05 16:40:31 -0700124
Mingyao Yang86974902017-03-01 14:03:51 -0800125 if (!new_array->HasNonEnvironmentUses()) {
126 new_array->RemoveEnvironmentUsers();
127 new_array->GetBlock()->RemoveInstruction(new_array);
128 }
129 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700130 }
131
132 private:
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800133 // If heap_values[index] is an instance field store, need to keep the store.
134 // This is necessary if a heap value is killed due to merging, or loop side
135 // effects (which is essentially merging also), since a load later from the
136 // location won't be eliminated.
137 void KeepIfIsStore(HInstruction* heap_value) {
138 if (heap_value == kDefaultHeapValue ||
139 heap_value == kUnknownHeapValue ||
Mingyao Yang86974902017-03-01 14:03:51 -0800140 !(heap_value->IsInstanceFieldSet() || heap_value->IsArraySet())) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800141 return;
142 }
143 auto idx = std::find(possibly_removed_stores_.begin(),
144 possibly_removed_stores_.end(), heap_value);
145 if (idx != possibly_removed_stores_.end()) {
146 // Make sure the store is kept.
147 possibly_removed_stores_.erase(idx);
148 }
149 }
150
151 void HandleLoopSideEffects(HBasicBlock* block) {
152 DCHECK(block->IsLoopHeader());
153 int block_id = block->GetBlockId();
Vladimir Marko009d1662017-10-10 13:21:15 +0100154 ScopedArenaVector<HInstruction*>& heap_values = heap_values_for_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000155
156 // Don't eliminate loads in irreducible loops. This is safe for singletons, because
157 // they are always used by the non-eliminated loop-phi.
158 if (block->GetLoopInformation()->IsIrreducible()) {
159 if (kIsDebugBuild) {
160 for (size_t i = 0; i < heap_values.size(); i++) {
161 DCHECK_EQ(heap_values[i], kUnknownHeapValue);
162 }
163 }
164 return;
165 }
166
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800167 HBasicBlock* pre_header = block->GetLoopInformation()->GetPreHeader();
Vladimir Marko009d1662017-10-10 13:21:15 +0100168 ScopedArenaVector<HInstruction*>& pre_header_heap_values =
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800169 heap_values_for_[pre_header->GetBlockId()];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000170
Mingyao Yang803cbb92015-12-01 12:24:36 -0800171 // Inherit the values from pre-header.
172 for (size_t i = 0; i < heap_values.size(); i++) {
173 heap_values[i] = pre_header_heap_values[i];
174 }
175
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800176 // We do a single pass in reverse post order. For loops, use the side effects as a hint
177 // to see if the heap values should be killed.
178 if (side_effects_.GetLoopEffects(block).DoesAnyWrite()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800179 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800180 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
181 ReferenceInfo* ref_info = location->GetReferenceInfo();
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800182 if (ref_info->IsSingletonAndRemovable() &&
183 !location->IsValueKilledByLoopSideEffects()) {
184 // A removable singleton's field that's not stored into inside a loop is
185 // invariant throughout the loop. Nothing to do.
186 DCHECK(ref_info->IsSingletonAndRemovable());
187 } else {
188 // heap value is killed by loop side effects (stored into directly, or
189 // due to aliasing). Or the heap value may be needed after method return
190 // or deoptimization.
Mingyao Yang803cbb92015-12-01 12:24:36 -0800191 KeepIfIsStore(pre_header_heap_values[i]);
192 heap_values[i] = kUnknownHeapValue;
Mingyao Yang803cbb92015-12-01 12:24:36 -0800193 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800194 }
195 }
196 }
197
Mingyao Yang8df69d42015-10-22 15:40:58 -0700198 void MergePredecessorValues(HBasicBlock* block) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100199 ArrayRef<HBasicBlock* const> predecessors(block->GetPredecessors());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700200 if (predecessors.size() == 0) {
201 return;
202 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700203
Vladimir Marko009d1662017-10-10 13:21:15 +0100204 ScopedArenaVector<HInstruction*>& heap_values = heap_values_for_[block->GetBlockId()];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700205 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700206 HInstruction* merged_value = nullptr;
207 // Whether merged_value is a result that's merged from all predecessors.
208 bool from_all_predecessors = true;
209 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
210 HInstruction* singleton_ref = nullptr;
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800211 if (ref_info->IsSingleton()) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700212 // We do more analysis of liveness when merging heap values for such
213 // cases since stores into such references may potentially be eliminated.
214 singleton_ref = ref_info->GetReference();
215 }
216
217 for (HBasicBlock* predecessor : predecessors) {
218 HInstruction* pred_value = heap_values_for_[predecessor->GetBlockId()][i];
219 if ((singleton_ref != nullptr) &&
220 !singleton_ref->GetBlock()->Dominates(predecessor)) {
221 // singleton_ref is not live in this predecessor. Skip this predecessor since
222 // it does not really have the location.
223 DCHECK_EQ(pred_value, kUnknownHeapValue);
224 from_all_predecessors = false;
225 continue;
226 }
227 if (merged_value == nullptr) {
228 // First seen heap value.
229 merged_value = pred_value;
230 } else if (pred_value != merged_value) {
231 // There are conflicting values.
232 merged_value = kUnknownHeapValue;
233 break;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700234 }
235 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800236
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800237 if (merged_value == kUnknownHeapValue || ref_info->IsSingletonAndNonRemovable()) {
238 // There are conflicting heap values from different predecessors,
239 // or the heap value may be needed after method return or deoptimization.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800240 // Keep the last store in each predecessor since future loads cannot be eliminated.
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700241 for (HBasicBlock* predecessor : predecessors) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100242 ScopedArenaVector<HInstruction*>& pred_values =
243 heap_values_for_[predecessor->GetBlockId()];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800244 KeepIfIsStore(pred_values[i]);
245 }
246 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700247
248 if ((merged_value == nullptr) || !from_all_predecessors) {
249 DCHECK(singleton_ref != nullptr);
250 DCHECK((singleton_ref->GetBlock() == block) ||
251 !singleton_ref->GetBlock()->Dominates(block));
252 // singleton_ref is not defined before block or defined only in some of its
253 // predecessors, so block doesn't really have the location at its entry.
254 heap_values[i] = kUnknownHeapValue;
255 } else {
256 heap_values[i] = merged_value;
257 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700258 }
259 }
260
261 // `instruction` is being removed. Try to see if the null check on it
262 // can be removed. This can happen if the same value is set in two branches
263 // but not in dominators. Such as:
264 // int[] a = foo();
265 // if () {
266 // a[0] = 2;
267 // } else {
268 // a[0] = 2;
269 // }
270 // // a[0] can now be replaced with constant 2, and the null check on it can be removed.
271 void TryRemovingNullCheck(HInstruction* instruction) {
272 HInstruction* prev = instruction->GetPrevious();
273 if ((prev != nullptr) && prev->IsNullCheck() && (prev == instruction->InputAt(0))) {
274 // Previous instruction is a null check for this instruction. Remove the null check.
275 prev->ReplaceWith(prev->InputAt(0));
276 prev->GetBlock()->RemoveInstruction(prev);
277 }
278 }
279
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100280 HInstruction* GetDefaultValue(DataType::Type type) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700281 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100282 case DataType::Type::kReference:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700283 return GetGraph()->GetNullConstant();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100284 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100285 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100286 case DataType::Type::kInt8:
287 case DataType::Type::kUint16:
288 case DataType::Type::kInt16:
289 case DataType::Type::kInt32:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700290 return GetGraph()->GetIntConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100291 case DataType::Type::kInt64:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700292 return GetGraph()->GetLongConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100293 case DataType::Type::kFloat32:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700294 return GetGraph()->GetFloatConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100295 case DataType::Type::kFloat64:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700296 return GetGraph()->GetDoubleConstant(0);
297 default:
298 UNREACHABLE();
299 }
300 }
301
302 void VisitGetLocation(HInstruction* instruction,
303 HInstruction* ref,
304 size_t offset,
305 HInstruction* index,
306 int16_t declaring_class_def_index) {
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100307 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700308 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
309 size_t idx = heap_location_collector_.FindHeapLocationIndex(
310 ref_info, offset, index, declaring_class_def_index);
311 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
Vladimir Marko009d1662017-10-10 13:21:15 +0100312 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700313 heap_values_for_[instruction->GetBlock()->GetBlockId()];
314 HInstruction* heap_value = heap_values[idx];
315 if (heap_value == kDefaultHeapValue) {
316 HInstruction* constant = GetDefaultValue(instruction->GetType());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800317 removed_loads_.push_back(instruction);
318 substitute_instructions_for_loads_.push_back(constant);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700319 heap_values[idx] = constant;
320 return;
321 }
Mingyao Yang86974902017-03-01 14:03:51 -0800322 if (heap_value != kUnknownHeapValue) {
323 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
324 HInstruction* store = heap_value;
325 // This load must be from a singleton since it's from the same
326 // field/element that a "removed" store puts the value. That store
327 // must be to a singleton's field/element.
328 DCHECK(ref_info->IsSingleton());
329 // Get the real heap value of the store.
330 heap_value = heap_value->IsInstanceFieldSet() ? store->InputAt(1) : store->InputAt(2);
331 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800332 }
David Brazdil15693bf2015-12-16 10:30:45 +0000333 if (heap_value == kUnknownHeapValue) {
334 // Load isn't eliminated. Put the load as the value into the HeapLocation.
335 // This acts like GVN but with better aliasing analysis.
336 heap_values[idx] = instruction;
337 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100338 if (DataType::Kind(heap_value->GetType()) != DataType::Kind(instruction->GetType())) {
Nicolas Geoffray03971632016-03-17 10:44:24 +0000339 // The only situation where the same heap location has different type is when
Nicolas Geoffray65fef302016-05-04 14:00:12 +0100340 // we do an array get on an instruction that originates from the null constant
341 // (the null could be behind a field access, an array access, a null check or
342 // a bound type).
343 // In order to stay properly typed on primitive types, we do not eliminate
344 // the array gets.
Nicolas Geoffray03971632016-03-17 10:44:24 +0000345 if (kIsDebugBuild) {
346 DCHECK(heap_value->IsArrayGet()) << heap_value->DebugName();
347 DCHECK(instruction->IsArrayGet()) << instruction->DebugName();
Nicolas Geoffray03971632016-03-17 10:44:24 +0000348 }
349 return;
350 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800351 removed_loads_.push_back(instruction);
352 substitute_instructions_for_loads_.push_back(heap_value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700353 TryRemovingNullCheck(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700354 }
355 }
356
357 bool Equal(HInstruction* heap_value, HInstruction* value) {
358 if (heap_value == value) {
359 return true;
360 }
361 if (heap_value == kDefaultHeapValue && GetDefaultValue(value->GetType()) == value) {
362 return true;
363 }
364 return false;
365 }
366
367 void VisitSetLocation(HInstruction* instruction,
368 HInstruction* ref,
369 size_t offset,
370 HInstruction* index,
371 int16_t declaring_class_def_index,
372 HInstruction* value) {
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100373 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700374 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
375 size_t idx = heap_location_collector_.FindHeapLocationIndex(
376 ref_info, offset, index, declaring_class_def_index);
377 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
Vladimir Marko009d1662017-10-10 13:21:15 +0100378 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700379 heap_values_for_[instruction->GetBlock()->GetBlockId()];
380 HInstruction* heap_value = heap_values[idx];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800381 bool same_value = false;
382 bool possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700383 if (Equal(heap_value, value)) {
384 // Store into the heap location with the same value.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800385 same_value = true;
Mingyao Yang86974902017-03-01 14:03:51 -0800386 } else if (index != nullptr && ref_info->HasIndexAliasing()) {
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800387 // For array element, don't eliminate stores if the index can be aliased.
388 } else if (ref_info->IsSingleton()) {
389 // Store into a field of a singleton. The value cannot be killed due to
390 // aliasing/invocation. It can be redundant since future loads can
391 // directly get the value set by this instruction. The value can still be killed due to
392 // merging or loop side effects. Stores whose values are killed due to merging/loop side
393 // effects later will be removed from possibly_removed_stores_ when that is detected.
394 // Stores whose values may be needed after method return or deoptimization
395 // are also removed from possibly_removed_stores_ when that is detected.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800396 possibly_redundant = true;
397 HNewInstance* new_instance = ref_info->GetReference()->AsNewInstance();
Mingyao Yang86974902017-03-01 14:03:51 -0800398 if (new_instance != nullptr && new_instance->IsFinalizable()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800399 // Finalizable objects escape globally. Need to keep the store.
400 possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700401 } else {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800402 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
403 if (loop_info != nullptr) {
404 // instruction is a store in the loop so the loop must does write.
405 DCHECK(side_effects_.GetLoopEffects(loop_info->GetHeader()).DoesAnyWrite());
406
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800407 if (loop_info->IsDefinedOutOfTheLoop(original_ref)) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800408 DCHECK(original_ref->GetBlock()->Dominates(loop_info->GetPreHeader()));
409 // Keep the store since its value may be needed at the loop header.
410 possibly_redundant = false;
411 } else {
412 // The singleton is created inside the loop. Value stored to it isn't needed at
413 // the loop header. This is true for outer loops also.
414 }
415 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700416 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700417 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800418 if (same_value || possibly_redundant) {
419 possibly_removed_stores_.push_back(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700420 }
Mingyao Yange9d6e602015-10-23 17:08:42 -0700421
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800422 if (!same_value) {
423 if (possibly_redundant) {
Mingyao Yang86974902017-03-01 14:03:51 -0800424 DCHECK(instruction->IsInstanceFieldSet() || instruction->IsArraySet());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800425 // Put the store as the heap value. If the value is loaded from heap
426 // by a load later, this store isn't really redundant.
427 heap_values[idx] = instruction;
428 } else {
429 heap_values[idx] = value;
430 }
431 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700432 // This store may kill values in other heap locations due to aliasing.
433 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800434 if (i == idx) {
435 continue;
436 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700437 if (heap_values[i] == value) {
438 // Same value should be kept even if aliasing happens.
439 continue;
440 }
441 if (heap_values[i] == kUnknownHeapValue) {
442 // Value is already unknown, no need for aliasing check.
443 continue;
444 }
445 if (heap_location_collector_.MayAlias(i, idx)) {
446 // Kill heap locations that may alias.
447 heap_values[i] = kUnknownHeapValue;
448 }
449 }
450 }
451
452 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
453 HInstruction* obj = instruction->InputAt(0);
454 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
455 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
456 VisitGetLocation(instruction, obj, offset, nullptr, declaring_class_def_index);
457 }
458
459 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
460 HInstruction* obj = instruction->InputAt(0);
461 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
462 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
463 HInstruction* value = instruction->InputAt(1);
464 VisitSetLocation(instruction, obj, offset, nullptr, declaring_class_def_index, value);
465 }
466
467 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
468 HInstruction* cls = instruction->InputAt(0);
469 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
470 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
471 VisitGetLocation(instruction, cls, offset, nullptr, declaring_class_def_index);
472 }
473
474 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
475 HInstruction* cls = instruction->InputAt(0);
476 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
477 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
478 HInstruction* value = instruction->InputAt(1);
479 VisitSetLocation(instruction, cls, offset, nullptr, declaring_class_def_index, value);
480 }
481
482 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
483 HInstruction* array = instruction->InputAt(0);
484 HInstruction* index = instruction->InputAt(1);
485 VisitGetLocation(instruction,
486 array,
487 HeapLocation::kInvalidFieldOffset,
488 index,
489 HeapLocation::kDeclaringClassDefIndexForArrays);
490 }
491
492 void VisitArraySet(HArraySet* instruction) OVERRIDE {
493 HInstruction* array = instruction->InputAt(0);
494 HInstruction* index = instruction->InputAt(1);
495 HInstruction* value = instruction->InputAt(2);
496 VisitSetLocation(instruction,
497 array,
498 HeapLocation::kInvalidFieldOffset,
499 index,
500 HeapLocation::kDeclaringClassDefIndexForArrays,
501 value);
502 }
503
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800504 void VisitDeoptimize(HDeoptimize* instruction) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100505 const ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800506 heap_values_for_[instruction->GetBlock()->GetBlockId()];
507 for (HInstruction* heap_value : heap_values) {
508 // Filter out fake instructions before checking instruction kind below.
509 if (heap_value == kUnknownHeapValue || heap_value == kDefaultHeapValue) {
510 continue;
511 }
512 // A store is kept as the heap value for possibly removed stores.
513 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
514 // Check whether the reference for a store is used by an environment local of
515 // HDeoptimize.
516 HInstruction* reference = heap_value->InputAt(0);
517 DCHECK(heap_location_collector_.FindReferenceInfoOf(reference)->IsSingleton());
518 for (const HUseListNode<HEnvironment*>& use : reference->GetEnvUses()) {
519 HEnvironment* user = use.GetUser();
520 if (user->GetHolder() == instruction) {
521 // The singleton for the store is visible at this deoptimization
522 // point. Need to keep the store so that the heap value is
523 // seen by the interpreter.
524 KeepIfIsStore(heap_value);
525 }
526 }
527 }
528 }
529 }
530
Mingyao Yang8df69d42015-10-22 15:40:58 -0700531 void HandleInvoke(HInstruction* invoke) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100532 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700533 heap_values_for_[invoke->GetBlock()->GetBlockId()];
534 for (size_t i = 0; i < heap_values.size(); i++) {
535 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
536 if (ref_info->IsSingleton()) {
537 // Singleton references cannot be seen by the callee.
538 } else {
539 heap_values[i] = kUnknownHeapValue;
540 }
541 }
542 }
543
Mingyao Yangc62b7ec2017-10-25 16:42:15 -0700544 void VisitInvoke(HInvoke* invoke) OVERRIDE {
Orion Hodsonac141392017-01-13 11:53:47 +0000545 HandleInvoke(invoke);
546 }
547
Mingyao Yang8df69d42015-10-22 15:40:58 -0700548 void VisitClinitCheck(HClinitCheck* clinit) OVERRIDE {
549 HandleInvoke(clinit);
550 }
551
552 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* instruction) OVERRIDE {
553 // Conservatively treat it as an invocation.
554 HandleInvoke(instruction);
555 }
556
557 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* instruction) OVERRIDE {
558 // Conservatively treat it as an invocation.
559 HandleInvoke(instruction);
560 }
561
562 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* instruction) OVERRIDE {
563 // Conservatively treat it as an invocation.
564 HandleInvoke(instruction);
565 }
566
567 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* instruction) OVERRIDE {
568 // Conservatively treat it as an invocation.
569 HandleInvoke(instruction);
570 }
571
572 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
573 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_instance);
574 if (ref_info == nullptr) {
575 // new_instance isn't used for field accesses. No need to process it.
576 return;
577 }
Aart Bik71bf7b42016-11-16 10:17:46 -0800578 if (ref_info->IsSingletonAndRemovable() &&
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800579 !new_instance->IsFinalizable() &&
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000580 !new_instance->NeedsChecks()) {
Mingyao Yang062157f2016-03-02 10:15:36 -0800581 singleton_new_instances_.push_back(new_instance);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700582 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100583 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700584 heap_values_for_[new_instance->GetBlock()->GetBlockId()];
585 for (size_t i = 0; i < heap_values.size(); i++) {
586 HInstruction* ref =
587 heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo()->GetReference();
588 size_t offset = heap_location_collector_.GetHeapLocation(i)->GetOffset();
589 if (ref == new_instance && offset >= mirror::kObjectHeaderSize) {
590 // Instance fields except the header fields are set to default heap values.
591 heap_values[i] = kDefaultHeapValue;
592 }
593 }
594 }
595
Mingyao Yang86974902017-03-01 14:03:51 -0800596 void VisitNewArray(HNewArray* new_array) OVERRIDE {
597 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_array);
598 if (ref_info == nullptr) {
599 // new_array isn't used for array accesses. No need to process it.
600 return;
601 }
602 if (ref_info->IsSingletonAndRemovable()) {
603 singleton_new_arrays_.push_back(new_array);
604 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100605 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang86974902017-03-01 14:03:51 -0800606 heap_values_for_[new_array->GetBlock()->GetBlockId()];
607 for (size_t i = 0; i < heap_values.size(); i++) {
608 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
609 HInstruction* ref = location->GetReferenceInfo()->GetReference();
610 if (ref == new_array && location->GetIndex() != nullptr) {
611 // Array elements are set to default heap values.
612 heap_values[i] = kDefaultHeapValue;
613 }
614 }
615 }
616
Mingyao Yang8df69d42015-10-22 15:40:58 -0700617 // Find an instruction's substitute if it should be removed.
618 // Return the same instruction if it should not be removed.
619 HInstruction* FindSubstitute(HInstruction* instruction) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800620 size_t size = removed_loads_.size();
Mingyao Yang8df69d42015-10-22 15:40:58 -0700621 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800622 if (removed_loads_[i] == instruction) {
623 return substitute_instructions_for_loads_[i];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700624 }
625 }
626 return instruction;
627 }
628
629 const HeapLocationCollector& heap_location_collector_;
630 const SideEffectsAnalysis& side_effects_;
631
Vladimir Marko009d1662017-10-10 13:21:15 +0100632 // Use local allocator for allocating memory.
633 ScopedArenaAllocator allocator_;
634
Mingyao Yang8df69d42015-10-22 15:40:58 -0700635 // One array of heap values for each block.
Vladimir Marko009d1662017-10-10 13:21:15 +0100636 ScopedArenaVector<ScopedArenaVector<HInstruction*>> heap_values_for_;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700637
638 // We record the instructions that should be eliminated but may be
639 // used by heap locations. They'll be removed in the end.
Vladimir Marko009d1662017-10-10 13:21:15 +0100640 ScopedArenaVector<HInstruction*> removed_loads_;
641 ScopedArenaVector<HInstruction*> substitute_instructions_for_loads_;
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800642
643 // Stores in this list may be removed from the list later when it's
644 // found that the store cannot be eliminated.
Vladimir Marko009d1662017-10-10 13:21:15 +0100645 ScopedArenaVector<HInstruction*> possibly_removed_stores_;
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800646
Vladimir Marko009d1662017-10-10 13:21:15 +0100647 ScopedArenaVector<HInstruction*> singleton_new_instances_;
648 ScopedArenaVector<HInstruction*> singleton_new_arrays_;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700649
650 DISALLOW_COPY_AND_ASSIGN(LSEVisitor);
651};
652
653void LoadStoreElimination::Run() {
David Brazdil8993caf2015-12-07 10:04:40 +0000654 if (graph_->IsDebuggable() || graph_->HasTryCatch()) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700655 // Debugger may set heap values or trigger deoptimization of callers.
David Brazdil8993caf2015-12-07 10:04:40 +0000656 // Try/catch support not implemented yet.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700657 // Skip this optimization.
658 return;
659 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100660 const HeapLocationCollector& heap_location_collector = lsa_.GetHeapLocationCollector();
661 if (heap_location_collector.GetNumberOfHeapLocations() == 0) {
662 // No HeapLocation information from LSA, skip this optimization.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700663 return;
664 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100665
Aart Bikd30f2052017-09-12 13:07:00 -0700666 // TODO: analyze VecLoad/VecStore better.
667 if (graph_->HasSIMD()) {
668 return;
669 }
670
Igor Murashkin6ef45672017-08-08 13:59:55 -0700671 LSEVisitor lse_visitor(graph_, heap_location_collector, side_effects_, stats_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100672 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
673 lse_visitor.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700674 }
675 lse_visitor.RemoveInstructions();
676}
677
678} // namespace art