blob: 7d953c0963783132e2fec63864e6499d77030f07 [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() ||
xueliang.zhong27dae5f2017-09-21 13:48:55 +010086 load->IsArrayGet() ||
87 load->IsVecLoad());
Mingyao Yangfb8464a2015-11-02 10:56:59 -080088 HInstruction* substitute = substitute_instructions_for_loads_[i];
89 DCHECK(substitute != nullptr);
90 // Keep tracing substitute till one that's not removed.
91 HInstruction* sub_sub = FindSubstitute(substitute);
92 while (sub_sub != substitute) {
93 substitute = sub_sub;
94 sub_sub = FindSubstitute(substitute);
Mingyao Yang8df69d42015-10-22 15:40:58 -070095 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -080096 load->ReplaceWith(substitute);
97 load->GetBlock()->RemoveInstruction(load);
Mingyao Yang8df69d42015-10-22 15:40:58 -070098 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -080099
100 // At this point, stores in possibly_removed_stores_ can be safely removed.
Mingyao Yang86974902017-03-01 14:03:51 -0800101 for (HInstruction* store : possibly_removed_stores_) {
xueliang.zhong27dae5f2017-09-21 13:48:55 +0100102 DCHECK(store->IsInstanceFieldSet() ||
103 store->IsStaticFieldSet() ||
104 store->IsArraySet() ||
105 store->IsVecStore());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800106 store->GetBlock()->RemoveInstruction(store);
107 }
108
Igor Murashkind01745e2017-04-05 16:40:31 -0700109 // Eliminate singleton-classified instructions:
110 // * - Constructor fences (they never escape this thread).
111 // * - Allocations (if they are unused).
Mingyao Yang86974902017-03-01 14:03:51 -0800112 for (HInstruction* new_instance : singleton_new_instances_) {
Igor Murashkin6ef45672017-08-08 13:59:55 -0700113 size_t removed = HConstructorFence::RemoveConstructorFences(new_instance);
114 MaybeRecordStat(stats_,
115 MethodCompilationStat::kConstructorFenceRemovedLSE,
116 removed);
Igor Murashkind01745e2017-04-05 16:40:31 -0700117
Mingyao Yang062157f2016-03-02 10:15:36 -0800118 if (!new_instance->HasNonEnvironmentUses()) {
119 new_instance->RemoveEnvironmentUsers();
120 new_instance->GetBlock()->RemoveInstruction(new_instance);
121 }
122 }
Mingyao Yang86974902017-03-01 14:03:51 -0800123 for (HInstruction* new_array : singleton_new_arrays_) {
Igor Murashkin6ef45672017-08-08 13:59:55 -0700124 size_t removed = HConstructorFence::RemoveConstructorFences(new_array);
125 MaybeRecordStat(stats_,
126 MethodCompilationStat::kConstructorFenceRemovedLSE,
127 removed);
Igor Murashkind01745e2017-04-05 16:40:31 -0700128
Mingyao Yang86974902017-03-01 14:03:51 -0800129 if (!new_array->HasNonEnvironmentUses()) {
130 new_array->RemoveEnvironmentUsers();
131 new_array->GetBlock()->RemoveInstruction(new_array);
132 }
133 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700134 }
135
136 private:
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800137 // If heap_values[index] is an instance field store, need to keep the store.
138 // This is necessary if a heap value is killed due to merging, or loop side
139 // effects (which is essentially merging also), since a load later from the
140 // location won't be eliminated.
141 void KeepIfIsStore(HInstruction* heap_value) {
142 if (heap_value == kDefaultHeapValue ||
143 heap_value == kUnknownHeapValue ||
xueliang.zhong27dae5f2017-09-21 13:48:55 +0100144 !(heap_value->IsInstanceFieldSet() ||
145 heap_value->IsArraySet() ||
146 heap_value->IsVecStore())) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800147 return;
148 }
149 auto idx = std::find(possibly_removed_stores_.begin(),
150 possibly_removed_stores_.end(), heap_value);
151 if (idx != possibly_removed_stores_.end()) {
152 // Make sure the store is kept.
153 possibly_removed_stores_.erase(idx);
154 }
155 }
156
157 void HandleLoopSideEffects(HBasicBlock* block) {
158 DCHECK(block->IsLoopHeader());
159 int block_id = block->GetBlockId();
Vladimir Marko009d1662017-10-10 13:21:15 +0100160 ScopedArenaVector<HInstruction*>& heap_values = heap_values_for_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000161
162 // Don't eliminate loads in irreducible loops. This is safe for singletons, because
163 // they are always used by the non-eliminated loop-phi.
164 if (block->GetLoopInformation()->IsIrreducible()) {
165 if (kIsDebugBuild) {
166 for (size_t i = 0; i < heap_values.size(); i++) {
167 DCHECK_EQ(heap_values[i], kUnknownHeapValue);
168 }
169 }
170 return;
171 }
172
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800173 HBasicBlock* pre_header = block->GetLoopInformation()->GetPreHeader();
Vladimir Marko009d1662017-10-10 13:21:15 +0100174 ScopedArenaVector<HInstruction*>& pre_header_heap_values =
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800175 heap_values_for_[pre_header->GetBlockId()];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000176
Mingyao Yang803cbb92015-12-01 12:24:36 -0800177 // Inherit the values from pre-header.
178 for (size_t i = 0; i < heap_values.size(); i++) {
179 heap_values[i] = pre_header_heap_values[i];
180 }
181
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800182 // We do a single pass in reverse post order. For loops, use the side effects as a hint
183 // to see if the heap values should be killed.
184 if (side_effects_.GetLoopEffects(block).DoesAnyWrite()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800185 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800186 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
187 ReferenceInfo* ref_info = location->GetReferenceInfo();
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800188 if (ref_info->IsSingletonAndRemovable() &&
189 !location->IsValueKilledByLoopSideEffects()) {
190 // A removable singleton's field that's not stored into inside a loop is
191 // invariant throughout the loop. Nothing to do.
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800192 } else {
193 // heap value is killed by loop side effects (stored into directly, or
194 // due to aliasing). Or the heap value may be needed after method return
195 // or deoptimization.
Mingyao Yang803cbb92015-12-01 12:24:36 -0800196 KeepIfIsStore(pre_header_heap_values[i]);
197 heap_values[i] = kUnknownHeapValue;
Mingyao Yang803cbb92015-12-01 12:24:36 -0800198 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800199 }
200 }
201 }
202
Mingyao Yang8df69d42015-10-22 15:40:58 -0700203 void MergePredecessorValues(HBasicBlock* block) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100204 ArrayRef<HBasicBlock* const> predecessors(block->GetPredecessors());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700205 if (predecessors.size() == 0) {
206 return;
207 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700208
Vladimir Marko009d1662017-10-10 13:21:15 +0100209 ScopedArenaVector<HInstruction*>& heap_values = heap_values_for_[block->GetBlockId()];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700210 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700211 HInstruction* merged_value = nullptr;
212 // Whether merged_value is a result that's merged from all predecessors.
213 bool from_all_predecessors = true;
214 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
215 HInstruction* singleton_ref = nullptr;
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800216 if (ref_info->IsSingleton()) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700217 // We do more analysis of liveness when merging heap values for such
218 // cases since stores into such references may potentially be eliminated.
219 singleton_ref = ref_info->GetReference();
220 }
221
222 for (HBasicBlock* predecessor : predecessors) {
223 HInstruction* pred_value = heap_values_for_[predecessor->GetBlockId()][i];
224 if ((singleton_ref != nullptr) &&
225 !singleton_ref->GetBlock()->Dominates(predecessor)) {
226 // singleton_ref is not live in this predecessor. Skip this predecessor since
227 // it does not really have the location.
228 DCHECK_EQ(pred_value, kUnknownHeapValue);
229 from_all_predecessors = false;
230 continue;
231 }
232 if (merged_value == nullptr) {
233 // First seen heap value.
234 merged_value = pred_value;
235 } else if (pred_value != merged_value) {
236 // There are conflicting values.
237 merged_value = kUnknownHeapValue;
238 break;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700239 }
240 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800241
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800242 if (merged_value == kUnknownHeapValue || ref_info->IsSingletonAndNonRemovable()) {
243 // There are conflicting heap values from different predecessors,
244 // or the heap value may be needed after method return or deoptimization.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800245 // Keep the last store in each predecessor since future loads cannot be eliminated.
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700246 for (HBasicBlock* predecessor : predecessors) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100247 ScopedArenaVector<HInstruction*>& pred_values =
248 heap_values_for_[predecessor->GetBlockId()];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800249 KeepIfIsStore(pred_values[i]);
250 }
251 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700252
253 if ((merged_value == nullptr) || !from_all_predecessors) {
254 DCHECK(singleton_ref != nullptr);
255 DCHECK((singleton_ref->GetBlock() == block) ||
256 !singleton_ref->GetBlock()->Dominates(block));
257 // singleton_ref is not defined before block or defined only in some of its
258 // predecessors, so block doesn't really have the location at its entry.
259 heap_values[i] = kUnknownHeapValue;
260 } else {
261 heap_values[i] = merged_value;
262 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700263 }
264 }
265
266 // `instruction` is being removed. Try to see if the null check on it
267 // can be removed. This can happen if the same value is set in two branches
268 // but not in dominators. Such as:
269 // int[] a = foo();
270 // if () {
271 // a[0] = 2;
272 // } else {
273 // a[0] = 2;
274 // }
275 // // a[0] can now be replaced with constant 2, and the null check on it can be removed.
276 void TryRemovingNullCheck(HInstruction* instruction) {
277 HInstruction* prev = instruction->GetPrevious();
278 if ((prev != nullptr) && prev->IsNullCheck() && (prev == instruction->InputAt(0))) {
279 // Previous instruction is a null check for this instruction. Remove the null check.
280 prev->ReplaceWith(prev->InputAt(0));
281 prev->GetBlock()->RemoveInstruction(prev);
282 }
283 }
284
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100285 HInstruction* GetDefaultValue(DataType::Type type) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700286 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100287 case DataType::Type::kReference:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700288 return GetGraph()->GetNullConstant();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100289 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100290 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100291 case DataType::Type::kInt8:
292 case DataType::Type::kUint16:
293 case DataType::Type::kInt16:
294 case DataType::Type::kInt32:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700295 return GetGraph()->GetIntConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100296 case DataType::Type::kInt64:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700297 return GetGraph()->GetLongConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100298 case DataType::Type::kFloat32:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700299 return GetGraph()->GetFloatConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100300 case DataType::Type::kFloat64:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700301 return GetGraph()->GetDoubleConstant(0);
302 default:
303 UNREACHABLE();
304 }
305 }
306
307 void VisitGetLocation(HInstruction* instruction,
308 HInstruction* ref,
309 size_t offset,
310 HInstruction* index,
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100311 size_t vector_length,
Mingyao Yang8df69d42015-10-22 15:40:58 -0700312 int16_t declaring_class_def_index) {
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100313 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700314 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
315 size_t idx = heap_location_collector_.FindHeapLocationIndex(
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100316 ref_info, offset, index, vector_length, declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700317 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
Vladimir Marko009d1662017-10-10 13:21:15 +0100318 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700319 heap_values_for_[instruction->GetBlock()->GetBlockId()];
320 HInstruction* heap_value = heap_values[idx];
321 if (heap_value == kDefaultHeapValue) {
322 HInstruction* constant = GetDefaultValue(instruction->GetType());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800323 removed_loads_.push_back(instruction);
324 substitute_instructions_for_loads_.push_back(constant);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700325 heap_values[idx] = constant;
326 return;
327 }
Mingyao Yang86974902017-03-01 14:03:51 -0800328 if (heap_value != kUnknownHeapValue) {
xueliang.zhong27dae5f2017-09-21 13:48:55 +0100329 if (heap_value->IsInstanceFieldSet() ||
330 heap_value->IsArraySet() ||
331 heap_value->IsVecStore()) {
Mingyao Yang86974902017-03-01 14:03:51 -0800332 HInstruction* store = heap_value;
333 // This load must be from a singleton since it's from the same
334 // field/element that a "removed" store puts the value. That store
335 // must be to a singleton's field/element.
336 DCHECK(ref_info->IsSingleton());
337 // Get the real heap value of the store.
338 heap_value = heap_value->IsInstanceFieldSet() ? store->InputAt(1) : store->InputAt(2);
339 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800340 }
David Brazdil15693bf2015-12-16 10:30:45 +0000341 if (heap_value == kUnknownHeapValue) {
342 // Load isn't eliminated. Put the load as the value into the HeapLocation.
343 // This acts like GVN but with better aliasing analysis.
344 heap_values[idx] = instruction;
345 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100346 if (DataType::Kind(heap_value->GetType()) != DataType::Kind(instruction->GetType())) {
Nicolas Geoffray03971632016-03-17 10:44:24 +0000347 // The only situation where the same heap location has different type is when
Nicolas Geoffray65fef302016-05-04 14:00:12 +0100348 // we do an array get on an instruction that originates from the null constant
349 // (the null could be behind a field access, an array access, a null check or
350 // a bound type).
351 // In order to stay properly typed on primitive types, we do not eliminate
352 // the array gets.
Nicolas Geoffray03971632016-03-17 10:44:24 +0000353 if (kIsDebugBuild) {
354 DCHECK(heap_value->IsArrayGet()) << heap_value->DebugName();
355 DCHECK(instruction->IsArrayGet()) << instruction->DebugName();
Nicolas Geoffray03971632016-03-17 10:44:24 +0000356 }
357 return;
358 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800359 removed_loads_.push_back(instruction);
360 substitute_instructions_for_loads_.push_back(heap_value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700361 TryRemovingNullCheck(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700362 }
363 }
364
365 bool Equal(HInstruction* heap_value, HInstruction* value) {
366 if (heap_value == value) {
367 return true;
368 }
369 if (heap_value == kDefaultHeapValue && GetDefaultValue(value->GetType()) == value) {
370 return true;
371 }
372 return false;
373 }
374
375 void VisitSetLocation(HInstruction* instruction,
376 HInstruction* ref,
377 size_t offset,
378 HInstruction* index,
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100379 size_t vector_length,
Mingyao Yang8df69d42015-10-22 15:40:58 -0700380 int16_t declaring_class_def_index,
381 HInstruction* value) {
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100382 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700383 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
384 size_t idx = heap_location_collector_.FindHeapLocationIndex(
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100385 ref_info, offset, index, vector_length, declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700386 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
Vladimir Marko009d1662017-10-10 13:21:15 +0100387 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700388 heap_values_for_[instruction->GetBlock()->GetBlockId()];
389 HInstruction* heap_value = heap_values[idx];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800390 bool same_value = false;
391 bool possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700392 if (Equal(heap_value, value)) {
393 // Store into the heap location with the same value.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800394 same_value = true;
Mingyao Yang0e3151b2017-10-30 11:19:57 -0700395 } else if (index != nullptr &&
396 heap_location_collector_.GetHeapLocation(idx)->HasAliasedLocations()) {
397 // For array element, don't eliminate stores if the location can be aliased
398 // (due to either ref or index aliasing).
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800399 } else if (ref_info->IsSingleton()) {
Mingyao Yang025c1a62017-10-30 11:19:57 -0700400 // Store into a field/element of a singleton. The value cannot be killed due to
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800401 // aliasing/invocation. It can be redundant since future loads can
402 // directly get the value set by this instruction. The value can still be killed due to
403 // merging or loop side effects. Stores whose values are killed due to merging/loop side
404 // effects later will be removed from possibly_removed_stores_ when that is detected.
405 // Stores whose values may be needed after method return or deoptimization
406 // are also removed from possibly_removed_stores_ when that is detected.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800407 possibly_redundant = true;
Mingyao Yang025c1a62017-10-30 11:19:57 -0700408 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
409 if (loop_info != nullptr) {
410 // instruction is a store in the loop so the loop must does write.
411 DCHECK(side_effects_.GetLoopEffects(loop_info->GetHeader()).DoesAnyWrite());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800412
Mingyao Yang025c1a62017-10-30 11:19:57 -0700413 if (loop_info->IsDefinedOutOfTheLoop(original_ref)) {
414 DCHECK(original_ref->GetBlock()->Dominates(loop_info->GetPreHeader()));
415 // Keep the store since its value may be needed at the loop header.
416 possibly_redundant = false;
417 } else {
418 // The singleton is created inside the loop. Value stored to it isn't needed at
419 // the loop header. This is true for outer loops also.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800420 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700421 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700422 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800423 if (same_value || possibly_redundant) {
424 possibly_removed_stores_.push_back(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700425 }
Mingyao Yange9d6e602015-10-23 17:08:42 -0700426
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800427 if (!same_value) {
428 if (possibly_redundant) {
xueliang.zhong27dae5f2017-09-21 13:48:55 +0100429 DCHECK(instruction->IsInstanceFieldSet() ||
430 instruction->IsArraySet() ||
431 instruction->IsVecStore());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800432 // Put the store as the heap value. If the value is loaded from heap
433 // by a load later, this store isn't really redundant.
434 heap_values[idx] = instruction;
435 } else {
436 heap_values[idx] = value;
437 }
438 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700439 // This store may kill values in other heap locations due to aliasing.
440 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800441 if (i == idx) {
442 continue;
443 }
xueliang.zhong27dae5f2017-09-21 13:48:55 +0100444 if (heap_values[i] == value && !instruction->IsVecOperation()) {
445 // For field/array, same value should be kept even if aliasing happens.
446 //
447 // For vector values , this is NOT safe. For example:
448 // packed_data = [0xA, 0xB, 0xC, 0xD]; <-- Different values in each lane.
449 // VecStore array[i ,i+1,i+2,i+3] = packed_data;
450 // VecStore array[i+1,i+2,i+3,i+4] = packed_data; <-- We are here (partial overlap).
451 // VecLoad vx = array[i,i+1,i+2,i+3]; <-- Cannot be eliminated.
452 //
453 // TODO: to allow such 'same value' optimization on vector data,
454 // LSA needs to report more fine-grain MAY alias information:
455 // (1) May alias due to two vector data partial overlap.
456 // e.g. a[i..i+3] and a[i+1,..,i+4].
457 // (2) May alias due to two vector data may complete overlap each other.
458 // e.g. a[i..i+3] and b[i..i+3].
459 // (3) May alias but the exact relationship between two locations is unknown.
460 // e.g. a[i..i+3] and b[j..j+3], where values of a,b,i,j are all unknown.
461 // This 'same value' optimization can apply only on case (2).
Mingyao Yang8df69d42015-10-22 15:40:58 -0700462 continue;
463 }
464 if (heap_values[i] == kUnknownHeapValue) {
465 // Value is already unknown, no need for aliasing check.
466 continue;
467 }
468 if (heap_location_collector_.MayAlias(i, idx)) {
469 // Kill heap locations that may alias.
470 heap_values[i] = kUnknownHeapValue;
471 }
472 }
473 }
474
475 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
476 HInstruction* obj = instruction->InputAt(0);
477 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
478 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100479 VisitGetLocation(instruction,
480 obj,
481 offset,
482 nullptr,
483 HeapLocation::kScalar,
484 declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700485 }
486
487 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
488 HInstruction* obj = instruction->InputAt(0);
489 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
490 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
491 HInstruction* value = instruction->InputAt(1);
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100492 VisitSetLocation(instruction,
493 obj,
494 offset,
495 nullptr,
496 HeapLocation::kScalar,
497 declaring_class_def_index,
498 value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700499 }
500
501 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
502 HInstruction* cls = instruction->InputAt(0);
503 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
504 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100505 VisitGetLocation(instruction,
506 cls,
507 offset,
508 nullptr,
509 HeapLocation::kScalar,
510 declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700511 }
512
513 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
514 HInstruction* cls = instruction->InputAt(0);
515 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
516 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
517 HInstruction* value = instruction->InputAt(1);
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100518 VisitSetLocation(instruction,
519 cls,
520 offset,
521 nullptr,
522 HeapLocation::kScalar,
523 declaring_class_def_index,
524 value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700525 }
526
527 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
528 HInstruction* array = instruction->InputAt(0);
529 HInstruction* index = instruction->InputAt(1);
530 VisitGetLocation(instruction,
531 array,
532 HeapLocation::kInvalidFieldOffset,
533 index,
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100534 HeapLocation::kScalar,
Mingyao Yang8df69d42015-10-22 15:40:58 -0700535 HeapLocation::kDeclaringClassDefIndexForArrays);
536 }
537
538 void VisitArraySet(HArraySet* instruction) OVERRIDE {
539 HInstruction* array = instruction->InputAt(0);
540 HInstruction* index = instruction->InputAt(1);
541 HInstruction* value = instruction->InputAt(2);
542 VisitSetLocation(instruction,
543 array,
544 HeapLocation::kInvalidFieldOffset,
545 index,
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100546 HeapLocation::kScalar,
Mingyao Yang8df69d42015-10-22 15:40:58 -0700547 HeapLocation::kDeclaringClassDefIndexForArrays,
548 value);
549 }
550
xueliang.zhong27dae5f2017-09-21 13:48:55 +0100551 void VisitVecLoad(HVecLoad* instruction) OVERRIDE {
552 HInstruction* array = instruction->InputAt(0);
553 HInstruction* index = instruction->InputAt(1);
554 size_t vector_length = instruction->GetVectorLength();
555 VisitGetLocation(instruction,
556 array,
557 HeapLocation::kInvalidFieldOffset,
558 index,
559 vector_length,
560 HeapLocation::kDeclaringClassDefIndexForArrays);
561 }
562
563 void VisitVecStore(HVecStore* instruction) OVERRIDE {
564 HInstruction* array = instruction->InputAt(0);
565 HInstruction* index = instruction->InputAt(1);
566 HInstruction* value = instruction->InputAt(2);
567 size_t vector_length = instruction->GetVectorLength();
568 VisitSetLocation(instruction,
569 array,
570 HeapLocation::kInvalidFieldOffset,
571 index,
572 vector_length,
573 HeapLocation::kDeclaringClassDefIndexForArrays,
574 value);
575 }
576
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800577 void VisitDeoptimize(HDeoptimize* instruction) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100578 const ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800579 heap_values_for_[instruction->GetBlock()->GetBlockId()];
580 for (HInstruction* heap_value : heap_values) {
581 // Filter out fake instructions before checking instruction kind below.
582 if (heap_value == kUnknownHeapValue || heap_value == kDefaultHeapValue) {
583 continue;
584 }
585 // A store is kept as the heap value for possibly removed stores.
xueliang.zhong27dae5f2017-09-21 13:48:55 +0100586 if (heap_value->IsInstanceFieldSet() ||
587 heap_value->IsArraySet() ||
588 heap_value->IsVecStore()) {
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800589 // Check whether the reference for a store is used by an environment local of
590 // HDeoptimize.
591 HInstruction* reference = heap_value->InputAt(0);
592 DCHECK(heap_location_collector_.FindReferenceInfoOf(reference)->IsSingleton());
593 for (const HUseListNode<HEnvironment*>& use : reference->GetEnvUses()) {
594 HEnvironment* user = use.GetUser();
595 if (user->GetHolder() == instruction) {
596 // The singleton for the store is visible at this deoptimization
597 // point. Need to keep the store so that the heap value is
598 // seen by the interpreter.
599 KeepIfIsStore(heap_value);
600 }
601 }
602 }
603 }
604 }
605
Mingyao Yang293f1c02017-11-08 15:22:17 -0800606 void HandleInvoke(HInstruction* instruction) {
607 SideEffects side_effects = instruction->GetSideEffects();
Vladimir Marko009d1662017-10-10 13:21:15 +0100608 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang293f1c02017-11-08 15:22:17 -0800609 heap_values_for_[instruction->GetBlock()->GetBlockId()];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700610 for (size_t i = 0; i < heap_values.size(); i++) {
611 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
612 if (ref_info->IsSingleton()) {
613 // Singleton references cannot be seen by the callee.
614 } else {
Mingyao Yang293f1c02017-11-08 15:22:17 -0800615 if (side_effects.DoesAnyRead()) {
616 KeepIfIsStore(heap_values[i]);
617 }
618 if (side_effects.DoesAnyWrite()) {
619 heap_values[i] = kUnknownHeapValue;
620 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700621 }
622 }
623 }
624
Mingyao Yangc62b7ec2017-10-25 16:42:15 -0700625 void VisitInvoke(HInvoke* invoke) OVERRIDE {
Orion Hodsonac141392017-01-13 11:53:47 +0000626 HandleInvoke(invoke);
627 }
628
Mingyao Yang8df69d42015-10-22 15:40:58 -0700629 void VisitClinitCheck(HClinitCheck* clinit) OVERRIDE {
630 HandleInvoke(clinit);
631 }
632
633 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* instruction) OVERRIDE {
634 // Conservatively treat it as an invocation.
635 HandleInvoke(instruction);
636 }
637
638 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* instruction) OVERRIDE {
639 // Conservatively treat it as an invocation.
640 HandleInvoke(instruction);
641 }
642
643 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* instruction) OVERRIDE {
644 // Conservatively treat it as an invocation.
645 HandleInvoke(instruction);
646 }
647
648 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* instruction) OVERRIDE {
649 // Conservatively treat it as an invocation.
650 HandleInvoke(instruction);
651 }
652
653 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
654 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_instance);
655 if (ref_info == nullptr) {
656 // new_instance isn't used for field accesses. No need to process it.
657 return;
658 }
Mingyao Yang025c1a62017-10-30 11:19:57 -0700659 if (ref_info->IsSingletonAndRemovable() && !new_instance->NeedsChecks()) {
660 DCHECK(!new_instance->IsFinalizable());
Mingyao Yang062157f2016-03-02 10:15:36 -0800661 singleton_new_instances_.push_back(new_instance);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700662 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100663 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700664 heap_values_for_[new_instance->GetBlock()->GetBlockId()];
665 for (size_t i = 0; i < heap_values.size(); i++) {
666 HInstruction* ref =
667 heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo()->GetReference();
668 size_t offset = heap_location_collector_.GetHeapLocation(i)->GetOffset();
669 if (ref == new_instance && offset >= mirror::kObjectHeaderSize) {
670 // Instance fields except the header fields are set to default heap values.
671 heap_values[i] = kDefaultHeapValue;
672 }
673 }
674 }
675
Mingyao Yang86974902017-03-01 14:03:51 -0800676 void VisitNewArray(HNewArray* new_array) OVERRIDE {
677 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_array);
678 if (ref_info == nullptr) {
679 // new_array isn't used for array accesses. No need to process it.
680 return;
681 }
682 if (ref_info->IsSingletonAndRemovable()) {
683 singleton_new_arrays_.push_back(new_array);
684 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100685 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang86974902017-03-01 14:03:51 -0800686 heap_values_for_[new_array->GetBlock()->GetBlockId()];
687 for (size_t i = 0; i < heap_values.size(); i++) {
688 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
689 HInstruction* ref = location->GetReferenceInfo()->GetReference();
690 if (ref == new_array && location->GetIndex() != nullptr) {
691 // Array elements are set to default heap values.
692 heap_values[i] = kDefaultHeapValue;
693 }
694 }
695 }
696
Mingyao Yang8df69d42015-10-22 15:40:58 -0700697 // Find an instruction's substitute if it should be removed.
698 // Return the same instruction if it should not be removed.
699 HInstruction* FindSubstitute(HInstruction* instruction) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800700 size_t size = removed_loads_.size();
Mingyao Yang8df69d42015-10-22 15:40:58 -0700701 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800702 if (removed_loads_[i] == instruction) {
703 return substitute_instructions_for_loads_[i];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700704 }
705 }
706 return instruction;
707 }
708
709 const HeapLocationCollector& heap_location_collector_;
710 const SideEffectsAnalysis& side_effects_;
711
Vladimir Marko009d1662017-10-10 13:21:15 +0100712 // Use local allocator for allocating memory.
713 ScopedArenaAllocator allocator_;
714
Mingyao Yang8df69d42015-10-22 15:40:58 -0700715 // One array of heap values for each block.
Vladimir Marko009d1662017-10-10 13:21:15 +0100716 ScopedArenaVector<ScopedArenaVector<HInstruction*>> heap_values_for_;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700717
718 // We record the instructions that should be eliminated but may be
719 // used by heap locations. They'll be removed in the end.
Vladimir Marko009d1662017-10-10 13:21:15 +0100720 ScopedArenaVector<HInstruction*> removed_loads_;
721 ScopedArenaVector<HInstruction*> substitute_instructions_for_loads_;
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800722
723 // Stores in this list may be removed from the list later when it's
724 // found that the store cannot be eliminated.
Vladimir Marko009d1662017-10-10 13:21:15 +0100725 ScopedArenaVector<HInstruction*> possibly_removed_stores_;
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800726
Vladimir Marko009d1662017-10-10 13:21:15 +0100727 ScopedArenaVector<HInstruction*> singleton_new_instances_;
728 ScopedArenaVector<HInstruction*> singleton_new_arrays_;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700729
730 DISALLOW_COPY_AND_ASSIGN(LSEVisitor);
731};
732
733void LoadStoreElimination::Run() {
David Brazdil8993caf2015-12-07 10:04:40 +0000734 if (graph_->IsDebuggable() || graph_->HasTryCatch()) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700735 // Debugger may set heap values or trigger deoptimization of callers.
David Brazdil8993caf2015-12-07 10:04:40 +0000736 // Try/catch support not implemented yet.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700737 // Skip this optimization.
738 return;
739 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100740 const HeapLocationCollector& heap_location_collector = lsa_.GetHeapLocationCollector();
741 if (heap_location_collector.GetNumberOfHeapLocations() == 0) {
742 // No HeapLocation information from LSA, skip this optimization.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700743 return;
744 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100745
Igor Murashkin6ef45672017-08-08 13:59:55 -0700746 LSEVisitor lse_visitor(graph_, heap_location_collector, side_effects_, stats_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100747 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
748 lse_visitor.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700749 }
750 lse_visitor.RemoveInstructions();
751}
752
753} // namespace art