blob: af5585ec9260f7ee64d5c1ad29687230fd4f0202 [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
42class LSEVisitor : public HGraphVisitor {
43 public:
44 LSEVisitor(HGraph* graph,
45 const HeapLocationCollector& heap_locations_collector,
Igor Murashkin6ef45672017-08-08 13:59:55 -070046 const SideEffectsAnalysis& side_effects,
47 OptimizingCompilerStats* stats)
48 : HGraphVisitor(graph, stats),
Mingyao Yang8df69d42015-10-22 15:40:58 -070049 heap_location_collector_(heap_locations_collector),
50 side_effects_(side_effects),
Vladimir Marko009d1662017-10-10 13:21:15 +010051 allocator_(graph->GetArenaStack()),
Mingyao Yang8df69d42015-10-22 15:40:58 -070052 heap_values_for_(graph->GetBlocks().size(),
Vladimir Marko009d1662017-10-10 13:21:15 +010053 ScopedArenaVector<HInstruction*>(heap_locations_collector.
54 GetNumberOfHeapLocations(),
55 kUnknownHeapValue,
56 allocator_.Adapter(kArenaAllocLSE)),
57 allocator_.Adapter(kArenaAllocLSE)),
58 removed_loads_(allocator_.Adapter(kArenaAllocLSE)),
59 substitute_instructions_for_loads_(allocator_.Adapter(kArenaAllocLSE)),
60 possibly_removed_stores_(allocator_.Adapter(kArenaAllocLSE)),
61 singleton_new_instances_(allocator_.Adapter(kArenaAllocLSE)),
62 singleton_new_arrays_(allocator_.Adapter(kArenaAllocLSE)) {
Mingyao Yang8df69d42015-10-22 15:40:58 -070063 }
64
65 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080066 // Populate the heap_values array for this block.
Mingyao Yang8df69d42015-10-22 15:40:58 -070067 // TODO: try to reuse the heap_values array from one predecessor if possible.
68 if (block->IsLoopHeader()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080069 HandleLoopSideEffects(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -070070 } else {
71 MergePredecessorValues(block);
72 }
73 HGraphVisitor::VisitBasicBlock(block);
74 }
75
76 // Remove recorded instructions that should be eliminated.
77 void RemoveInstructions() {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080078 size_t size = removed_loads_.size();
79 DCHECK_EQ(size, substitute_instructions_for_loads_.size());
Mingyao Yang8df69d42015-10-22 15:40:58 -070080 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080081 HInstruction* load = removed_loads_[i];
82 DCHECK(load != nullptr);
83 DCHECK(load->IsInstanceFieldGet() ||
84 load->IsStaticFieldGet() ||
85 load->IsArrayGet());
86 HInstruction* substitute = substitute_instructions_for_loads_[i];
87 DCHECK(substitute != nullptr);
88 // Keep tracing substitute till one that's not removed.
89 HInstruction* sub_sub = FindSubstitute(substitute);
90 while (sub_sub != substitute) {
91 substitute = sub_sub;
92 sub_sub = FindSubstitute(substitute);
Mingyao Yang8df69d42015-10-22 15:40:58 -070093 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -080094 load->ReplaceWith(substitute);
95 load->GetBlock()->RemoveInstruction(load);
Mingyao Yang8df69d42015-10-22 15:40:58 -070096 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -080097
98 // At this point, stores in possibly_removed_stores_ can be safely removed.
Mingyao Yang86974902017-03-01 14:03:51 -080099 for (HInstruction* store : possibly_removed_stores_) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800100 DCHECK(store->IsInstanceFieldSet() || store->IsStaticFieldSet() || store->IsArraySet());
101 store->GetBlock()->RemoveInstruction(store);
102 }
103
Igor Murashkind01745e2017-04-05 16:40:31 -0700104 // Eliminate singleton-classified instructions:
105 // * - Constructor fences (they never escape this thread).
106 // * - Allocations (if they are unused).
Mingyao Yang86974902017-03-01 14:03:51 -0800107 for (HInstruction* new_instance : singleton_new_instances_) {
Igor Murashkin6ef45672017-08-08 13:59:55 -0700108 size_t removed = HConstructorFence::RemoveConstructorFences(new_instance);
109 MaybeRecordStat(stats_,
110 MethodCompilationStat::kConstructorFenceRemovedLSE,
111 removed);
Igor Murashkind01745e2017-04-05 16:40:31 -0700112
Mingyao Yang062157f2016-03-02 10:15:36 -0800113 if (!new_instance->HasNonEnvironmentUses()) {
114 new_instance->RemoveEnvironmentUsers();
115 new_instance->GetBlock()->RemoveInstruction(new_instance);
116 }
117 }
Mingyao Yang86974902017-03-01 14:03:51 -0800118 for (HInstruction* new_array : singleton_new_arrays_) {
Igor Murashkin6ef45672017-08-08 13:59:55 -0700119 size_t removed = HConstructorFence::RemoveConstructorFences(new_array);
120 MaybeRecordStat(stats_,
121 MethodCompilationStat::kConstructorFenceRemovedLSE,
122 removed);
Igor Murashkind01745e2017-04-05 16:40:31 -0700123
Mingyao Yang86974902017-03-01 14:03:51 -0800124 if (!new_array->HasNonEnvironmentUses()) {
125 new_array->RemoveEnvironmentUsers();
126 new_array->GetBlock()->RemoveInstruction(new_array);
127 }
128 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700129 }
130
131 private:
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800132 // If heap_values[index] is an instance field store, need to keep the store.
133 // This is necessary if a heap value is killed due to merging, or loop side
134 // effects (which is essentially merging also), since a load later from the
135 // location won't be eliminated.
136 void KeepIfIsStore(HInstruction* heap_value) {
137 if (heap_value == kDefaultHeapValue ||
138 heap_value == kUnknownHeapValue ||
Mingyao Yang86974902017-03-01 14:03:51 -0800139 !(heap_value->IsInstanceFieldSet() || heap_value->IsArraySet())) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800140 return;
141 }
142 auto idx = std::find(possibly_removed_stores_.begin(),
143 possibly_removed_stores_.end(), heap_value);
144 if (idx != possibly_removed_stores_.end()) {
145 // Make sure the store is kept.
146 possibly_removed_stores_.erase(idx);
147 }
148 }
149
150 void HandleLoopSideEffects(HBasicBlock* block) {
151 DCHECK(block->IsLoopHeader());
152 int block_id = block->GetBlockId();
Vladimir Marko009d1662017-10-10 13:21:15 +0100153 ScopedArenaVector<HInstruction*>& heap_values = heap_values_for_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000154
155 // Don't eliminate loads in irreducible loops. This is safe for singletons, because
156 // they are always used by the non-eliminated loop-phi.
157 if (block->GetLoopInformation()->IsIrreducible()) {
158 if (kIsDebugBuild) {
159 for (size_t i = 0; i < heap_values.size(); i++) {
160 DCHECK_EQ(heap_values[i], kUnknownHeapValue);
161 }
162 }
163 return;
164 }
165
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800166 HBasicBlock* pre_header = block->GetLoopInformation()->GetPreHeader();
Vladimir Marko009d1662017-10-10 13:21:15 +0100167 ScopedArenaVector<HInstruction*>& pre_header_heap_values =
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800168 heap_values_for_[pre_header->GetBlockId()];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000169
Mingyao Yang803cbb92015-12-01 12:24:36 -0800170 // Inherit the values from pre-header.
171 for (size_t i = 0; i < heap_values.size(); i++) {
172 heap_values[i] = pre_header_heap_values[i];
173 }
174
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800175 // We do a single pass in reverse post order. For loops, use the side effects as a hint
176 // to see if the heap values should be killed.
177 if (side_effects_.GetLoopEffects(block).DoesAnyWrite()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800178 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800179 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
180 ReferenceInfo* ref_info = location->GetReferenceInfo();
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800181 if (ref_info->IsSingletonAndRemovable() &&
182 !location->IsValueKilledByLoopSideEffects()) {
183 // A removable singleton's field that's not stored into inside a loop is
184 // invariant throughout the loop. Nothing to do.
185 DCHECK(ref_info->IsSingletonAndRemovable());
186 } else {
187 // heap value is killed by loop side effects (stored into directly, or
188 // due to aliasing). Or the heap value may be needed after method return
189 // or deoptimization.
Mingyao Yang803cbb92015-12-01 12:24:36 -0800190 KeepIfIsStore(pre_header_heap_values[i]);
191 heap_values[i] = kUnknownHeapValue;
Mingyao Yang803cbb92015-12-01 12:24:36 -0800192 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800193 }
194 }
195 }
196
Mingyao Yang8df69d42015-10-22 15:40:58 -0700197 void MergePredecessorValues(HBasicBlock* block) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100198 ArrayRef<HBasicBlock* const> predecessors(block->GetPredecessors());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700199 if (predecessors.size() == 0) {
200 return;
201 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700202
Vladimir Marko009d1662017-10-10 13:21:15 +0100203 ScopedArenaVector<HInstruction*>& heap_values = heap_values_for_[block->GetBlockId()];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700204 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700205 HInstruction* merged_value = nullptr;
206 // Whether merged_value is a result that's merged from all predecessors.
207 bool from_all_predecessors = true;
208 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
209 HInstruction* singleton_ref = nullptr;
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800210 if (ref_info->IsSingleton()) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700211 // We do more analysis of liveness when merging heap values for such
212 // cases since stores into such references may potentially be eliminated.
213 singleton_ref = ref_info->GetReference();
214 }
215
216 for (HBasicBlock* predecessor : predecessors) {
217 HInstruction* pred_value = heap_values_for_[predecessor->GetBlockId()][i];
218 if ((singleton_ref != nullptr) &&
219 !singleton_ref->GetBlock()->Dominates(predecessor)) {
220 // singleton_ref is not live in this predecessor. Skip this predecessor since
221 // it does not really have the location.
222 DCHECK_EQ(pred_value, kUnknownHeapValue);
223 from_all_predecessors = false;
224 continue;
225 }
226 if (merged_value == nullptr) {
227 // First seen heap value.
228 merged_value = pred_value;
229 } else if (pred_value != merged_value) {
230 // There are conflicting values.
231 merged_value = kUnknownHeapValue;
232 break;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700233 }
234 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800235
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800236 if (merged_value == kUnknownHeapValue || ref_info->IsSingletonAndNonRemovable()) {
237 // There are conflicting heap values from different predecessors,
238 // or the heap value may be needed after method return or deoptimization.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800239 // Keep the last store in each predecessor since future loads cannot be eliminated.
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700240 for (HBasicBlock* predecessor : predecessors) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100241 ScopedArenaVector<HInstruction*>& pred_values =
242 heap_values_for_[predecessor->GetBlockId()];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800243 KeepIfIsStore(pred_values[i]);
244 }
245 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700246
247 if ((merged_value == nullptr) || !from_all_predecessors) {
248 DCHECK(singleton_ref != nullptr);
249 DCHECK((singleton_ref->GetBlock() == block) ||
250 !singleton_ref->GetBlock()->Dominates(block));
251 // singleton_ref is not defined before block or defined only in some of its
252 // predecessors, so block doesn't really have the location at its entry.
253 heap_values[i] = kUnknownHeapValue;
254 } else {
255 heap_values[i] = merged_value;
256 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700257 }
258 }
259
260 // `instruction` is being removed. Try to see if the null check on it
261 // can be removed. This can happen if the same value is set in two branches
262 // but not in dominators. Such as:
263 // int[] a = foo();
264 // if () {
265 // a[0] = 2;
266 // } else {
267 // a[0] = 2;
268 // }
269 // // a[0] can now be replaced with constant 2, and the null check on it can be removed.
270 void TryRemovingNullCheck(HInstruction* instruction) {
271 HInstruction* prev = instruction->GetPrevious();
272 if ((prev != nullptr) && prev->IsNullCheck() && (prev == instruction->InputAt(0))) {
273 // Previous instruction is a null check for this instruction. Remove the null check.
274 prev->ReplaceWith(prev->InputAt(0));
275 prev->GetBlock()->RemoveInstruction(prev);
276 }
277 }
278
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100279 HInstruction* GetDefaultValue(DataType::Type type) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700280 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100281 case DataType::Type::kReference:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700282 return GetGraph()->GetNullConstant();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100283 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100284 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100285 case DataType::Type::kInt8:
286 case DataType::Type::kUint16:
287 case DataType::Type::kInt16:
288 case DataType::Type::kInt32:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700289 return GetGraph()->GetIntConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100290 case DataType::Type::kInt64:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700291 return GetGraph()->GetLongConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100292 case DataType::Type::kFloat32:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700293 return GetGraph()->GetFloatConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100294 case DataType::Type::kFloat64:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700295 return GetGraph()->GetDoubleConstant(0);
296 default:
297 UNREACHABLE();
298 }
299 }
300
301 void VisitGetLocation(HInstruction* instruction,
302 HInstruction* ref,
303 size_t offset,
304 HInstruction* index,
305 int16_t declaring_class_def_index) {
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100306 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700307 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
308 size_t idx = heap_location_collector_.FindHeapLocationIndex(
309 ref_info, offset, index, declaring_class_def_index);
310 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
Vladimir Marko009d1662017-10-10 13:21:15 +0100311 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700312 heap_values_for_[instruction->GetBlock()->GetBlockId()];
313 HInstruction* heap_value = heap_values[idx];
314 if (heap_value == kDefaultHeapValue) {
315 HInstruction* constant = GetDefaultValue(instruction->GetType());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800316 removed_loads_.push_back(instruction);
317 substitute_instructions_for_loads_.push_back(constant);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700318 heap_values[idx] = constant;
319 return;
320 }
Mingyao Yang86974902017-03-01 14:03:51 -0800321 if (heap_value != kUnknownHeapValue) {
322 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
323 HInstruction* store = heap_value;
324 // This load must be from a singleton since it's from the same
325 // field/element that a "removed" store puts the value. That store
326 // must be to a singleton's field/element.
327 DCHECK(ref_info->IsSingleton());
328 // Get the real heap value of the store.
329 heap_value = heap_value->IsInstanceFieldSet() ? store->InputAt(1) : store->InputAt(2);
330 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800331 }
David Brazdil15693bf2015-12-16 10:30:45 +0000332 if (heap_value == kUnknownHeapValue) {
333 // Load isn't eliminated. Put the load as the value into the HeapLocation.
334 // This acts like GVN but with better aliasing analysis.
335 heap_values[idx] = instruction;
336 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100337 if (DataType::Kind(heap_value->GetType()) != DataType::Kind(instruction->GetType())) {
Nicolas Geoffray03971632016-03-17 10:44:24 +0000338 // The only situation where the same heap location has different type is when
Nicolas Geoffray65fef302016-05-04 14:00:12 +0100339 // we do an array get on an instruction that originates from the null constant
340 // (the null could be behind a field access, an array access, a null check or
341 // a bound type).
342 // In order to stay properly typed on primitive types, we do not eliminate
343 // the array gets.
Nicolas Geoffray03971632016-03-17 10:44:24 +0000344 if (kIsDebugBuild) {
345 DCHECK(heap_value->IsArrayGet()) << heap_value->DebugName();
346 DCHECK(instruction->IsArrayGet()) << instruction->DebugName();
Nicolas Geoffray03971632016-03-17 10:44:24 +0000347 }
348 return;
349 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800350 removed_loads_.push_back(instruction);
351 substitute_instructions_for_loads_.push_back(heap_value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700352 TryRemovingNullCheck(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700353 }
354 }
355
356 bool Equal(HInstruction* heap_value, HInstruction* value) {
357 if (heap_value == value) {
358 return true;
359 }
360 if (heap_value == kDefaultHeapValue && GetDefaultValue(value->GetType()) == value) {
361 return true;
362 }
363 return false;
364 }
365
366 void VisitSetLocation(HInstruction* instruction,
367 HInstruction* ref,
368 size_t offset,
369 HInstruction* index,
370 int16_t declaring_class_def_index,
371 HInstruction* value) {
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100372 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700373 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
374 size_t idx = heap_location_collector_.FindHeapLocationIndex(
375 ref_info, offset, index, declaring_class_def_index);
376 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
Vladimir Marko009d1662017-10-10 13:21:15 +0100377 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700378 heap_values_for_[instruction->GetBlock()->GetBlockId()];
379 HInstruction* heap_value = heap_values[idx];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800380 bool same_value = false;
381 bool possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700382 if (Equal(heap_value, value)) {
383 // Store into the heap location with the same value.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800384 same_value = true;
Mingyao Yang86974902017-03-01 14:03:51 -0800385 } else if (index != nullptr && ref_info->HasIndexAliasing()) {
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800386 // For array element, don't eliminate stores if the index can be aliased.
387 } else if (ref_info->IsSingleton()) {
388 // Store into a field of a singleton. The value cannot be killed due to
389 // aliasing/invocation. It can be redundant since future loads can
390 // directly get the value set by this instruction. The value can still be killed due to
391 // merging or loop side effects. Stores whose values are killed due to merging/loop side
392 // effects later will be removed from possibly_removed_stores_ when that is detected.
393 // Stores whose values may be needed after method return or deoptimization
394 // are also removed from possibly_removed_stores_ when that is detected.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800395 possibly_redundant = true;
396 HNewInstance* new_instance = ref_info->GetReference()->AsNewInstance();
Mingyao Yang86974902017-03-01 14:03:51 -0800397 if (new_instance != nullptr && new_instance->IsFinalizable()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800398 // Finalizable objects escape globally. Need to keep the store.
399 possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700400 } else {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800401 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
402 if (loop_info != nullptr) {
403 // instruction is a store in the loop so the loop must does write.
404 DCHECK(side_effects_.GetLoopEffects(loop_info->GetHeader()).DoesAnyWrite());
405
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800406 if (loop_info->IsDefinedOutOfTheLoop(original_ref)) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800407 DCHECK(original_ref->GetBlock()->Dominates(loop_info->GetPreHeader()));
408 // Keep the store since its value may be needed at the loop header.
409 possibly_redundant = false;
410 } else {
411 // The singleton is created inside the loop. Value stored to it isn't needed at
412 // the loop header. This is true for outer loops also.
413 }
414 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700415 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700416 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800417 if (same_value || possibly_redundant) {
418 possibly_removed_stores_.push_back(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700419 }
Mingyao Yange9d6e602015-10-23 17:08:42 -0700420
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800421 if (!same_value) {
422 if (possibly_redundant) {
Mingyao Yang86974902017-03-01 14:03:51 -0800423 DCHECK(instruction->IsInstanceFieldSet() || instruction->IsArraySet());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800424 // Put the store as the heap value. If the value is loaded from heap
425 // by a load later, this store isn't really redundant.
426 heap_values[idx] = instruction;
427 } else {
428 heap_values[idx] = value;
429 }
430 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700431 // This store may kill values in other heap locations due to aliasing.
432 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800433 if (i == idx) {
434 continue;
435 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700436 if (heap_values[i] == value) {
437 // Same value should be kept even if aliasing happens.
438 continue;
439 }
440 if (heap_values[i] == kUnknownHeapValue) {
441 // Value is already unknown, no need for aliasing check.
442 continue;
443 }
444 if (heap_location_collector_.MayAlias(i, idx)) {
445 // Kill heap locations that may alias.
446 heap_values[i] = kUnknownHeapValue;
447 }
448 }
449 }
450
451 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
452 HInstruction* obj = instruction->InputAt(0);
453 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
454 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
455 VisitGetLocation(instruction, obj, offset, nullptr, declaring_class_def_index);
456 }
457
458 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
459 HInstruction* obj = instruction->InputAt(0);
460 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
461 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
462 HInstruction* value = instruction->InputAt(1);
463 VisitSetLocation(instruction, obj, offset, nullptr, declaring_class_def_index, value);
464 }
465
466 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
467 HInstruction* cls = instruction->InputAt(0);
468 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
469 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
470 VisitGetLocation(instruction, cls, offset, nullptr, declaring_class_def_index);
471 }
472
473 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
474 HInstruction* cls = instruction->InputAt(0);
475 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
476 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
477 HInstruction* value = instruction->InputAt(1);
478 VisitSetLocation(instruction, cls, offset, nullptr, declaring_class_def_index, value);
479 }
480
481 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
482 HInstruction* array = instruction->InputAt(0);
483 HInstruction* index = instruction->InputAt(1);
484 VisitGetLocation(instruction,
485 array,
486 HeapLocation::kInvalidFieldOffset,
487 index,
488 HeapLocation::kDeclaringClassDefIndexForArrays);
489 }
490
491 void VisitArraySet(HArraySet* instruction) OVERRIDE {
492 HInstruction* array = instruction->InputAt(0);
493 HInstruction* index = instruction->InputAt(1);
494 HInstruction* value = instruction->InputAt(2);
495 VisitSetLocation(instruction,
496 array,
497 HeapLocation::kInvalidFieldOffset,
498 index,
499 HeapLocation::kDeclaringClassDefIndexForArrays,
500 value);
501 }
502
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800503 void VisitDeoptimize(HDeoptimize* instruction) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100504 const ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800505 heap_values_for_[instruction->GetBlock()->GetBlockId()];
506 for (HInstruction* heap_value : heap_values) {
507 // Filter out fake instructions before checking instruction kind below.
508 if (heap_value == kUnknownHeapValue || heap_value == kDefaultHeapValue) {
509 continue;
510 }
511 // A store is kept as the heap value for possibly removed stores.
512 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
513 // Check whether the reference for a store is used by an environment local of
514 // HDeoptimize.
515 HInstruction* reference = heap_value->InputAt(0);
516 DCHECK(heap_location_collector_.FindReferenceInfoOf(reference)->IsSingleton());
517 for (const HUseListNode<HEnvironment*>& use : reference->GetEnvUses()) {
518 HEnvironment* user = use.GetUser();
519 if (user->GetHolder() == instruction) {
520 // The singleton for the store is visible at this deoptimization
521 // point. Need to keep the store so that the heap value is
522 // seen by the interpreter.
523 KeepIfIsStore(heap_value);
524 }
525 }
526 }
527 }
528 }
529
Mingyao Yang8df69d42015-10-22 15:40:58 -0700530 void HandleInvoke(HInstruction* invoke) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100531 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700532 heap_values_for_[invoke->GetBlock()->GetBlockId()];
533 for (size_t i = 0; i < heap_values.size(); i++) {
534 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
535 if (ref_info->IsSingleton()) {
536 // Singleton references cannot be seen by the callee.
537 } else {
538 heap_values[i] = kUnknownHeapValue;
539 }
540 }
541 }
542
543 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) OVERRIDE {
544 HandleInvoke(invoke);
545 }
546
547 void VisitInvokeVirtual(HInvokeVirtual* invoke) OVERRIDE {
548 HandleInvoke(invoke);
549 }
550
551 void VisitInvokeInterface(HInvokeInterface* invoke) OVERRIDE {
552 HandleInvoke(invoke);
553 }
554
555 void VisitInvokeUnresolved(HInvokeUnresolved* invoke) OVERRIDE {
556 HandleInvoke(invoke);
557 }
558
Orion Hodsonac141392017-01-13 11:53:47 +0000559 void VisitInvokePolymorphic(HInvokePolymorphic* invoke) OVERRIDE {
560 HandleInvoke(invoke);
561 }
562
Mingyao Yang8df69d42015-10-22 15:40:58 -0700563 void VisitClinitCheck(HClinitCheck* clinit) OVERRIDE {
564 HandleInvoke(clinit);
565 }
566
567 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* instruction) OVERRIDE {
568 // Conservatively treat it as an invocation.
569 HandleInvoke(instruction);
570 }
571
572 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* instruction) OVERRIDE {
573 // Conservatively treat it as an invocation.
574 HandleInvoke(instruction);
575 }
576
577 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* instruction) OVERRIDE {
578 // Conservatively treat it as an invocation.
579 HandleInvoke(instruction);
580 }
581
582 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* instruction) OVERRIDE {
583 // Conservatively treat it as an invocation.
584 HandleInvoke(instruction);
585 }
586
587 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
588 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_instance);
589 if (ref_info == nullptr) {
590 // new_instance isn't used for field accesses. No need to process it.
591 return;
592 }
Aart Bik71bf7b42016-11-16 10:17:46 -0800593 if (ref_info->IsSingletonAndRemovable() &&
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800594 !new_instance->IsFinalizable() &&
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000595 !new_instance->NeedsChecks()) {
Mingyao Yang062157f2016-03-02 10:15:36 -0800596 singleton_new_instances_.push_back(new_instance);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700597 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100598 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700599 heap_values_for_[new_instance->GetBlock()->GetBlockId()];
600 for (size_t i = 0; i < heap_values.size(); i++) {
601 HInstruction* ref =
602 heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo()->GetReference();
603 size_t offset = heap_location_collector_.GetHeapLocation(i)->GetOffset();
604 if (ref == new_instance && offset >= mirror::kObjectHeaderSize) {
605 // Instance fields except the header fields are set to default heap values.
606 heap_values[i] = kDefaultHeapValue;
607 }
608 }
609 }
610
Mingyao Yang86974902017-03-01 14:03:51 -0800611 void VisitNewArray(HNewArray* new_array) OVERRIDE {
612 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_array);
613 if (ref_info == nullptr) {
614 // new_array isn't used for array accesses. No need to process it.
615 return;
616 }
617 if (ref_info->IsSingletonAndRemovable()) {
618 singleton_new_arrays_.push_back(new_array);
619 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100620 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang86974902017-03-01 14:03:51 -0800621 heap_values_for_[new_array->GetBlock()->GetBlockId()];
622 for (size_t i = 0; i < heap_values.size(); i++) {
623 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
624 HInstruction* ref = location->GetReferenceInfo()->GetReference();
625 if (ref == new_array && location->GetIndex() != nullptr) {
626 // Array elements are set to default heap values.
627 heap_values[i] = kDefaultHeapValue;
628 }
629 }
630 }
631
Mingyao Yang8df69d42015-10-22 15:40:58 -0700632 // Find an instruction's substitute if it should be removed.
633 // Return the same instruction if it should not be removed.
634 HInstruction* FindSubstitute(HInstruction* instruction) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800635 size_t size = removed_loads_.size();
Mingyao Yang8df69d42015-10-22 15:40:58 -0700636 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800637 if (removed_loads_[i] == instruction) {
638 return substitute_instructions_for_loads_[i];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700639 }
640 }
641 return instruction;
642 }
643
644 const HeapLocationCollector& heap_location_collector_;
645 const SideEffectsAnalysis& side_effects_;
646
Vladimir Marko009d1662017-10-10 13:21:15 +0100647 // Use local allocator for allocating memory.
648 ScopedArenaAllocator allocator_;
649
Mingyao Yang8df69d42015-10-22 15:40:58 -0700650 // One array of heap values for each block.
Vladimir Marko009d1662017-10-10 13:21:15 +0100651 ScopedArenaVector<ScopedArenaVector<HInstruction*>> heap_values_for_;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700652
653 // We record the instructions that should be eliminated but may be
654 // used by heap locations. They'll be removed in the end.
Vladimir Marko009d1662017-10-10 13:21:15 +0100655 ScopedArenaVector<HInstruction*> removed_loads_;
656 ScopedArenaVector<HInstruction*> substitute_instructions_for_loads_;
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800657
658 // Stores in this list may be removed from the list later when it's
659 // found that the store cannot be eliminated.
Vladimir Marko009d1662017-10-10 13:21:15 +0100660 ScopedArenaVector<HInstruction*> possibly_removed_stores_;
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800661
Vladimir Marko009d1662017-10-10 13:21:15 +0100662 ScopedArenaVector<HInstruction*> singleton_new_instances_;
663 ScopedArenaVector<HInstruction*> singleton_new_arrays_;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700664
665 DISALLOW_COPY_AND_ASSIGN(LSEVisitor);
666};
667
668void LoadStoreElimination::Run() {
David Brazdil8993caf2015-12-07 10:04:40 +0000669 if (graph_->IsDebuggable() || graph_->HasTryCatch()) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700670 // Debugger may set heap values or trigger deoptimization of callers.
David Brazdil8993caf2015-12-07 10:04:40 +0000671 // Try/catch support not implemented yet.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700672 // Skip this optimization.
673 return;
674 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100675 const HeapLocationCollector& heap_location_collector = lsa_.GetHeapLocationCollector();
676 if (heap_location_collector.GetNumberOfHeapLocations() == 0) {
677 // No HeapLocation information from LSA, skip this optimization.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700678 return;
679 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100680
Aart Bikd30f2052017-09-12 13:07:00 -0700681 // TODO: analyze VecLoad/VecStore better.
682 if (graph_->HasSIMD()) {
683 return;
684 }
685
Igor Murashkin6ef45672017-08-08 13:59:55 -0700686 LSEVisitor lse_visitor(graph_, heap_location_collector, side_effects_, stats_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100687 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
688 lse_visitor.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700689 }
690 lse_visitor.RemoveInstructions();
691}
692
693} // namespace art