blob: bd14f2b142ca498425677dbe1b4629d92d0b384a [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
19#include "escape.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070020#include "load_store_analysis.h"
Mingyao Yang8df69d42015-10-22 15:40:58 -070021#include "side_effects_analysis.h"
22
23#include <iostream>
24
25namespace art {
26
Mingyao Yang8df69d42015-10-22 15:40:58 -070027// An unknown heap value. Loads with such a value in the heap location cannot be eliminated.
Mingyao Yangfb8464a2015-11-02 10:56:59 -080028// A heap location can be set to kUnknownHeapValue when:
29// - initially set a value.
30// - killed due to aliasing, merging, invocation, or loop side effects.
Mingyao Yang8df69d42015-10-22 15:40:58 -070031static HInstruction* const kUnknownHeapValue =
32 reinterpret_cast<HInstruction*>(static_cast<uintptr_t>(-1));
Mingyao Yangfb8464a2015-11-02 10:56:59 -080033
Mingyao Yang8df69d42015-10-22 15:40:58 -070034// Default heap value after an allocation.
Mingyao Yangfb8464a2015-11-02 10:56:59 -080035// A heap location can be set to that value right after an allocation.
Mingyao Yang8df69d42015-10-22 15:40:58 -070036static HInstruction* const kDefaultHeapValue =
37 reinterpret_cast<HInstruction*>(static_cast<uintptr_t>(-2));
38
39class LSEVisitor : public HGraphVisitor {
40 public:
41 LSEVisitor(HGraph* graph,
42 const HeapLocationCollector& heap_locations_collector,
Igor Murashkin6ef45672017-08-08 13:59:55 -070043 const SideEffectsAnalysis& side_effects,
44 OptimizingCompilerStats* stats)
45 : HGraphVisitor(graph, stats),
Mingyao Yang8df69d42015-10-22 15:40:58 -070046 heap_location_collector_(heap_locations_collector),
47 side_effects_(side_effects),
48 heap_values_for_(graph->GetBlocks().size(),
49 ArenaVector<HInstruction*>(heap_locations_collector.
xueliang.zhongc239a2b2017-04-27 15:31:37 +010050 GetNumberOfHeapLocations(),
Mingyao Yang8df69d42015-10-22 15:40:58 -070051 kUnknownHeapValue,
52 graph->GetArena()->Adapter(kArenaAllocLSE)),
53 graph->GetArena()->Adapter(kArenaAllocLSE)),
Mingyao Yangfb8464a2015-11-02 10:56:59 -080054 removed_loads_(graph->GetArena()->Adapter(kArenaAllocLSE)),
55 substitute_instructions_for_loads_(graph->GetArena()->Adapter(kArenaAllocLSE)),
56 possibly_removed_stores_(graph->GetArena()->Adapter(kArenaAllocLSE)),
Mingyao Yang86974902017-03-01 14:03:51 -080057 singleton_new_instances_(graph->GetArena()->Adapter(kArenaAllocLSE)),
58 singleton_new_arrays_(graph->GetArena()->Adapter(kArenaAllocLSE)) {
Mingyao Yang8df69d42015-10-22 15:40:58 -070059 }
60
61 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080062 // Populate the heap_values array for this block.
Mingyao Yang8df69d42015-10-22 15:40:58 -070063 // TODO: try to reuse the heap_values array from one predecessor if possible.
64 if (block->IsLoopHeader()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080065 HandleLoopSideEffects(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -070066 } else {
67 MergePredecessorValues(block);
68 }
69 HGraphVisitor::VisitBasicBlock(block);
70 }
71
72 // Remove recorded instructions that should be eliminated.
73 void RemoveInstructions() {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080074 size_t size = removed_loads_.size();
75 DCHECK_EQ(size, substitute_instructions_for_loads_.size());
Mingyao Yang8df69d42015-10-22 15:40:58 -070076 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080077 HInstruction* load = removed_loads_[i];
78 DCHECK(load != nullptr);
79 DCHECK(load->IsInstanceFieldGet() ||
80 load->IsStaticFieldGet() ||
81 load->IsArrayGet());
82 HInstruction* substitute = substitute_instructions_for_loads_[i];
83 DCHECK(substitute != nullptr);
84 // Keep tracing substitute till one that's not removed.
85 HInstruction* sub_sub = FindSubstitute(substitute);
86 while (sub_sub != substitute) {
87 substitute = sub_sub;
88 sub_sub = FindSubstitute(substitute);
Mingyao Yang8df69d42015-10-22 15:40:58 -070089 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -080090 load->ReplaceWith(substitute);
91 load->GetBlock()->RemoveInstruction(load);
Mingyao Yang8df69d42015-10-22 15:40:58 -070092 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -080093
94 // At this point, stores in possibly_removed_stores_ can be safely removed.
Mingyao Yang86974902017-03-01 14:03:51 -080095 for (HInstruction* store : possibly_removed_stores_) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080096 DCHECK(store->IsInstanceFieldSet() || store->IsStaticFieldSet() || store->IsArraySet());
97 store->GetBlock()->RemoveInstruction(store);
98 }
99
Igor Murashkind01745e2017-04-05 16:40:31 -0700100 // Eliminate singleton-classified instructions:
101 // * - Constructor fences (they never escape this thread).
102 // * - Allocations (if they are unused).
Mingyao Yang86974902017-03-01 14:03:51 -0800103 for (HInstruction* new_instance : singleton_new_instances_) {
Igor Murashkin6ef45672017-08-08 13:59:55 -0700104 size_t removed = HConstructorFence::RemoveConstructorFences(new_instance);
105 MaybeRecordStat(stats_,
106 MethodCompilationStat::kConstructorFenceRemovedLSE,
107 removed);
Igor Murashkind01745e2017-04-05 16:40:31 -0700108
Mingyao Yang062157f2016-03-02 10:15:36 -0800109 if (!new_instance->HasNonEnvironmentUses()) {
110 new_instance->RemoveEnvironmentUsers();
111 new_instance->GetBlock()->RemoveInstruction(new_instance);
112 }
113 }
Mingyao Yang86974902017-03-01 14:03:51 -0800114 for (HInstruction* new_array : singleton_new_arrays_) {
Igor Murashkin6ef45672017-08-08 13:59:55 -0700115 size_t removed = HConstructorFence::RemoveConstructorFences(new_array);
116 MaybeRecordStat(stats_,
117 MethodCompilationStat::kConstructorFenceRemovedLSE,
118 removed);
Igor Murashkind01745e2017-04-05 16:40:31 -0700119
Mingyao Yang86974902017-03-01 14:03:51 -0800120 if (!new_array->HasNonEnvironmentUses()) {
121 new_array->RemoveEnvironmentUsers();
122 new_array->GetBlock()->RemoveInstruction(new_array);
123 }
124 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700125 }
126
127 private:
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800128 // If heap_values[index] is an instance field store, need to keep the store.
129 // This is necessary if a heap value is killed due to merging, or loop side
130 // effects (which is essentially merging also), since a load later from the
131 // location won't be eliminated.
132 void KeepIfIsStore(HInstruction* heap_value) {
133 if (heap_value == kDefaultHeapValue ||
134 heap_value == kUnknownHeapValue ||
Mingyao Yang86974902017-03-01 14:03:51 -0800135 !(heap_value->IsInstanceFieldSet() || heap_value->IsArraySet())) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800136 return;
137 }
138 auto idx = std::find(possibly_removed_stores_.begin(),
139 possibly_removed_stores_.end(), heap_value);
140 if (idx != possibly_removed_stores_.end()) {
141 // Make sure the store is kept.
142 possibly_removed_stores_.erase(idx);
143 }
144 }
145
146 void HandleLoopSideEffects(HBasicBlock* block) {
147 DCHECK(block->IsLoopHeader());
148 int block_id = block->GetBlockId();
149 ArenaVector<HInstruction*>& heap_values = heap_values_for_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000150
151 // Don't eliminate loads in irreducible loops. This is safe for singletons, because
152 // they are always used by the non-eliminated loop-phi.
153 if (block->GetLoopInformation()->IsIrreducible()) {
154 if (kIsDebugBuild) {
155 for (size_t i = 0; i < heap_values.size(); i++) {
156 DCHECK_EQ(heap_values[i], kUnknownHeapValue);
157 }
158 }
159 return;
160 }
161
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800162 HBasicBlock* pre_header = block->GetLoopInformation()->GetPreHeader();
163 ArenaVector<HInstruction*>& pre_header_heap_values =
164 heap_values_for_[pre_header->GetBlockId()];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000165
Mingyao Yang803cbb92015-12-01 12:24:36 -0800166 // Inherit the values from pre-header.
167 for (size_t i = 0; i < heap_values.size(); i++) {
168 heap_values[i] = pre_header_heap_values[i];
169 }
170
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800171 // We do a single pass in reverse post order. For loops, use the side effects as a hint
172 // to see if the heap values should be killed.
173 if (side_effects_.GetLoopEffects(block).DoesAnyWrite()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800174 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800175 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
176 ReferenceInfo* ref_info = location->GetReferenceInfo();
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800177 if (ref_info->IsSingletonAndRemovable() &&
178 !location->IsValueKilledByLoopSideEffects()) {
179 // A removable singleton's field that's not stored into inside a loop is
180 // invariant throughout the loop. Nothing to do.
181 DCHECK(ref_info->IsSingletonAndRemovable());
182 } else {
183 // heap value is killed by loop side effects (stored into directly, or
184 // due to aliasing). Or the heap value may be needed after method return
185 // or deoptimization.
Mingyao Yang803cbb92015-12-01 12:24:36 -0800186 KeepIfIsStore(pre_header_heap_values[i]);
187 heap_values[i] = kUnknownHeapValue;
Mingyao Yang803cbb92015-12-01 12:24:36 -0800188 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800189 }
190 }
191 }
192
Mingyao Yang8df69d42015-10-22 15:40:58 -0700193 void MergePredecessorValues(HBasicBlock* block) {
194 const ArenaVector<HBasicBlock*>& predecessors = block->GetPredecessors();
195 if (predecessors.size() == 0) {
196 return;
197 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700198
Mingyao Yang8df69d42015-10-22 15:40:58 -0700199 ArenaVector<HInstruction*>& heap_values = heap_values_for_[block->GetBlockId()];
200 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700201 HInstruction* merged_value = nullptr;
202 // Whether merged_value is a result that's merged from all predecessors.
203 bool from_all_predecessors = true;
204 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
205 HInstruction* singleton_ref = nullptr;
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800206 if (ref_info->IsSingleton()) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700207 // We do more analysis of liveness when merging heap values for such
208 // cases since stores into such references may potentially be eliminated.
209 singleton_ref = ref_info->GetReference();
210 }
211
212 for (HBasicBlock* predecessor : predecessors) {
213 HInstruction* pred_value = heap_values_for_[predecessor->GetBlockId()][i];
214 if ((singleton_ref != nullptr) &&
215 !singleton_ref->GetBlock()->Dominates(predecessor)) {
216 // singleton_ref is not live in this predecessor. Skip this predecessor since
217 // it does not really have the location.
218 DCHECK_EQ(pred_value, kUnknownHeapValue);
219 from_all_predecessors = false;
220 continue;
221 }
222 if (merged_value == nullptr) {
223 // First seen heap value.
224 merged_value = pred_value;
225 } else if (pred_value != merged_value) {
226 // There are conflicting values.
227 merged_value = kUnknownHeapValue;
228 break;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700229 }
230 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800231
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800232 if (merged_value == kUnknownHeapValue || ref_info->IsSingletonAndNonRemovable()) {
233 // There are conflicting heap values from different predecessors,
234 // or the heap value may be needed after method return or deoptimization.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800235 // Keep the last store in each predecessor since future loads cannot be eliminated.
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700236 for (HBasicBlock* predecessor : predecessors) {
237 ArenaVector<HInstruction*>& pred_values = heap_values_for_[predecessor->GetBlockId()];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800238 KeepIfIsStore(pred_values[i]);
239 }
240 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700241
242 if ((merged_value == nullptr) || !from_all_predecessors) {
243 DCHECK(singleton_ref != nullptr);
244 DCHECK((singleton_ref->GetBlock() == block) ||
245 !singleton_ref->GetBlock()->Dominates(block));
246 // singleton_ref is not defined before block or defined only in some of its
247 // predecessors, so block doesn't really have the location at its entry.
248 heap_values[i] = kUnknownHeapValue;
249 } else {
250 heap_values[i] = merged_value;
251 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700252 }
253 }
254
255 // `instruction` is being removed. Try to see if the null check on it
256 // can be removed. This can happen if the same value is set in two branches
257 // but not in dominators. Such as:
258 // int[] a = foo();
259 // if () {
260 // a[0] = 2;
261 // } else {
262 // a[0] = 2;
263 // }
264 // // a[0] can now be replaced with constant 2, and the null check on it can be removed.
265 void TryRemovingNullCheck(HInstruction* instruction) {
266 HInstruction* prev = instruction->GetPrevious();
267 if ((prev != nullptr) && prev->IsNullCheck() && (prev == instruction->InputAt(0))) {
268 // Previous instruction is a null check for this instruction. Remove the null check.
269 prev->ReplaceWith(prev->InputAt(0));
270 prev->GetBlock()->RemoveInstruction(prev);
271 }
272 }
273
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100274 HInstruction* GetDefaultValue(DataType::Type type) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700275 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100276 case DataType::Type::kReference:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700277 return GetGraph()->GetNullConstant();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100278 case DataType::Type::kBool:
279 case DataType::Type::kInt8:
280 case DataType::Type::kUint16:
281 case DataType::Type::kInt16:
282 case DataType::Type::kInt32:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700283 return GetGraph()->GetIntConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100284 case DataType::Type::kInt64:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700285 return GetGraph()->GetLongConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100286 case DataType::Type::kFloat32:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700287 return GetGraph()->GetFloatConstant(0);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100288 case DataType::Type::kFloat64:
Mingyao Yang8df69d42015-10-22 15:40:58 -0700289 return GetGraph()->GetDoubleConstant(0);
290 default:
291 UNREACHABLE();
292 }
293 }
294
295 void VisitGetLocation(HInstruction* instruction,
296 HInstruction* ref,
297 size_t offset,
298 HInstruction* index,
299 int16_t declaring_class_def_index) {
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100300 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700301 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
302 size_t idx = heap_location_collector_.FindHeapLocationIndex(
303 ref_info, offset, index, declaring_class_def_index);
304 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
305 ArenaVector<HInstruction*>& heap_values =
306 heap_values_for_[instruction->GetBlock()->GetBlockId()];
307 HInstruction* heap_value = heap_values[idx];
308 if (heap_value == kDefaultHeapValue) {
309 HInstruction* constant = GetDefaultValue(instruction->GetType());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800310 removed_loads_.push_back(instruction);
311 substitute_instructions_for_loads_.push_back(constant);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700312 heap_values[idx] = constant;
313 return;
314 }
Mingyao Yang86974902017-03-01 14:03:51 -0800315 if (heap_value != kUnknownHeapValue) {
316 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
317 HInstruction* store = heap_value;
318 // This load must be from a singleton since it's from the same
319 // field/element that a "removed" store puts the value. That store
320 // must be to a singleton's field/element.
321 DCHECK(ref_info->IsSingleton());
322 // Get the real heap value of the store.
323 heap_value = heap_value->IsInstanceFieldSet() ? store->InputAt(1) : store->InputAt(2);
324 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800325 }
David Brazdil15693bf2015-12-16 10:30:45 +0000326 if (heap_value == kUnknownHeapValue) {
327 // Load isn't eliminated. Put the load as the value into the HeapLocation.
328 // This acts like GVN but with better aliasing analysis.
329 heap_values[idx] = instruction;
330 } else {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100331 if (DataType::Kind(heap_value->GetType()) != DataType::Kind(instruction->GetType())) {
Nicolas Geoffray03971632016-03-17 10:44:24 +0000332 // The only situation where the same heap location has different type is when
Nicolas Geoffray65fef302016-05-04 14:00:12 +0100333 // we do an array get on an instruction that originates from the null constant
334 // (the null could be behind a field access, an array access, a null check or
335 // a bound type).
336 // In order to stay properly typed on primitive types, we do not eliminate
337 // the array gets.
Nicolas Geoffray03971632016-03-17 10:44:24 +0000338 if (kIsDebugBuild) {
339 DCHECK(heap_value->IsArrayGet()) << heap_value->DebugName();
340 DCHECK(instruction->IsArrayGet()) << instruction->DebugName();
Nicolas Geoffray03971632016-03-17 10:44:24 +0000341 }
342 return;
343 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800344 removed_loads_.push_back(instruction);
345 substitute_instructions_for_loads_.push_back(heap_value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700346 TryRemovingNullCheck(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700347 }
348 }
349
350 bool Equal(HInstruction* heap_value, HInstruction* value) {
351 if (heap_value == value) {
352 return true;
353 }
354 if (heap_value == kDefaultHeapValue && GetDefaultValue(value->GetType()) == value) {
355 return true;
356 }
357 return false;
358 }
359
360 void VisitSetLocation(HInstruction* instruction,
361 HInstruction* ref,
362 size_t offset,
363 HInstruction* index,
364 int16_t declaring_class_def_index,
365 HInstruction* value) {
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100366 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700367 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
368 size_t idx = heap_location_collector_.FindHeapLocationIndex(
369 ref_info, offset, index, declaring_class_def_index);
370 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
371 ArenaVector<HInstruction*>& heap_values =
372 heap_values_for_[instruction->GetBlock()->GetBlockId()];
373 HInstruction* heap_value = heap_values[idx];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800374 bool same_value = false;
375 bool possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700376 if (Equal(heap_value, value)) {
377 // Store into the heap location with the same value.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800378 same_value = true;
Mingyao Yang86974902017-03-01 14:03:51 -0800379 } else if (index != nullptr && ref_info->HasIndexAliasing()) {
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800380 // For array element, don't eliminate stores if the index can be aliased.
381 } else if (ref_info->IsSingleton()) {
382 // Store into a field of a singleton. The value cannot be killed due to
383 // aliasing/invocation. It can be redundant since future loads can
384 // directly get the value set by this instruction. The value can still be killed due to
385 // merging or loop side effects. Stores whose values are killed due to merging/loop side
386 // effects later will be removed from possibly_removed_stores_ when that is detected.
387 // Stores whose values may be needed after method return or deoptimization
388 // are also removed from possibly_removed_stores_ when that is detected.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800389 possibly_redundant = true;
390 HNewInstance* new_instance = ref_info->GetReference()->AsNewInstance();
Mingyao Yang86974902017-03-01 14:03:51 -0800391 if (new_instance != nullptr && new_instance->IsFinalizable()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800392 // Finalizable objects escape globally. Need to keep the store.
393 possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700394 } else {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800395 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
396 if (loop_info != nullptr) {
397 // instruction is a store in the loop so the loop must does write.
398 DCHECK(side_effects_.GetLoopEffects(loop_info->GetHeader()).DoesAnyWrite());
399
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800400 if (loop_info->IsDefinedOutOfTheLoop(original_ref)) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800401 DCHECK(original_ref->GetBlock()->Dominates(loop_info->GetPreHeader()));
402 // Keep the store since its value may be needed at the loop header.
403 possibly_redundant = false;
404 } else {
405 // The singleton is created inside the loop. Value stored to it isn't needed at
406 // the loop header. This is true for outer loops also.
407 }
408 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700409 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700410 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800411 if (same_value || possibly_redundant) {
412 possibly_removed_stores_.push_back(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700413 }
Mingyao Yange9d6e602015-10-23 17:08:42 -0700414
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800415 if (!same_value) {
416 if (possibly_redundant) {
Mingyao Yang86974902017-03-01 14:03:51 -0800417 DCHECK(instruction->IsInstanceFieldSet() || instruction->IsArraySet());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800418 // Put the store as the heap value. If the value is loaded from heap
419 // by a load later, this store isn't really redundant.
420 heap_values[idx] = instruction;
421 } else {
422 heap_values[idx] = value;
423 }
424 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700425 // This store may kill values in other heap locations due to aliasing.
426 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800427 if (i == idx) {
428 continue;
429 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700430 if (heap_values[i] == value) {
431 // Same value should be kept even if aliasing happens.
432 continue;
433 }
434 if (heap_values[i] == kUnknownHeapValue) {
435 // Value is already unknown, no need for aliasing check.
436 continue;
437 }
438 if (heap_location_collector_.MayAlias(i, idx)) {
439 // Kill heap locations that may alias.
440 heap_values[i] = kUnknownHeapValue;
441 }
442 }
443 }
444
445 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
446 HInstruction* obj = instruction->InputAt(0);
447 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
448 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
449 VisitGetLocation(instruction, obj, offset, nullptr, declaring_class_def_index);
450 }
451
452 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
453 HInstruction* obj = instruction->InputAt(0);
454 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
455 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
456 HInstruction* value = instruction->InputAt(1);
457 VisitSetLocation(instruction, obj, offset, nullptr, declaring_class_def_index, value);
458 }
459
460 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
461 HInstruction* cls = instruction->InputAt(0);
462 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
463 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
464 VisitGetLocation(instruction, cls, offset, nullptr, declaring_class_def_index);
465 }
466
467 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
468 HInstruction* cls = instruction->InputAt(0);
469 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
470 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
471 HInstruction* value = instruction->InputAt(1);
472 VisitSetLocation(instruction, cls, offset, nullptr, declaring_class_def_index, value);
473 }
474
475 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
476 HInstruction* array = instruction->InputAt(0);
477 HInstruction* index = instruction->InputAt(1);
478 VisitGetLocation(instruction,
479 array,
480 HeapLocation::kInvalidFieldOffset,
481 index,
482 HeapLocation::kDeclaringClassDefIndexForArrays);
483 }
484
485 void VisitArraySet(HArraySet* instruction) OVERRIDE {
486 HInstruction* array = instruction->InputAt(0);
487 HInstruction* index = instruction->InputAt(1);
488 HInstruction* value = instruction->InputAt(2);
489 VisitSetLocation(instruction,
490 array,
491 HeapLocation::kInvalidFieldOffset,
492 index,
493 HeapLocation::kDeclaringClassDefIndexForArrays,
494 value);
495 }
496
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800497 void VisitDeoptimize(HDeoptimize* instruction) {
498 const ArenaVector<HInstruction*>& heap_values =
499 heap_values_for_[instruction->GetBlock()->GetBlockId()];
500 for (HInstruction* heap_value : heap_values) {
501 // Filter out fake instructions before checking instruction kind below.
502 if (heap_value == kUnknownHeapValue || heap_value == kDefaultHeapValue) {
503 continue;
504 }
505 // A store is kept as the heap value for possibly removed stores.
506 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
507 // Check whether the reference for a store is used by an environment local of
508 // HDeoptimize.
509 HInstruction* reference = heap_value->InputAt(0);
510 DCHECK(heap_location_collector_.FindReferenceInfoOf(reference)->IsSingleton());
511 for (const HUseListNode<HEnvironment*>& use : reference->GetEnvUses()) {
512 HEnvironment* user = use.GetUser();
513 if (user->GetHolder() == instruction) {
514 // The singleton for the store is visible at this deoptimization
515 // point. Need to keep the store so that the heap value is
516 // seen by the interpreter.
517 KeepIfIsStore(heap_value);
518 }
519 }
520 }
521 }
522 }
523
Mingyao Yang8df69d42015-10-22 15:40:58 -0700524 void HandleInvoke(HInstruction* invoke) {
525 ArenaVector<HInstruction*>& heap_values =
526 heap_values_for_[invoke->GetBlock()->GetBlockId()];
527 for (size_t i = 0; i < heap_values.size(); i++) {
528 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
529 if (ref_info->IsSingleton()) {
530 // Singleton references cannot be seen by the callee.
531 } else {
532 heap_values[i] = kUnknownHeapValue;
533 }
534 }
535 }
536
537 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) OVERRIDE {
538 HandleInvoke(invoke);
539 }
540
541 void VisitInvokeVirtual(HInvokeVirtual* invoke) OVERRIDE {
542 HandleInvoke(invoke);
543 }
544
545 void VisitInvokeInterface(HInvokeInterface* invoke) OVERRIDE {
546 HandleInvoke(invoke);
547 }
548
549 void VisitInvokeUnresolved(HInvokeUnresolved* invoke) OVERRIDE {
550 HandleInvoke(invoke);
551 }
552
Orion Hodsonac141392017-01-13 11:53:47 +0000553 void VisitInvokePolymorphic(HInvokePolymorphic* invoke) OVERRIDE {
554 HandleInvoke(invoke);
555 }
556
Mingyao Yang8df69d42015-10-22 15:40:58 -0700557 void VisitClinitCheck(HClinitCheck* clinit) OVERRIDE {
558 HandleInvoke(clinit);
559 }
560
561 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* instruction) OVERRIDE {
562 // Conservatively treat it as an invocation.
563 HandleInvoke(instruction);
564 }
565
566 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* instruction) OVERRIDE {
567 // Conservatively treat it as an invocation.
568 HandleInvoke(instruction);
569 }
570
571 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* instruction) OVERRIDE {
572 // Conservatively treat it as an invocation.
573 HandleInvoke(instruction);
574 }
575
576 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* instruction) OVERRIDE {
577 // Conservatively treat it as an invocation.
578 HandleInvoke(instruction);
579 }
580
581 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
582 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_instance);
583 if (ref_info == nullptr) {
584 // new_instance isn't used for field accesses. No need to process it.
585 return;
586 }
Aart Bik71bf7b42016-11-16 10:17:46 -0800587 if (ref_info->IsSingletonAndRemovable() &&
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800588 !new_instance->IsFinalizable() &&
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000589 !new_instance->NeedsChecks()) {
Mingyao Yang062157f2016-03-02 10:15:36 -0800590 singleton_new_instances_.push_back(new_instance);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700591 }
592 ArenaVector<HInstruction*>& heap_values =
593 heap_values_for_[new_instance->GetBlock()->GetBlockId()];
594 for (size_t i = 0; i < heap_values.size(); i++) {
595 HInstruction* ref =
596 heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo()->GetReference();
597 size_t offset = heap_location_collector_.GetHeapLocation(i)->GetOffset();
598 if (ref == new_instance && offset >= mirror::kObjectHeaderSize) {
599 // Instance fields except the header fields are set to default heap values.
600 heap_values[i] = kDefaultHeapValue;
601 }
602 }
603 }
604
Mingyao Yang86974902017-03-01 14:03:51 -0800605 void VisitNewArray(HNewArray* new_array) OVERRIDE {
606 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_array);
607 if (ref_info == nullptr) {
608 // new_array isn't used for array accesses. No need to process it.
609 return;
610 }
611 if (ref_info->IsSingletonAndRemovable()) {
612 singleton_new_arrays_.push_back(new_array);
613 }
614 ArenaVector<HInstruction*>& heap_values =
615 heap_values_for_[new_array->GetBlock()->GetBlockId()];
616 for (size_t i = 0; i < heap_values.size(); i++) {
617 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
618 HInstruction* ref = location->GetReferenceInfo()->GetReference();
619 if (ref == new_array && location->GetIndex() != nullptr) {
620 // Array elements are set to default heap values.
621 heap_values[i] = kDefaultHeapValue;
622 }
623 }
624 }
625
Mingyao Yang8df69d42015-10-22 15:40:58 -0700626 // Find an instruction's substitute if it should be removed.
627 // Return the same instruction if it should not be removed.
628 HInstruction* FindSubstitute(HInstruction* instruction) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800629 size_t size = removed_loads_.size();
Mingyao Yang8df69d42015-10-22 15:40:58 -0700630 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800631 if (removed_loads_[i] == instruction) {
632 return substitute_instructions_for_loads_[i];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700633 }
634 }
635 return instruction;
636 }
637
638 const HeapLocationCollector& heap_location_collector_;
639 const SideEffectsAnalysis& side_effects_;
640
641 // One array of heap values for each block.
642 ArenaVector<ArenaVector<HInstruction*>> heap_values_for_;
643
644 // We record the instructions that should be eliminated but may be
645 // used by heap locations. They'll be removed in the end.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800646 ArenaVector<HInstruction*> removed_loads_;
647 ArenaVector<HInstruction*> substitute_instructions_for_loads_;
648
649 // Stores in this list may be removed from the list later when it's
650 // found that the store cannot be eliminated.
651 ArenaVector<HInstruction*> possibly_removed_stores_;
652
Mingyao Yang8df69d42015-10-22 15:40:58 -0700653 ArenaVector<HInstruction*> singleton_new_instances_;
Mingyao Yang86974902017-03-01 14:03:51 -0800654 ArenaVector<HInstruction*> singleton_new_arrays_;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700655
656 DISALLOW_COPY_AND_ASSIGN(LSEVisitor);
657};
658
659void LoadStoreElimination::Run() {
David Brazdil8993caf2015-12-07 10:04:40 +0000660 if (graph_->IsDebuggable() || graph_->HasTryCatch()) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700661 // Debugger may set heap values or trigger deoptimization of callers.
David Brazdil8993caf2015-12-07 10:04:40 +0000662 // Try/catch support not implemented yet.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700663 // Skip this optimization.
664 return;
665 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100666 const HeapLocationCollector& heap_location_collector = lsa_.GetHeapLocationCollector();
667 if (heap_location_collector.GetNumberOfHeapLocations() == 0) {
668 // No HeapLocation information from LSA, skip this optimization.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700669 return;
670 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100671
Aart Bikd30f2052017-09-12 13:07:00 -0700672 // TODO: analyze VecLoad/VecStore better.
673 if (graph_->HasSIMD()) {
674 return;
675 }
676
Igor Murashkin6ef45672017-08-08 13:59:55 -0700677 LSEVisitor lse_visitor(graph_, heap_location_collector, side_effects_, stats_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100678 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
679 lse_visitor.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700680 }
681 lse_visitor.RemoveInstructions();
682}
683
684} // namespace art