blob: 8a9acf108c738f6bf785ccecaba06226d2be407d [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
274 HInstruction* GetDefaultValue(Primitive::Type type) {
275 switch (type) {
276 case Primitive::kPrimNot:
277 return GetGraph()->GetNullConstant();
278 case Primitive::kPrimBoolean:
279 case Primitive::kPrimByte:
280 case Primitive::kPrimChar:
281 case Primitive::kPrimShort:
282 case Primitive::kPrimInt:
283 return GetGraph()->GetIntConstant(0);
284 case Primitive::kPrimLong:
285 return GetGraph()->GetLongConstant(0);
286 case Primitive::kPrimFloat:
287 return GetGraph()->GetFloatConstant(0);
288 case Primitive::kPrimDouble:
289 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 {
Nicolas Geoffray03971632016-03-17 10:44:24 +0000331 if (Primitive::PrimitiveKind(heap_value->GetType())
332 != Primitive::PrimitiveKind(instruction->GetType())) {
333 // The only situation where the same heap location has different type is when
Nicolas Geoffray65fef302016-05-04 14:00:12 +0100334 // we do an array get on an instruction that originates from the null constant
335 // (the null could be behind a field access, an array access, a null check or
336 // a bound type).
337 // In order to stay properly typed on primitive types, we do not eliminate
338 // the array gets.
Nicolas Geoffray03971632016-03-17 10:44:24 +0000339 if (kIsDebugBuild) {
340 DCHECK(heap_value->IsArrayGet()) << heap_value->DebugName();
341 DCHECK(instruction->IsArrayGet()) << instruction->DebugName();
Nicolas Geoffray03971632016-03-17 10:44:24 +0000342 }
343 return;
344 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800345 removed_loads_.push_back(instruction);
346 substitute_instructions_for_loads_.push_back(heap_value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700347 TryRemovingNullCheck(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700348 }
349 }
350
351 bool Equal(HInstruction* heap_value, HInstruction* value) {
352 if (heap_value == value) {
353 return true;
354 }
355 if (heap_value == kDefaultHeapValue && GetDefaultValue(value->GetType()) == value) {
356 return true;
357 }
358 return false;
359 }
360
361 void VisitSetLocation(HInstruction* instruction,
362 HInstruction* ref,
363 size_t offset,
364 HInstruction* index,
365 int16_t declaring_class_def_index,
366 HInstruction* value) {
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100367 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700368 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
369 size_t idx = heap_location_collector_.FindHeapLocationIndex(
370 ref_info, offset, index, declaring_class_def_index);
371 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
372 ArenaVector<HInstruction*>& heap_values =
373 heap_values_for_[instruction->GetBlock()->GetBlockId()];
374 HInstruction* heap_value = heap_values[idx];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800375 bool same_value = false;
376 bool possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700377 if (Equal(heap_value, value)) {
378 // Store into the heap location with the same value.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800379 same_value = true;
Mingyao Yang86974902017-03-01 14:03:51 -0800380 } else if (index != nullptr && ref_info->HasIndexAliasing()) {
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800381 // For array element, don't eliminate stores if the index can be aliased.
382 } else if (ref_info->IsSingleton()) {
383 // Store into a field of a singleton. The value cannot be killed due to
384 // aliasing/invocation. It can be redundant since future loads can
385 // directly get the value set by this instruction. The value can still be killed due to
386 // merging or loop side effects. Stores whose values are killed due to merging/loop side
387 // effects later will be removed from possibly_removed_stores_ when that is detected.
388 // Stores whose values may be needed after method return or deoptimization
389 // are also removed from possibly_removed_stores_ when that is detected.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800390 possibly_redundant = true;
391 HNewInstance* new_instance = ref_info->GetReference()->AsNewInstance();
Mingyao Yang86974902017-03-01 14:03:51 -0800392 if (new_instance != nullptr && new_instance->IsFinalizable()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800393 // Finalizable objects escape globally. Need to keep the store.
394 possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700395 } else {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800396 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
397 if (loop_info != nullptr) {
398 // instruction is a store in the loop so the loop must does write.
399 DCHECK(side_effects_.GetLoopEffects(loop_info->GetHeader()).DoesAnyWrite());
400
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800401 if (loop_info->IsDefinedOutOfTheLoop(original_ref)) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800402 DCHECK(original_ref->GetBlock()->Dominates(loop_info->GetPreHeader()));
403 // Keep the store since its value may be needed at the loop header.
404 possibly_redundant = false;
405 } else {
406 // The singleton is created inside the loop. Value stored to it isn't needed at
407 // the loop header. This is true for outer loops also.
408 }
409 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700410 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700411 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800412 if (same_value || possibly_redundant) {
413 possibly_removed_stores_.push_back(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700414 }
Mingyao Yange9d6e602015-10-23 17:08:42 -0700415
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800416 if (!same_value) {
417 if (possibly_redundant) {
Mingyao Yang86974902017-03-01 14:03:51 -0800418 DCHECK(instruction->IsInstanceFieldSet() || instruction->IsArraySet());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800419 // Put the store as the heap value. If the value is loaded from heap
420 // by a load later, this store isn't really redundant.
421 heap_values[idx] = instruction;
422 } else {
423 heap_values[idx] = value;
424 }
425 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700426 // This store may kill values in other heap locations due to aliasing.
427 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800428 if (i == idx) {
429 continue;
430 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700431 if (heap_values[i] == value) {
432 // Same value should be kept even if aliasing happens.
433 continue;
434 }
435 if (heap_values[i] == kUnknownHeapValue) {
436 // Value is already unknown, no need for aliasing check.
437 continue;
438 }
439 if (heap_location_collector_.MayAlias(i, idx)) {
440 // Kill heap locations that may alias.
441 heap_values[i] = kUnknownHeapValue;
442 }
443 }
444 }
445
446 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
447 HInstruction* obj = instruction->InputAt(0);
448 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
449 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
450 VisitGetLocation(instruction, obj, offset, nullptr, declaring_class_def_index);
451 }
452
453 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
454 HInstruction* obj = instruction->InputAt(0);
455 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
456 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
457 HInstruction* value = instruction->InputAt(1);
458 VisitSetLocation(instruction, obj, offset, nullptr, declaring_class_def_index, value);
459 }
460
461 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
462 HInstruction* cls = instruction->InputAt(0);
463 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
464 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
465 VisitGetLocation(instruction, cls, offset, nullptr, declaring_class_def_index);
466 }
467
468 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
469 HInstruction* cls = instruction->InputAt(0);
470 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
471 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
472 HInstruction* value = instruction->InputAt(1);
473 VisitSetLocation(instruction, cls, offset, nullptr, declaring_class_def_index, value);
474 }
475
476 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
477 HInstruction* array = instruction->InputAt(0);
478 HInstruction* index = instruction->InputAt(1);
479 VisitGetLocation(instruction,
480 array,
481 HeapLocation::kInvalidFieldOffset,
482 index,
483 HeapLocation::kDeclaringClassDefIndexForArrays);
484 }
485
486 void VisitArraySet(HArraySet* instruction) OVERRIDE {
487 HInstruction* array = instruction->InputAt(0);
488 HInstruction* index = instruction->InputAt(1);
489 HInstruction* value = instruction->InputAt(2);
490 VisitSetLocation(instruction,
491 array,
492 HeapLocation::kInvalidFieldOffset,
493 index,
494 HeapLocation::kDeclaringClassDefIndexForArrays,
495 value);
496 }
497
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800498 void VisitDeoptimize(HDeoptimize* instruction) {
499 const ArenaVector<HInstruction*>& heap_values =
500 heap_values_for_[instruction->GetBlock()->GetBlockId()];
501 for (HInstruction* heap_value : heap_values) {
502 // Filter out fake instructions before checking instruction kind below.
503 if (heap_value == kUnknownHeapValue || heap_value == kDefaultHeapValue) {
504 continue;
505 }
506 // A store is kept as the heap value for possibly removed stores.
507 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
508 // Check whether the reference for a store is used by an environment local of
509 // HDeoptimize.
510 HInstruction* reference = heap_value->InputAt(0);
511 DCHECK(heap_location_collector_.FindReferenceInfoOf(reference)->IsSingleton());
512 for (const HUseListNode<HEnvironment*>& use : reference->GetEnvUses()) {
513 HEnvironment* user = use.GetUser();
514 if (user->GetHolder() == instruction) {
515 // The singleton for the store is visible at this deoptimization
516 // point. Need to keep the store so that the heap value is
517 // seen by the interpreter.
518 KeepIfIsStore(heap_value);
519 }
520 }
521 }
522 }
523 }
524
Mingyao Yang8df69d42015-10-22 15:40:58 -0700525 void HandleInvoke(HInstruction* invoke) {
526 ArenaVector<HInstruction*>& heap_values =
527 heap_values_for_[invoke->GetBlock()->GetBlockId()];
528 for (size_t i = 0; i < heap_values.size(); i++) {
529 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
530 if (ref_info->IsSingleton()) {
531 // Singleton references cannot be seen by the callee.
532 } else {
533 heap_values[i] = kUnknownHeapValue;
534 }
535 }
536 }
537
538 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) OVERRIDE {
539 HandleInvoke(invoke);
540 }
541
542 void VisitInvokeVirtual(HInvokeVirtual* invoke) OVERRIDE {
543 HandleInvoke(invoke);
544 }
545
546 void VisitInvokeInterface(HInvokeInterface* invoke) OVERRIDE {
547 HandleInvoke(invoke);
548 }
549
550 void VisitInvokeUnresolved(HInvokeUnresolved* invoke) OVERRIDE {
551 HandleInvoke(invoke);
552 }
553
Orion Hodsonac141392017-01-13 11:53:47 +0000554 void VisitInvokePolymorphic(HInvokePolymorphic* invoke) OVERRIDE {
555 HandleInvoke(invoke);
556 }
557
Mingyao Yang8df69d42015-10-22 15:40:58 -0700558 void VisitClinitCheck(HClinitCheck* clinit) OVERRIDE {
559 HandleInvoke(clinit);
560 }
561
562 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* instruction) OVERRIDE {
563 // Conservatively treat it as an invocation.
564 HandleInvoke(instruction);
565 }
566
567 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* instruction) OVERRIDE {
568 // Conservatively treat it as an invocation.
569 HandleInvoke(instruction);
570 }
571
572 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* instruction) OVERRIDE {
573 // Conservatively treat it as an invocation.
574 HandleInvoke(instruction);
575 }
576
577 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* instruction) OVERRIDE {
578 // Conservatively treat it as an invocation.
579 HandleInvoke(instruction);
580 }
581
582 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
583 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_instance);
584 if (ref_info == nullptr) {
585 // new_instance isn't used for field accesses. No need to process it.
586 return;
587 }
Aart Bik71bf7b42016-11-16 10:17:46 -0800588 if (ref_info->IsSingletonAndRemovable() &&
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800589 !new_instance->IsFinalizable() &&
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000590 !new_instance->NeedsChecks()) {
Mingyao Yang062157f2016-03-02 10:15:36 -0800591 singleton_new_instances_.push_back(new_instance);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700592 }
593 ArenaVector<HInstruction*>& heap_values =
594 heap_values_for_[new_instance->GetBlock()->GetBlockId()];
595 for (size_t i = 0; i < heap_values.size(); i++) {
596 HInstruction* ref =
597 heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo()->GetReference();
598 size_t offset = heap_location_collector_.GetHeapLocation(i)->GetOffset();
599 if (ref == new_instance && offset >= mirror::kObjectHeaderSize) {
600 // Instance fields except the header fields are set to default heap values.
601 heap_values[i] = kDefaultHeapValue;
602 }
603 }
604 }
605
Mingyao Yang86974902017-03-01 14:03:51 -0800606 void VisitNewArray(HNewArray* new_array) OVERRIDE {
607 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_array);
608 if (ref_info == nullptr) {
609 // new_array isn't used for array accesses. No need to process it.
610 return;
611 }
612 if (ref_info->IsSingletonAndRemovable()) {
613 singleton_new_arrays_.push_back(new_array);
614 }
615 ArenaVector<HInstruction*>& heap_values =
616 heap_values_for_[new_array->GetBlock()->GetBlockId()];
617 for (size_t i = 0; i < heap_values.size(); i++) {
618 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
619 HInstruction* ref = location->GetReferenceInfo()->GetReference();
620 if (ref == new_array && location->GetIndex() != nullptr) {
621 // Array elements are set to default heap values.
622 heap_values[i] = kDefaultHeapValue;
623 }
624 }
625 }
626
Mingyao Yang8df69d42015-10-22 15:40:58 -0700627 // Find an instruction's substitute if it should be removed.
628 // Return the same instruction if it should not be removed.
629 HInstruction* FindSubstitute(HInstruction* instruction) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800630 size_t size = removed_loads_.size();
Mingyao Yang8df69d42015-10-22 15:40:58 -0700631 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800632 if (removed_loads_[i] == instruction) {
633 return substitute_instructions_for_loads_[i];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700634 }
635 }
636 return instruction;
637 }
638
639 const HeapLocationCollector& heap_location_collector_;
640 const SideEffectsAnalysis& side_effects_;
641
642 // One array of heap values for each block.
643 ArenaVector<ArenaVector<HInstruction*>> heap_values_for_;
644
645 // We record the instructions that should be eliminated but may be
646 // used by heap locations. They'll be removed in the end.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800647 ArenaVector<HInstruction*> removed_loads_;
648 ArenaVector<HInstruction*> substitute_instructions_for_loads_;
649
650 // Stores in this list may be removed from the list later when it's
651 // found that the store cannot be eliminated.
652 ArenaVector<HInstruction*> possibly_removed_stores_;
653
Mingyao Yang8df69d42015-10-22 15:40:58 -0700654 ArenaVector<HInstruction*> singleton_new_instances_;
Mingyao Yang86974902017-03-01 14:03:51 -0800655 ArenaVector<HInstruction*> singleton_new_arrays_;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700656
657 DISALLOW_COPY_AND_ASSIGN(LSEVisitor);
658};
659
660void LoadStoreElimination::Run() {
David Brazdil8993caf2015-12-07 10:04:40 +0000661 if (graph_->IsDebuggable() || graph_->HasTryCatch()) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700662 // Debugger may set heap values or trigger deoptimization of callers.
David Brazdil8993caf2015-12-07 10:04:40 +0000663 // Try/catch support not implemented yet.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700664 // Skip this optimization.
665 return;
666 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100667 const HeapLocationCollector& heap_location_collector = lsa_.GetHeapLocationCollector();
668 if (heap_location_collector.GetNumberOfHeapLocations() == 0) {
669 // No HeapLocation information from LSA, skip this optimization.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700670 return;
671 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100672
Aart Bikd30f2052017-09-12 13:07:00 -0700673 // TODO: analyze VecLoad/VecStore better.
674 if (graph_->HasSIMD()) {
675 return;
676 }
677
Igor Murashkin6ef45672017-08-08 13:59:55 -0700678 LSEVisitor lse_visitor(graph_, heap_location_collector, side_effects_, stats_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100679 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
680 lse_visitor.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700681 }
682 lse_visitor.RemoveInstructions();
683}
684
685} // namespace art