blob: fddda3d8c0617147d5046023a24eecc6bac09378 [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,
43 const SideEffectsAnalysis& side_effects)
44 : HGraphVisitor(graph),
45 heap_location_collector_(heap_locations_collector),
46 side_effects_(side_effects),
47 heap_values_for_(graph->GetBlocks().size(),
48 ArenaVector<HInstruction*>(heap_locations_collector.
xueliang.zhongc239a2b2017-04-27 15:31:37 +010049 GetNumberOfHeapLocations(),
Mingyao Yang8df69d42015-10-22 15:40:58 -070050 kUnknownHeapValue,
51 graph->GetArena()->Adapter(kArenaAllocLSE)),
52 graph->GetArena()->Adapter(kArenaAllocLSE)),
Mingyao Yangfb8464a2015-11-02 10:56:59 -080053 removed_loads_(graph->GetArena()->Adapter(kArenaAllocLSE)),
54 substitute_instructions_for_loads_(graph->GetArena()->Adapter(kArenaAllocLSE)),
55 possibly_removed_stores_(graph->GetArena()->Adapter(kArenaAllocLSE)),
Mingyao Yang86974902017-03-01 14:03:51 -080056 singleton_new_instances_(graph->GetArena()->Adapter(kArenaAllocLSE)),
57 singleton_new_arrays_(graph->GetArena()->Adapter(kArenaAllocLSE)) {
Mingyao Yang8df69d42015-10-22 15:40:58 -070058 }
59
60 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080061 // Populate the heap_values array for this block.
Mingyao Yang8df69d42015-10-22 15:40:58 -070062 // TODO: try to reuse the heap_values array from one predecessor if possible.
63 if (block->IsLoopHeader()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080064 HandleLoopSideEffects(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -070065 } else {
66 MergePredecessorValues(block);
67 }
68 HGraphVisitor::VisitBasicBlock(block);
69 }
70
71 // Remove recorded instructions that should be eliminated.
72 void RemoveInstructions() {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080073 size_t size = removed_loads_.size();
74 DCHECK_EQ(size, substitute_instructions_for_loads_.size());
Mingyao Yang8df69d42015-10-22 15:40:58 -070075 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080076 HInstruction* load = removed_loads_[i];
77 DCHECK(load != nullptr);
78 DCHECK(load->IsInstanceFieldGet() ||
79 load->IsStaticFieldGet() ||
80 load->IsArrayGet());
81 HInstruction* substitute = substitute_instructions_for_loads_[i];
82 DCHECK(substitute != nullptr);
83 // Keep tracing substitute till one that's not removed.
84 HInstruction* sub_sub = FindSubstitute(substitute);
85 while (sub_sub != substitute) {
86 substitute = sub_sub;
87 sub_sub = FindSubstitute(substitute);
Mingyao Yang8df69d42015-10-22 15:40:58 -070088 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -080089 load->ReplaceWith(substitute);
90 load->GetBlock()->RemoveInstruction(load);
Mingyao Yang8df69d42015-10-22 15:40:58 -070091 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -080092
93 // At this point, stores in possibly_removed_stores_ can be safely removed.
Mingyao Yang86974902017-03-01 14:03:51 -080094 for (HInstruction* store : possibly_removed_stores_) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -080095 DCHECK(store->IsInstanceFieldSet() || store->IsStaticFieldSet() || store->IsArraySet());
96 store->GetBlock()->RemoveInstruction(store);
97 }
98
Igor Murashkind01745e2017-04-05 16:40:31 -070099 // Eliminate singleton-classified instructions:
100 // * - Constructor fences (they never escape this thread).
101 // * - Allocations (if they are unused).
Mingyao Yang86974902017-03-01 14:03:51 -0800102 for (HInstruction* new_instance : singleton_new_instances_) {
Igor Murashkind01745e2017-04-05 16:40:31 -0700103 HConstructorFence::RemoveConstructorFences(new_instance);
104
Mingyao Yang062157f2016-03-02 10:15:36 -0800105 if (!new_instance->HasNonEnvironmentUses()) {
106 new_instance->RemoveEnvironmentUsers();
107 new_instance->GetBlock()->RemoveInstruction(new_instance);
108 }
109 }
Mingyao Yang86974902017-03-01 14:03:51 -0800110 for (HInstruction* new_array : singleton_new_arrays_) {
Igor Murashkin79d8fa72017-04-18 09:37:23 -0700111 HConstructorFence::RemoveConstructorFences(new_array);
Igor Murashkind01745e2017-04-05 16:40:31 -0700112
Mingyao Yang86974902017-03-01 14:03:51 -0800113 if (!new_array->HasNonEnvironmentUses()) {
114 new_array->RemoveEnvironmentUsers();
115 new_array->GetBlock()->RemoveInstruction(new_array);
116 }
117 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700118 }
119
120 private:
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800121 // If heap_values[index] is an instance field store, need to keep the store.
122 // This is necessary if a heap value is killed due to merging, or loop side
123 // effects (which is essentially merging also), since a load later from the
124 // location won't be eliminated.
125 void KeepIfIsStore(HInstruction* heap_value) {
126 if (heap_value == kDefaultHeapValue ||
127 heap_value == kUnknownHeapValue ||
Mingyao Yang86974902017-03-01 14:03:51 -0800128 !(heap_value->IsInstanceFieldSet() || heap_value->IsArraySet())) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800129 return;
130 }
131 auto idx = std::find(possibly_removed_stores_.begin(),
132 possibly_removed_stores_.end(), heap_value);
133 if (idx != possibly_removed_stores_.end()) {
134 // Make sure the store is kept.
135 possibly_removed_stores_.erase(idx);
136 }
137 }
138
139 void HandleLoopSideEffects(HBasicBlock* block) {
140 DCHECK(block->IsLoopHeader());
141 int block_id = block->GetBlockId();
142 ArenaVector<HInstruction*>& heap_values = heap_values_for_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000143
144 // Don't eliminate loads in irreducible loops. This is safe for singletons, because
145 // they are always used by the non-eliminated loop-phi.
146 if (block->GetLoopInformation()->IsIrreducible()) {
147 if (kIsDebugBuild) {
148 for (size_t i = 0; i < heap_values.size(); i++) {
149 DCHECK_EQ(heap_values[i], kUnknownHeapValue);
150 }
151 }
152 return;
153 }
154
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800155 HBasicBlock* pre_header = block->GetLoopInformation()->GetPreHeader();
156 ArenaVector<HInstruction*>& pre_header_heap_values =
157 heap_values_for_[pre_header->GetBlockId()];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000158
Mingyao Yang803cbb92015-12-01 12:24:36 -0800159 // Inherit the values from pre-header.
160 for (size_t i = 0; i < heap_values.size(); i++) {
161 heap_values[i] = pre_header_heap_values[i];
162 }
163
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800164 // We do a single pass in reverse post order. For loops, use the side effects as a hint
165 // to see if the heap values should be killed.
166 if (side_effects_.GetLoopEffects(block).DoesAnyWrite()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800167 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800168 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
169 ReferenceInfo* ref_info = location->GetReferenceInfo();
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800170 if (ref_info->IsSingletonAndRemovable() &&
171 !location->IsValueKilledByLoopSideEffects()) {
172 // A removable singleton's field that's not stored into inside a loop is
173 // invariant throughout the loop. Nothing to do.
174 DCHECK(ref_info->IsSingletonAndRemovable());
175 } else {
176 // heap value is killed by loop side effects (stored into directly, or
177 // due to aliasing). Or the heap value may be needed after method return
178 // or deoptimization.
Mingyao Yang803cbb92015-12-01 12:24:36 -0800179 KeepIfIsStore(pre_header_heap_values[i]);
180 heap_values[i] = kUnknownHeapValue;
Mingyao Yang803cbb92015-12-01 12:24:36 -0800181 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800182 }
183 }
184 }
185
Mingyao Yang8df69d42015-10-22 15:40:58 -0700186 void MergePredecessorValues(HBasicBlock* block) {
187 const ArenaVector<HBasicBlock*>& predecessors = block->GetPredecessors();
188 if (predecessors.size() == 0) {
189 return;
190 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700191
Mingyao Yang8df69d42015-10-22 15:40:58 -0700192 ArenaVector<HInstruction*>& heap_values = heap_values_for_[block->GetBlockId()];
193 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700194 HInstruction* merged_value = nullptr;
195 // Whether merged_value is a result that's merged from all predecessors.
196 bool from_all_predecessors = true;
197 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
198 HInstruction* singleton_ref = nullptr;
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800199 if (ref_info->IsSingleton()) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700200 // We do more analysis of liveness when merging heap values for such
201 // cases since stores into such references may potentially be eliminated.
202 singleton_ref = ref_info->GetReference();
203 }
204
205 for (HBasicBlock* predecessor : predecessors) {
206 HInstruction* pred_value = heap_values_for_[predecessor->GetBlockId()][i];
207 if ((singleton_ref != nullptr) &&
208 !singleton_ref->GetBlock()->Dominates(predecessor)) {
209 // singleton_ref is not live in this predecessor. Skip this predecessor since
210 // it does not really have the location.
211 DCHECK_EQ(pred_value, kUnknownHeapValue);
212 from_all_predecessors = false;
213 continue;
214 }
215 if (merged_value == nullptr) {
216 // First seen heap value.
217 merged_value = pred_value;
218 } else if (pred_value != merged_value) {
219 // There are conflicting values.
220 merged_value = kUnknownHeapValue;
221 break;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700222 }
223 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800224
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800225 if (merged_value == kUnknownHeapValue || ref_info->IsSingletonAndNonRemovable()) {
226 // There are conflicting heap values from different predecessors,
227 // or the heap value may be needed after method return or deoptimization.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800228 // Keep the last store in each predecessor since future loads cannot be eliminated.
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700229 for (HBasicBlock* predecessor : predecessors) {
230 ArenaVector<HInstruction*>& pred_values = heap_values_for_[predecessor->GetBlockId()];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800231 KeepIfIsStore(pred_values[i]);
232 }
233 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700234
235 if ((merged_value == nullptr) || !from_all_predecessors) {
236 DCHECK(singleton_ref != nullptr);
237 DCHECK((singleton_ref->GetBlock() == block) ||
238 !singleton_ref->GetBlock()->Dominates(block));
239 // singleton_ref is not defined before block or defined only in some of its
240 // predecessors, so block doesn't really have the location at its entry.
241 heap_values[i] = kUnknownHeapValue;
242 } else {
243 heap_values[i] = merged_value;
244 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700245 }
246 }
247
248 // `instruction` is being removed. Try to see if the null check on it
249 // can be removed. This can happen if the same value is set in two branches
250 // but not in dominators. Such as:
251 // int[] a = foo();
252 // if () {
253 // a[0] = 2;
254 // } else {
255 // a[0] = 2;
256 // }
257 // // a[0] can now be replaced with constant 2, and the null check on it can be removed.
258 void TryRemovingNullCheck(HInstruction* instruction) {
259 HInstruction* prev = instruction->GetPrevious();
260 if ((prev != nullptr) && prev->IsNullCheck() && (prev == instruction->InputAt(0))) {
261 // Previous instruction is a null check for this instruction. Remove the null check.
262 prev->ReplaceWith(prev->InputAt(0));
263 prev->GetBlock()->RemoveInstruction(prev);
264 }
265 }
266
267 HInstruction* GetDefaultValue(Primitive::Type type) {
268 switch (type) {
269 case Primitive::kPrimNot:
270 return GetGraph()->GetNullConstant();
271 case Primitive::kPrimBoolean:
272 case Primitive::kPrimByte:
273 case Primitive::kPrimChar:
274 case Primitive::kPrimShort:
275 case Primitive::kPrimInt:
276 return GetGraph()->GetIntConstant(0);
277 case Primitive::kPrimLong:
278 return GetGraph()->GetLongConstant(0);
279 case Primitive::kPrimFloat:
280 return GetGraph()->GetFloatConstant(0);
281 case Primitive::kPrimDouble:
282 return GetGraph()->GetDoubleConstant(0);
283 default:
284 UNREACHABLE();
285 }
286 }
287
288 void VisitGetLocation(HInstruction* instruction,
289 HInstruction* ref,
290 size_t offset,
291 HInstruction* index,
292 int16_t declaring_class_def_index) {
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100293 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700294 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
295 size_t idx = heap_location_collector_.FindHeapLocationIndex(
296 ref_info, offset, index, declaring_class_def_index);
297 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
298 ArenaVector<HInstruction*>& heap_values =
299 heap_values_for_[instruction->GetBlock()->GetBlockId()];
300 HInstruction* heap_value = heap_values[idx];
301 if (heap_value == kDefaultHeapValue) {
302 HInstruction* constant = GetDefaultValue(instruction->GetType());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800303 removed_loads_.push_back(instruction);
304 substitute_instructions_for_loads_.push_back(constant);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700305 heap_values[idx] = constant;
306 return;
307 }
Mingyao Yang86974902017-03-01 14:03:51 -0800308 if (heap_value != kUnknownHeapValue) {
309 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
310 HInstruction* store = heap_value;
311 // This load must be from a singleton since it's from the same
312 // field/element that a "removed" store puts the value. That store
313 // must be to a singleton's field/element.
314 DCHECK(ref_info->IsSingleton());
315 // Get the real heap value of the store.
316 heap_value = heap_value->IsInstanceFieldSet() ? store->InputAt(1) : store->InputAt(2);
317 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800318 }
David Brazdil15693bf2015-12-16 10:30:45 +0000319 if (heap_value == kUnknownHeapValue) {
320 // Load isn't eliminated. Put the load as the value into the HeapLocation.
321 // This acts like GVN but with better aliasing analysis.
322 heap_values[idx] = instruction;
323 } else {
Nicolas Geoffray03971632016-03-17 10:44:24 +0000324 if (Primitive::PrimitiveKind(heap_value->GetType())
325 != Primitive::PrimitiveKind(instruction->GetType())) {
326 // The only situation where the same heap location has different type is when
Nicolas Geoffray65fef302016-05-04 14:00:12 +0100327 // we do an array get on an instruction that originates from the null constant
328 // (the null could be behind a field access, an array access, a null check or
329 // a bound type).
330 // In order to stay properly typed on primitive types, we do not eliminate
331 // the array gets.
Nicolas Geoffray03971632016-03-17 10:44:24 +0000332 if (kIsDebugBuild) {
333 DCHECK(heap_value->IsArrayGet()) << heap_value->DebugName();
334 DCHECK(instruction->IsArrayGet()) << instruction->DebugName();
Nicolas Geoffray03971632016-03-17 10:44:24 +0000335 }
336 return;
337 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800338 removed_loads_.push_back(instruction);
339 substitute_instructions_for_loads_.push_back(heap_value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700340 TryRemovingNullCheck(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700341 }
342 }
343
344 bool Equal(HInstruction* heap_value, HInstruction* value) {
345 if (heap_value == value) {
346 return true;
347 }
348 if (heap_value == kDefaultHeapValue && GetDefaultValue(value->GetType()) == value) {
349 return true;
350 }
351 return false;
352 }
353
354 void VisitSetLocation(HInstruction* instruction,
355 HInstruction* ref,
356 size_t offset,
357 HInstruction* index,
358 int16_t declaring_class_def_index,
359 HInstruction* value) {
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100360 HInstruction* original_ref = heap_location_collector_.HuntForOriginalReference(ref);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700361 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
362 size_t idx = heap_location_collector_.FindHeapLocationIndex(
363 ref_info, offset, index, declaring_class_def_index);
364 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
365 ArenaVector<HInstruction*>& heap_values =
366 heap_values_for_[instruction->GetBlock()->GetBlockId()];
367 HInstruction* heap_value = heap_values[idx];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800368 bool same_value = false;
369 bool possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700370 if (Equal(heap_value, value)) {
371 // Store into the heap location with the same value.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800372 same_value = true;
Mingyao Yang86974902017-03-01 14:03:51 -0800373 } else if (index != nullptr && ref_info->HasIndexAliasing()) {
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800374 // For array element, don't eliminate stores if the index can be aliased.
375 } else if (ref_info->IsSingleton()) {
376 // Store into a field of a singleton. The value cannot be killed due to
377 // aliasing/invocation. It can be redundant since future loads can
378 // directly get the value set by this instruction. The value can still be killed due to
379 // merging or loop side effects. Stores whose values are killed due to merging/loop side
380 // effects later will be removed from possibly_removed_stores_ when that is detected.
381 // Stores whose values may be needed after method return or deoptimization
382 // are also removed from possibly_removed_stores_ when that is detected.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800383 possibly_redundant = true;
384 HNewInstance* new_instance = ref_info->GetReference()->AsNewInstance();
Mingyao Yang86974902017-03-01 14:03:51 -0800385 if (new_instance != nullptr && new_instance->IsFinalizable()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800386 // Finalizable objects escape globally. Need to keep the store.
387 possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700388 } else {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800389 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
390 if (loop_info != nullptr) {
391 // instruction is a store in the loop so the loop must does write.
392 DCHECK(side_effects_.GetLoopEffects(loop_info->GetHeader()).DoesAnyWrite());
393
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800394 if (loop_info->IsDefinedOutOfTheLoop(original_ref)) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800395 DCHECK(original_ref->GetBlock()->Dominates(loop_info->GetPreHeader()));
396 // Keep the store since its value may be needed at the loop header.
397 possibly_redundant = false;
398 } else {
399 // The singleton is created inside the loop. Value stored to it isn't needed at
400 // the loop header. This is true for outer loops also.
401 }
402 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700403 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700404 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800405 if (same_value || possibly_redundant) {
406 possibly_removed_stores_.push_back(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700407 }
Mingyao Yange9d6e602015-10-23 17:08:42 -0700408
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800409 if (!same_value) {
410 if (possibly_redundant) {
Mingyao Yang86974902017-03-01 14:03:51 -0800411 DCHECK(instruction->IsInstanceFieldSet() || instruction->IsArraySet());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800412 // Put the store as the heap value. If the value is loaded from heap
413 // by a load later, this store isn't really redundant.
414 heap_values[idx] = instruction;
415 } else {
416 heap_values[idx] = value;
417 }
418 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700419 // This store may kill values in other heap locations due to aliasing.
420 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800421 if (i == idx) {
422 continue;
423 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700424 if (heap_values[i] == value) {
425 // Same value should be kept even if aliasing happens.
426 continue;
427 }
428 if (heap_values[i] == kUnknownHeapValue) {
429 // Value is already unknown, no need for aliasing check.
430 continue;
431 }
432 if (heap_location_collector_.MayAlias(i, idx)) {
433 // Kill heap locations that may alias.
434 heap_values[i] = kUnknownHeapValue;
435 }
436 }
437 }
438
439 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
440 HInstruction* obj = instruction->InputAt(0);
441 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
442 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
443 VisitGetLocation(instruction, obj, offset, nullptr, declaring_class_def_index);
444 }
445
446 void VisitInstanceFieldSet(HInstanceFieldSet* 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 HInstruction* value = instruction->InputAt(1);
451 VisitSetLocation(instruction, obj, offset, nullptr, declaring_class_def_index, value);
452 }
453
454 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
455 HInstruction* cls = instruction->InputAt(0);
456 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
457 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
458 VisitGetLocation(instruction, cls, offset, nullptr, declaring_class_def_index);
459 }
460
461 void VisitStaticFieldSet(HStaticFieldSet* 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 HInstruction* value = instruction->InputAt(1);
466 VisitSetLocation(instruction, cls, offset, nullptr, declaring_class_def_index, value);
467 }
468
469 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
470 HInstruction* array = instruction->InputAt(0);
471 HInstruction* index = instruction->InputAt(1);
472 VisitGetLocation(instruction,
473 array,
474 HeapLocation::kInvalidFieldOffset,
475 index,
476 HeapLocation::kDeclaringClassDefIndexForArrays);
477 }
478
479 void VisitArraySet(HArraySet* instruction) OVERRIDE {
480 HInstruction* array = instruction->InputAt(0);
481 HInstruction* index = instruction->InputAt(1);
482 HInstruction* value = instruction->InputAt(2);
483 VisitSetLocation(instruction,
484 array,
485 HeapLocation::kInvalidFieldOffset,
486 index,
487 HeapLocation::kDeclaringClassDefIndexForArrays,
488 value);
489 }
490
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800491 void VisitDeoptimize(HDeoptimize* instruction) {
492 const ArenaVector<HInstruction*>& heap_values =
493 heap_values_for_[instruction->GetBlock()->GetBlockId()];
494 for (HInstruction* heap_value : heap_values) {
495 // Filter out fake instructions before checking instruction kind below.
496 if (heap_value == kUnknownHeapValue || heap_value == kDefaultHeapValue) {
497 continue;
498 }
499 // A store is kept as the heap value for possibly removed stores.
500 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
501 // Check whether the reference for a store is used by an environment local of
502 // HDeoptimize.
503 HInstruction* reference = heap_value->InputAt(0);
504 DCHECK(heap_location_collector_.FindReferenceInfoOf(reference)->IsSingleton());
505 for (const HUseListNode<HEnvironment*>& use : reference->GetEnvUses()) {
506 HEnvironment* user = use.GetUser();
507 if (user->GetHolder() == instruction) {
508 // The singleton for the store is visible at this deoptimization
509 // point. Need to keep the store so that the heap value is
510 // seen by the interpreter.
511 KeepIfIsStore(heap_value);
512 }
513 }
514 }
515 }
516 }
517
Mingyao Yang8df69d42015-10-22 15:40:58 -0700518 void HandleInvoke(HInstruction* invoke) {
519 ArenaVector<HInstruction*>& heap_values =
520 heap_values_for_[invoke->GetBlock()->GetBlockId()];
521 for (size_t i = 0; i < heap_values.size(); i++) {
522 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
523 if (ref_info->IsSingleton()) {
524 // Singleton references cannot be seen by the callee.
525 } else {
526 heap_values[i] = kUnknownHeapValue;
527 }
528 }
529 }
530
531 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) OVERRIDE {
532 HandleInvoke(invoke);
533 }
534
535 void VisitInvokeVirtual(HInvokeVirtual* invoke) OVERRIDE {
536 HandleInvoke(invoke);
537 }
538
539 void VisitInvokeInterface(HInvokeInterface* invoke) OVERRIDE {
540 HandleInvoke(invoke);
541 }
542
543 void VisitInvokeUnresolved(HInvokeUnresolved* invoke) OVERRIDE {
544 HandleInvoke(invoke);
545 }
546
Orion Hodsonac141392017-01-13 11:53:47 +0000547 void VisitInvokePolymorphic(HInvokePolymorphic* invoke) OVERRIDE {
548 HandleInvoke(invoke);
549 }
550
Mingyao Yang8df69d42015-10-22 15:40:58 -0700551 void VisitClinitCheck(HClinitCheck* clinit) OVERRIDE {
552 HandleInvoke(clinit);
553 }
554
555 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* instruction) OVERRIDE {
556 // Conservatively treat it as an invocation.
557 HandleInvoke(instruction);
558 }
559
560 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* instruction) OVERRIDE {
561 // Conservatively treat it as an invocation.
562 HandleInvoke(instruction);
563 }
564
565 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* instruction) OVERRIDE {
566 // Conservatively treat it as an invocation.
567 HandleInvoke(instruction);
568 }
569
570 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* instruction) OVERRIDE {
571 // Conservatively treat it as an invocation.
572 HandleInvoke(instruction);
573 }
574
575 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
576 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_instance);
577 if (ref_info == nullptr) {
578 // new_instance isn't used for field accesses. No need to process it.
579 return;
580 }
Aart Bik71bf7b42016-11-16 10:17:46 -0800581 if (ref_info->IsSingletonAndRemovable() &&
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800582 !new_instance->IsFinalizable() &&
Nicolas Geoffray5247c082017-01-13 14:17:29 +0000583 !new_instance->NeedsChecks()) {
Mingyao Yang062157f2016-03-02 10:15:36 -0800584 singleton_new_instances_.push_back(new_instance);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700585 }
586 ArenaVector<HInstruction*>& heap_values =
587 heap_values_for_[new_instance->GetBlock()->GetBlockId()];
588 for (size_t i = 0; i < heap_values.size(); i++) {
589 HInstruction* ref =
590 heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo()->GetReference();
591 size_t offset = heap_location_collector_.GetHeapLocation(i)->GetOffset();
592 if (ref == new_instance && offset >= mirror::kObjectHeaderSize) {
593 // Instance fields except the header fields are set to default heap values.
594 heap_values[i] = kDefaultHeapValue;
595 }
596 }
597 }
598
Mingyao Yang86974902017-03-01 14:03:51 -0800599 void VisitNewArray(HNewArray* new_array) OVERRIDE {
600 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_array);
601 if (ref_info == nullptr) {
602 // new_array isn't used for array accesses. No need to process it.
603 return;
604 }
605 if (ref_info->IsSingletonAndRemovable()) {
606 singleton_new_arrays_.push_back(new_array);
607 }
608 ArenaVector<HInstruction*>& heap_values =
609 heap_values_for_[new_array->GetBlock()->GetBlockId()];
610 for (size_t i = 0; i < heap_values.size(); i++) {
611 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
612 HInstruction* ref = location->GetReferenceInfo()->GetReference();
613 if (ref == new_array && location->GetIndex() != nullptr) {
614 // Array elements are set to default heap values.
615 heap_values[i] = kDefaultHeapValue;
616 }
617 }
618 }
619
Mingyao Yang8df69d42015-10-22 15:40:58 -0700620 // Find an instruction's substitute if it should be removed.
621 // Return the same instruction if it should not be removed.
622 HInstruction* FindSubstitute(HInstruction* instruction) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800623 size_t size = removed_loads_.size();
Mingyao Yang8df69d42015-10-22 15:40:58 -0700624 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800625 if (removed_loads_[i] == instruction) {
626 return substitute_instructions_for_loads_[i];
Mingyao Yang8df69d42015-10-22 15:40:58 -0700627 }
628 }
629 return instruction;
630 }
631
632 const HeapLocationCollector& heap_location_collector_;
633 const SideEffectsAnalysis& side_effects_;
634
635 // One array of heap values for each block.
636 ArenaVector<ArenaVector<HInstruction*>> heap_values_for_;
637
638 // We record the instructions that should be eliminated but may be
639 // used by heap locations. They'll be removed in the end.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800640 ArenaVector<HInstruction*> removed_loads_;
641 ArenaVector<HInstruction*> substitute_instructions_for_loads_;
642
643 // Stores in this list may be removed from the list later when it's
644 // found that the store cannot be eliminated.
645 ArenaVector<HInstruction*> possibly_removed_stores_;
646
Mingyao Yang8df69d42015-10-22 15:40:58 -0700647 ArenaVector<HInstruction*> singleton_new_instances_;
Mingyao Yang86974902017-03-01 14:03:51 -0800648 ArenaVector<HInstruction*> singleton_new_arrays_;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700649
650 DISALLOW_COPY_AND_ASSIGN(LSEVisitor);
651};
652
653void LoadStoreElimination::Run() {
David Brazdil8993caf2015-12-07 10:04:40 +0000654 if (graph_->IsDebuggable() || graph_->HasTryCatch()) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700655 // Debugger may set heap values or trigger deoptimization of callers.
David Brazdil8993caf2015-12-07 10:04:40 +0000656 // Try/catch support not implemented yet.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700657 // Skip this optimization.
658 return;
659 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100660 const HeapLocationCollector& heap_location_collector = lsa_.GetHeapLocationCollector();
661 if (heap_location_collector.GetNumberOfHeapLocations() == 0) {
662 // No HeapLocation information from LSA, skip this optimization.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700663 return;
664 }
xueliang.zhongc239a2b2017-04-27 15:31:37 +0100665
Mingyao Yang8df69d42015-10-22 15:40:58 -0700666 LSEVisitor lse_visitor(graph_, heap_location_collector, side_effects_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100667 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
668 lse_visitor.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700669 }
670 lse_visitor.RemoveInstructions();
671}
672
673} // namespace art