blob: f03fffabe2c4da1321d60b638895d1df2023adae [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
Mingyao Yang206070c2017-11-29 23:01:58 -080077 // Find an instruction's substitute if it should be removed.
78 // Return the same instruction if it should not be removed.
79 HInstruction* FindSubstitute(HInstruction* instruction) {
80 size_t size = removed_loads_.size();
81 for (size_t i = 0; i < size; i++) {
82 if (removed_loads_[i] == instruction) {
83 return substitute_instructions_for_loads_[i];
84 }
85 }
86 return instruction;
87 }
88
Mingyao Yang8df69d42015-10-22 15:40:58 -070089 // Remove recorded instructions that should be eliminated.
90 void RemoveInstructions() {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080091 size_t size = removed_loads_.size();
92 DCHECK_EQ(size, substitute_instructions_for_loads_.size());
Mingyao Yang8df69d42015-10-22 15:40:58 -070093 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080094 HInstruction* load = removed_loads_[i];
95 DCHECK(load != nullptr);
96 DCHECK(load->IsInstanceFieldGet() ||
97 load->IsStaticFieldGet() ||
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +000098 load->IsArrayGet());
Mingyao Yangfb8464a2015-11-02 10:56:59 -080099 HInstruction* substitute = substitute_instructions_for_loads_[i];
100 DCHECK(substitute != nullptr);
Mingyao Yang206070c2017-11-29 23:01:58 -0800101 // We proactively retrieve the substitute for a removed load, so
102 // a load that has a substitute should not be observed as a heap
103 // location value.
104 DCHECK_EQ(FindSubstitute(substitute), substitute);
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800105 load->ReplaceWith(substitute);
106 load->GetBlock()->RemoveInstruction(load);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700107 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800108
109 // At this point, stores in possibly_removed_stores_ can be safely removed.
Mingyao Yang86974902017-03-01 14:03:51 -0800110 for (HInstruction* store : possibly_removed_stores_) {
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +0000111 DCHECK(store->IsInstanceFieldSet() || store->IsStaticFieldSet() || store->IsArraySet());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800112 store->GetBlock()->RemoveInstruction(store);
113 }
114
Igor Murashkind01745e2017-04-05 16:40:31 -0700115 // Eliminate singleton-classified instructions:
116 // * - Constructor fences (they never escape this thread).
117 // * - Allocations (if they are unused).
Mingyao Yang86974902017-03-01 14:03:51 -0800118 for (HInstruction* new_instance : singleton_new_instances_) {
Igor Murashkin6ef45672017-08-08 13:59:55 -0700119 size_t removed = HConstructorFence::RemoveConstructorFences(new_instance);
120 MaybeRecordStat(stats_,
121 MethodCompilationStat::kConstructorFenceRemovedLSE,
122 removed);
Igor Murashkind01745e2017-04-05 16:40:31 -0700123
Mingyao Yang062157f2016-03-02 10:15:36 -0800124 if (!new_instance->HasNonEnvironmentUses()) {
125 new_instance->RemoveEnvironmentUsers();
126 new_instance->GetBlock()->RemoveInstruction(new_instance);
127 }
128 }
Mingyao Yang86974902017-03-01 14:03:51 -0800129 for (HInstruction* new_array : singleton_new_arrays_) {
Igor Murashkin6ef45672017-08-08 13:59:55 -0700130 size_t removed = HConstructorFence::RemoveConstructorFences(new_array);
131 MaybeRecordStat(stats_,
132 MethodCompilationStat::kConstructorFenceRemovedLSE,
133 removed);
Igor Murashkind01745e2017-04-05 16:40:31 -0700134
Mingyao Yang86974902017-03-01 14:03:51 -0800135 if (!new_array->HasNonEnvironmentUses()) {
136 new_array->RemoveEnvironmentUsers();
137 new_array->GetBlock()->RemoveInstruction(new_array);
138 }
139 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700140 }
141
142 private:
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800143 // If heap_values[index] is an instance field store, need to keep the store.
144 // This is necessary if a heap value is killed due to merging, or loop side
145 // effects (which is essentially merging also), since a load later from the
146 // location won't be eliminated.
147 void KeepIfIsStore(HInstruction* heap_value) {
148 if (heap_value == kDefaultHeapValue ||
149 heap_value == kUnknownHeapValue ||
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +0000150 !(heap_value->IsInstanceFieldSet() || heap_value->IsArraySet())) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800151 return;
152 }
153 auto idx = std::find(possibly_removed_stores_.begin(),
154 possibly_removed_stores_.end(), heap_value);
155 if (idx != possibly_removed_stores_.end()) {
156 // Make sure the store is kept.
157 possibly_removed_stores_.erase(idx);
158 }
159 }
160
161 void HandleLoopSideEffects(HBasicBlock* block) {
162 DCHECK(block->IsLoopHeader());
163 int block_id = block->GetBlockId();
Vladimir Marko009d1662017-10-10 13:21:15 +0100164 ScopedArenaVector<HInstruction*>& heap_values = heap_values_for_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000165
166 // Don't eliminate loads in irreducible loops. This is safe for singletons, because
167 // they are always used by the non-eliminated loop-phi.
168 if (block->GetLoopInformation()->IsIrreducible()) {
169 if (kIsDebugBuild) {
170 for (size_t i = 0; i < heap_values.size(); i++) {
171 DCHECK_EQ(heap_values[i], kUnknownHeapValue);
172 }
173 }
174 return;
175 }
176
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800177 HBasicBlock* pre_header = block->GetLoopInformation()->GetPreHeader();
Vladimir Marko009d1662017-10-10 13:21:15 +0100178 ScopedArenaVector<HInstruction*>& pre_header_heap_values =
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800179 heap_values_for_[pre_header->GetBlockId()];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000180
Mingyao Yang803cbb92015-12-01 12:24:36 -0800181 // Inherit the values from pre-header.
182 for (size_t i = 0; i < heap_values.size(); i++) {
183 heap_values[i] = pre_header_heap_values[i];
184 }
185
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800186 // We do a single pass in reverse post order. For loops, use the side effects as a hint
187 // to see if the heap values should be killed.
188 if (side_effects_.GetLoopEffects(block).DoesAnyWrite()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800189 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800190 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
191 ReferenceInfo* ref_info = location->GetReferenceInfo();
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800192 if (ref_info->IsSingletonAndRemovable() &&
193 !location->IsValueKilledByLoopSideEffects()) {
194 // A removable singleton's field that's not stored into inside a loop is
195 // invariant throughout the loop. Nothing to do.
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800196 } else {
197 // heap value is killed by loop side effects (stored into directly, or
198 // due to aliasing). Or the heap value may be needed after method return
199 // or deoptimization.
Mingyao Yang803cbb92015-12-01 12:24:36 -0800200 KeepIfIsStore(pre_header_heap_values[i]);
201 heap_values[i] = kUnknownHeapValue;
Mingyao Yang803cbb92015-12-01 12:24:36 -0800202 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800203 }
204 }
205 }
206
Mingyao Yang8df69d42015-10-22 15:40:58 -0700207 void MergePredecessorValues(HBasicBlock* block) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100208 ArrayRef<HBasicBlock* const> predecessors(block->GetPredecessors());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700209 if (predecessors.size() == 0) {
210 return;
211 }
Mingyao Yang46721ef2017-10-05 14:45:17 -0700212 if (block->IsExitBlock()) {
213 // Exit block doesn't really merge values since the control flow ends in
214 // its predecessors. Each predecessor needs to make sure stores are kept
215 // if necessary.
216 return;
217 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700218
Vladimir Marko009d1662017-10-10 13:21:15 +0100219 ScopedArenaVector<HInstruction*>& heap_values = heap_values_for_[block->GetBlockId()];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700220 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700221 HInstruction* merged_value = nullptr;
222 // Whether merged_value is a result that's merged from all predecessors.
223 bool from_all_predecessors = true;
224 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
225 HInstruction* singleton_ref = nullptr;
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800226 if (ref_info->IsSingleton()) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700227 // We do more analysis of liveness when merging heap values for such
228 // cases since stores into such references may potentially be eliminated.
229 singleton_ref = ref_info->GetReference();
230 }
231
232 for (HBasicBlock* predecessor : predecessors) {
233 HInstruction* pred_value = heap_values_for_[predecessor->GetBlockId()][i];
234 if ((singleton_ref != nullptr) &&
235 !singleton_ref->GetBlock()->Dominates(predecessor)) {
236 // singleton_ref is not live in this predecessor. Skip this predecessor since
237 // it does not really have the location.
238 DCHECK_EQ(pred_value, kUnknownHeapValue);
239 from_all_predecessors = false;
240 continue;
241 }
242 if (merged_value == nullptr) {
243 // First seen heap value.
244 merged_value = pred_value;
245 } else if (pred_value != merged_value) {
246 // There are conflicting values.
247 merged_value = kUnknownHeapValue;
248 break;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700249 }
250 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800251
Mingyao Yang46721ef2017-10-05 14:45:17 -0700252 if (ref_info->IsSingleton()) {
253 if (ref_info->IsSingletonAndNonRemovable() ||
254 (merged_value == kUnknownHeapValue &&
255 !block->IsSingleReturnOrReturnVoidAllowingPhis())) {
256 // The heap value may be needed after method return or deoptimization,
257 // or there are conflicting heap values from different predecessors and
258 // this block is not a single return,
259 // keep the last store in each predecessor since future loads may not
260 // be eliminated.
261 for (HBasicBlock* predecessor : predecessors) {
262 ScopedArenaVector<HInstruction*>& pred_values =
263 heap_values_for_[predecessor->GetBlockId()];
264 KeepIfIsStore(pred_values[i]);
265 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800266 }
Mingyao Yang46721ef2017-10-05 14:45:17 -0700267 } else {
268 // Currenctly we don't eliminate stores to non-singletons.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800269 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700270
271 if ((merged_value == nullptr) || !from_all_predecessors) {
272 DCHECK(singleton_ref != nullptr);
273 DCHECK((singleton_ref->GetBlock() == block) ||
274 !singleton_ref->GetBlock()->Dominates(block));
275 // singleton_ref is not defined before block or defined only in some of its
276 // predecessors, so block doesn't really have the location at its entry.
277 heap_values[i] = kUnknownHeapValue;
278 } else {
279 heap_values[i] = merged_value;
280 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700281 }
282 }
283
284 // `instruction` is being removed. Try to see if the null check on it
285 // can be removed. This can happen if the same value is set in two branches
286 // but not in dominators. Such as:
287 // int[] a = foo();
288 // if () {
289 // a[0] = 2;
290 // } else {
291 // a[0] = 2;
292 // }
293 // // a[0] can now be replaced with constant 2, and the null check on it can be removed.
294 void TryRemovingNullCheck(HInstruction* instruction) {
295 HInstruction* prev = instruction->GetPrevious();
296 if ((prev != nullptr) && prev->IsNullCheck() && (prev == instruction->InputAt(0))) {
297 // Previous instruction is a null check for this instruction. Remove the null check.
298 prev->ReplaceWith(prev->InputAt(0));
299 prev->GetBlock()->RemoveInstruction(prev);
300 }
301 }
302
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100303 HInstruction* GetDefaultValue(DataType::Type type) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700304 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100305 case DataType::Type::kReference:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700306 return GetGraph()->GetNullConstant();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100307 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +0100308 case DataType::Type::kUint8:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100309 case DataType::Type::kInt8:
310 case DataType::Type::kUint16:
311 case DataType::Type::kInt16:
312 case DataType::Type::kInt32:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700313 return GetGraph()->GetIntConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100314 case DataType::Type::kInt64:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700315 return GetGraph()->GetLongConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100316 case DataType::Type::kFloat32:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700317 return GetGraph()->GetFloatConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100318 case DataType::Type::kFloat64:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700319 return GetGraph()->GetDoubleConstant(0);
320 default:
321 UNREACHABLE();
322 }
323 }
324
325 void VisitGetLocation(HInstruction* instruction,
326 HInstruction* ref,
327 size_t offset,
328 HInstruction* index,
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100329 size_t vector_length,
Mingyao Yang8df69d42015-10-22 15:40:58 -0700330 int16_t declaring_class_def_index) {
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100331 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700332 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
333 size_t idx = heap_location_collector_.FindHeapLocationIndex(
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100334 ref_info, offset, index, vector_length, declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700335 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
Vladimir Marko009d1662017-10-10 13:21:15 +0100336 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700337 heap_values_for_[instruction->GetBlock()->GetBlockId()];
338 HInstruction* heap_value = heap_values[idx];
339 if (heap_value == kDefaultHeapValue) {
340 HInstruction* constant = GetDefaultValue(instruction->GetType());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800341 removed_loads_.push_back(instruction);
342 substitute_instructions_for_loads_.push_back(constant);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700343 heap_values[idx] = constant;
344 return;
345 }
Mingyao Yang86974902017-03-01 14:03:51 -0800346 if (heap_value != kUnknownHeapValue) {
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +0000347 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
Mingyao Yang86974902017-03-01 14:03:51 -0800348 HInstruction* store = heap_value;
349 // This load must be from a singleton since it's from the same
350 // field/element that a "removed" store puts the value. That store
351 // must be to a singleton's field/element.
352 DCHECK(ref_info->IsSingleton());
353 // Get the real heap value of the store.
354 heap_value = heap_value->IsInstanceFieldSet() ? store->InputAt(1) : store->InputAt(2);
Mingyao Yang206070c2017-11-29 23:01:58 -0800355 // heap_value may already have a substitute.
356 heap_value = FindSubstitute(heap_value);
Mingyao Yang86974902017-03-01 14:03:51 -0800357 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800358 }
David Brazdil15693bf2015-12-16 10:30:45 +0000359 if (heap_value == kUnknownHeapValue) {
360 // Load isn't eliminated. Put the load as the value into the HeapLocation.
361 // This acts like GVN but with better aliasing analysis.
362 heap_values[idx] = instruction;
363 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100364 if (DataType::Kind(heap_value->GetType()) != DataType::Kind(instruction->GetType())) {
Nicolas Geoffray03971632016-03-17 10:44:24 +0000365 // The only situation where the same heap location has different type is when
Nicolas Geoffray65fef302016-05-04 14:00:12 +0100366 // we do an array get on an instruction that originates from the null constant
367 // (the null could be behind a field access, an array access, a null check or
368 // a bound type).
369 // In order to stay properly typed on primitive types, we do not eliminate
370 // the array gets.
Nicolas Geoffray03971632016-03-17 10:44:24 +0000371 if (kIsDebugBuild) {
372 DCHECK(heap_value->IsArrayGet()) << heap_value->DebugName();
373 DCHECK(instruction->IsArrayGet()) << instruction->DebugName();
Nicolas Geoffray03971632016-03-17 10:44:24 +0000374 }
375 return;
376 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800377 removed_loads_.push_back(instruction);
378 substitute_instructions_for_loads_.push_back(heap_value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700379 TryRemovingNullCheck(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700380 }
381 }
382
383 bool Equal(HInstruction* heap_value, HInstruction* value) {
384 if (heap_value == value) {
385 return true;
386 }
387 if (heap_value == kDefaultHeapValue && GetDefaultValue(value->GetType()) == value) {
388 return true;
389 }
390 return false;
391 }
392
393 void VisitSetLocation(HInstruction* instruction,
394 HInstruction* ref,
395 size_t offset,
396 HInstruction* index,
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100397 size_t vector_length,
Mingyao Yang8df69d42015-10-22 15:40:58 -0700398 int16_t declaring_class_def_index,
399 HInstruction* value) {
Mingyao Yang206070c2017-11-29 23:01:58 -0800400 // value may already have a substitute.
401 value = FindSubstitute(value);
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100402 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700403 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
404 size_t idx = heap_location_collector_.FindHeapLocationIndex(
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100405 ref_info, offset, index, vector_length, declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700406 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
Vladimir Marko009d1662017-10-10 13:21:15 +0100407 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700408 heap_values_for_[instruction->GetBlock()->GetBlockId()];
409 HInstruction* heap_value = heap_values[idx];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800410 bool same_value = false;
411 bool possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700412 if (Equal(heap_value, value)) {
413 // Store into the heap location with the same value.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800414 same_value = true;
Mingyao Yang0e3151b2017-10-30 11:19:57 -0700415 } else if (index != nullptr &&
416 heap_location_collector_.GetHeapLocation(idx)->HasAliasedLocations()) {
417 // For array element, don't eliminate stores if the location can be aliased
418 // (due to either ref or index aliasing).
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800419 } else if (ref_info->IsSingleton()) {
Mingyao Yang025c1a62017-10-30 11:19:57 -0700420 // Store into a field/element of a singleton. The value cannot be killed due to
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800421 // aliasing/invocation. It can be redundant since future loads can
422 // directly get the value set by this instruction. The value can still be killed due to
423 // merging or loop side effects. Stores whose values are killed due to merging/loop side
424 // effects later will be removed from possibly_removed_stores_ when that is detected.
425 // Stores whose values may be needed after method return or deoptimization
426 // are also removed from possibly_removed_stores_ when that is detected.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800427 possibly_redundant = true;
Mingyao Yang025c1a62017-10-30 11:19:57 -0700428 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
429 if (loop_info != nullptr) {
430 // instruction is a store in the loop so the loop must does write.
431 DCHECK(side_effects_.GetLoopEffects(loop_info->GetHeader()).DoesAnyWrite());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800432
Mingyao Yang025c1a62017-10-30 11:19:57 -0700433 if (loop_info->IsDefinedOutOfTheLoop(original_ref)) {
434 DCHECK(original_ref->GetBlock()->Dominates(loop_info->GetPreHeader()));
435 // Keep the store since its value may be needed at the loop header.
436 possibly_redundant = false;
437 } else {
438 // The singleton is created inside the loop. Value stored to it isn't needed at
439 // the loop header. This is true for outer loops also.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800440 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700441 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700442 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800443 if (same_value || possibly_redundant) {
444 possibly_removed_stores_.push_back(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700445 }
Mingyao Yange9d6e602015-10-23 17:08:42 -0700446
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800447 if (!same_value) {
448 if (possibly_redundant) {
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +0000449 DCHECK(instruction->IsInstanceFieldSet() || instruction->IsArraySet());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800450 // Put the store as the heap value. If the value is loaded from heap
451 // by a load later, this store isn't really redundant.
452 heap_values[idx] = instruction;
453 } else {
454 heap_values[idx] = value;
455 }
456 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700457 // This store may kill values in other heap locations due to aliasing.
458 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800459 if (i == idx) {
460 continue;
461 }
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +0000462 if (heap_values[i] == value) {
463 // Same value should be kept even if aliasing happens.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700464 continue;
465 }
466 if (heap_values[i] == kUnknownHeapValue) {
467 // Value is already unknown, no need for aliasing check.
468 continue;
469 }
470 if (heap_location_collector_.MayAlias(i, idx)) {
471 // Kill heap locations that may alias.
472 heap_values[i] = kUnknownHeapValue;
473 }
474 }
475 }
476
477 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
478 HInstruction* obj = instruction->InputAt(0);
479 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
480 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100481 VisitGetLocation(instruction,
482 obj,
483 offset,
484 nullptr,
485 HeapLocation::kScalar,
486 declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700487 }
488
489 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
490 HInstruction* obj = instruction->InputAt(0);
491 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
492 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
493 HInstruction* value = instruction->InputAt(1);
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100494 VisitSetLocation(instruction,
495 obj,
496 offset,
497 nullptr,
498 HeapLocation::kScalar,
499 declaring_class_def_index,
500 value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700501 }
502
503 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
504 HInstruction* cls = instruction->InputAt(0);
505 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
506 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100507 VisitGetLocation(instruction,
508 cls,
509 offset,
510 nullptr,
511 HeapLocation::kScalar,
512 declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700513 }
514
515 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
516 HInstruction* cls = instruction->InputAt(0);
517 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
518 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
519 HInstruction* value = instruction->InputAt(1);
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100520 VisitSetLocation(instruction,
521 cls,
522 offset,
523 nullptr,
524 HeapLocation::kScalar,
525 declaring_class_def_index,
526 value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700527 }
528
529 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
530 HInstruction* array = instruction->InputAt(0);
531 HInstruction* index = instruction->InputAt(1);
532 VisitGetLocation(instruction,
533 array,
534 HeapLocation::kInvalidFieldOffset,
535 index,
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100536 HeapLocation::kScalar,
Mingyao Yang8df69d42015-10-22 15:40:58 -0700537 HeapLocation::kDeclaringClassDefIndexForArrays);
538 }
539
540 void VisitArraySet(HArraySet* instruction) OVERRIDE {
541 HInstruction* array = instruction->InputAt(0);
542 HInstruction* index = instruction->InputAt(1);
543 HInstruction* value = instruction->InputAt(2);
544 VisitSetLocation(instruction,
545 array,
546 HeapLocation::kInvalidFieldOffset,
547 index,
xueliang.zhongb50b16a2017-09-19 17:43:29 +0100548 HeapLocation::kScalar,
Mingyao Yang8df69d42015-10-22 15:40:58 -0700549 HeapLocation::kDeclaringClassDefIndexForArrays,
550 value);
551 }
552
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800553 void VisitDeoptimize(HDeoptimize* instruction) {
Vladimir Marko009d1662017-10-10 13:21:15 +0100554 const ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800555 heap_values_for_[instruction->GetBlock()->GetBlockId()];
556 for (HInstruction* heap_value : heap_values) {
557 // Filter out fake instructions before checking instruction kind below.
558 if (heap_value == kUnknownHeapValue || heap_value == kDefaultHeapValue) {
559 continue;
560 }
561 // A store is kept as the heap value for possibly removed stores.
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +0000562 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800563 // Check whether the reference for a store is used by an environment local of
564 // HDeoptimize.
565 HInstruction* reference = heap_value->InputAt(0);
566 DCHECK(heap_location_collector_.FindReferenceInfoOf(reference)->IsSingleton());
567 for (const HUseListNode<HEnvironment*>& use : reference->GetEnvUses()) {
568 HEnvironment* user = use.GetUser();
569 if (user->GetHolder() == instruction) {
570 // The singleton for the store is visible at this deoptimization
571 // point. Need to keep the store so that the heap value is
572 // seen by the interpreter.
573 KeepIfIsStore(heap_value);
574 }
575 }
576 }
577 }
578 }
579
Mingyao Yang46721ef2017-10-05 14:45:17 -0700580 // Keep necessary stores before exiting a method via return/throw.
581 void HandleExit(HBasicBlock* block) {
582 const ScopedArenaVector<HInstruction*>& heap_values =
583 heap_values_for_[block->GetBlockId()];
584 for (size_t i = 0; i < heap_values.size(); i++) {
585 HInstruction* heap_value = heap_values[i];
586 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
587 if (!ref_info->IsSingletonAndRemovable()) {
588 KeepIfIsStore(heap_value);
589 }
590 }
591 }
592
593 void VisitReturn(HReturn* instruction) OVERRIDE {
594 HandleExit(instruction->GetBlock());
595 }
596
597 void VisitReturnVoid(HReturnVoid* return_void) OVERRIDE {
598 HandleExit(return_void->GetBlock());
599 }
600
601 void VisitThrow(HThrow* throw_instruction) OVERRIDE {
602 HandleExit(throw_instruction->GetBlock());
603 }
604
Mingyao Yang293f1c02017-11-08 15:22:17 -0800605 void HandleInvoke(HInstruction* instruction) {
606 SideEffects side_effects = instruction->GetSideEffects();
Vladimir Marko009d1662017-10-10 13:21:15 +0100607 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang293f1c02017-11-08 15:22:17 -0800608 heap_values_for_[instruction->GetBlock()->GetBlockId()];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700609 for (size_t i = 0; i < heap_values.size(); i++) {
610 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
611 if (ref_info->IsSingleton()) {
612 // Singleton references cannot be seen by the callee.
613 } else {
Mingyao Yang293f1c02017-11-08 15:22:17 -0800614 if (side_effects.DoesAnyRead()) {
615 KeepIfIsStore(heap_values[i]);
616 }
617 if (side_effects.DoesAnyWrite()) {
618 heap_values[i] = kUnknownHeapValue;
619 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700620 }
621 }
622 }
623
Mingyao Yangc62b7ec2017-10-25 16:42:15 -0700624 void VisitInvoke(HInvoke* invoke) OVERRIDE {
Orion Hodsonac141392017-01-13 11:53:47 +0000625 HandleInvoke(invoke);
626 }
627
Mingyao Yang8df69d42015-10-22 15:40:58 -0700628 void VisitClinitCheck(HClinitCheck* clinit) OVERRIDE {
629 HandleInvoke(clinit);
630 }
631
632 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* instruction) OVERRIDE {
633 // Conservatively treat it as an invocation.
634 HandleInvoke(instruction);
635 }
636
637 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* instruction) OVERRIDE {
638 // Conservatively treat it as an invocation.
639 HandleInvoke(instruction);
640 }
641
642 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* instruction) OVERRIDE {
643 // Conservatively treat it as an invocation.
644 HandleInvoke(instruction);
645 }
646
647 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* instruction) OVERRIDE {
648 // Conservatively treat it as an invocation.
649 HandleInvoke(instruction);
650 }
651
652 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
653 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_instance);
654 if (ref_info == nullptr) {
655 // new_instance isn't used for field accesses. No need to process it.
656 return;
657 }
Mingyao Yang025c1a62017-10-30 11:19:57 -0700658 if (ref_info->IsSingletonAndRemovable() && !new_instance->NeedsChecks()) {
659 DCHECK(!new_instance->IsFinalizable());
Mingyao Yang062157f2016-03-02 10:15:36 -0800660 singleton_new_instances_.push_back(new_instance);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700661 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100662 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang8df69d42015-10-22 15:40:58 -0700663 heap_values_for_[new_instance->GetBlock()->GetBlockId()];
664 for (size_t i = 0; i < heap_values.size(); i++) {
665 HInstruction* ref =
666 heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo()->GetReference();
667 size_t offset = heap_location_collector_.GetHeapLocation(i)->GetOffset();
668 if (ref == new_instance && offset >= mirror::kObjectHeaderSize) {
669 // Instance fields except the header fields are set to default heap values.
670 heap_values[i] = kDefaultHeapValue;
671 }
672 }
673 }
674
Mingyao Yang86974902017-03-01 14:03:51 -0800675 void VisitNewArray(HNewArray* new_array) OVERRIDE {
676 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_array);
677 if (ref_info == nullptr) {
678 // new_array isn't used for array accesses. No need to process it.
679 return;
680 }
681 if (ref_info->IsSingletonAndRemovable()) {
682 singleton_new_arrays_.push_back(new_array);
683 }
Vladimir Marko009d1662017-10-10 13:21:15 +0100684 ScopedArenaVector<HInstruction*>& heap_values =
Mingyao Yang86974902017-03-01 14:03:51 -0800685 heap_values_for_[new_array->GetBlock()->GetBlockId()];
686 for (size_t i = 0; i < heap_values.size(); i++) {
687 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
688 HInstruction* ref = location->GetReferenceInfo()->GetReference();
689 if (ref == new_array && location->GetIndex() != nullptr) {
690 // Array elements are set to default heap values.
691 heap_values[i] = kDefaultHeapValue;
692 }
693 }
694 }
695
Mingyao Yang8df69d42015-10-22 15:40:58 -0700696 const HeapLocationCollector& heap_location_collector_;
697 const SideEffectsAnalysis& side_effects_;
698
Vladimir Marko009d1662017-10-10 13:21:15 +0100699 // Use local allocator for allocating memory.
700 ScopedArenaAllocator allocator_;
701
Mingyao Yang8df69d42015-10-22 15:40:58 -0700702 // One array of heap values for each block.
Vladimir Marko009d1662017-10-10 13:21:15 +0100703 ScopedArenaVector<ScopedArenaVector<HInstruction*>> heap_values_for_;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700704
705 // We record the instructions that should be eliminated but may be
706 // used by heap locations. They'll be removed in the end.
Vladimir Marko009d1662017-10-10 13:21:15 +0100707 ScopedArenaVector<HInstruction*> removed_loads_;
708 ScopedArenaVector<HInstruction*> substitute_instructions_for_loads_;
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800709
710 // Stores in this list may be removed from the list later when it's
711 // found that the store cannot be eliminated.
Vladimir Marko009d1662017-10-10 13:21:15 +0100712 ScopedArenaVector<HInstruction*> possibly_removed_stores_;
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800713
Vladimir Marko009d1662017-10-10 13:21:15 +0100714 ScopedArenaVector<HInstruction*> singleton_new_instances_;
715 ScopedArenaVector<HInstruction*> singleton_new_arrays_;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700716
717 DISALLOW_COPY_AND_ASSIGN(LSEVisitor);
718};
719
720void LoadStoreElimination::Run() {
David Brazdil8993caf2015-12-07 10:04:40 +0000721 if (graph_->IsDebuggable() || graph_->HasTryCatch()) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700722 // Debugger may set heap values or trigger deoptimization of callers.
David Brazdil8993caf2015-12-07 10:04:40 +0000723 // Try/catch support not implemented yet.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700724 // Skip this optimization.
725 return;
726 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100727 const HeapLocationCollector& heap_location_collector = lsa_.GetHeapLocationCollector();
728 if (heap_location_collector.GetNumberOfHeapLocations() == 0) {
729 // No HeapLocation information from LSA, skip this optimization.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700730 return;
731 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100732
Nicolas Geoffray8c4ddb22017-11-13 11:49:53 +0000733 // TODO: analyze VecLoad/VecStore better.
734 if (graph_->HasSIMD()) {
735 return;
736 }
737
Igor Murashkin6ef45672017-08-08 13:59:55 -0700738 LSEVisitor lse_visitor(graph_, heap_location_collector, side_effects_, stats_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100739 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
740 lse_visitor.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700741 }
742 lse_visitor.RemoveInstructions();
743}
744
745} // namespace art