blob: 8d8cc93b9b35b5f2fa3eea17d030114345f98c22 [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"
Mingyao Yang8df69d42015-10-22 15:40:58 -070020#include "side_effects_analysis.h"
21
22#include <iostream>
23
24namespace art {
25
26class ReferenceInfo;
27
28// A cap for the number of heap locations to prevent pathological time/space consumption.
29// The number of heap locations for most of the methods stays below this threshold.
30constexpr size_t kMaxNumberOfHeapLocations = 32;
31
32// A ReferenceInfo contains additional info about a reference such as
33// whether it's a singleton, returned, etc.
34class ReferenceInfo : public ArenaObject<kArenaAllocMisc> {
35 public:
Aart Bik96fd51d2016-11-28 11:22:35 -080036 ReferenceInfo(HInstruction* reference, size_t pos)
37 : reference_(reference),
38 position_(pos),
39 is_singleton_(true),
Aart Bik71bf7b42016-11-16 10:17:46 -080040 is_singleton_and_not_returned_(true),
Mingyao Yang86974902017-03-01 14:03:51 -080041 is_singleton_and_not_deopt_visible_(true),
42 has_index_aliasing_(false) {
Aart Bik71bf7b42016-11-16 10:17:46 -080043 CalculateEscape(reference_,
44 nullptr,
45 &is_singleton_,
46 &is_singleton_and_not_returned_,
47 &is_singleton_and_not_deopt_visible_);
Mingyao Yang8df69d42015-10-22 15:40:58 -070048 }
49
50 HInstruction* GetReference() const {
51 return reference_;
52 }
53
54 size_t GetPosition() const {
55 return position_;
56 }
57
58 // Returns true if reference_ is the only name that can refer to its value during
59 // the lifetime of the method. So it's guaranteed to not have any alias in
60 // the method (including its callees).
61 bool IsSingleton() const {
62 return is_singleton_;
63 }
64
Mingyao Yange58bdca2016-10-28 11:07:24 -070065 // Returns true if reference_ is a singleton and not returned to the caller or
66 // used as an environment local of an HDeoptimize instruction.
Mingyao Yang8df69d42015-10-22 15:40:58 -070067 // The allocation and stores into reference_ may be eliminated for such cases.
Aart Bik71bf7b42016-11-16 10:17:46 -080068 bool IsSingletonAndRemovable() const {
69 return is_singleton_and_not_returned_ && is_singleton_and_not_deopt_visible_;
Mingyao Yang8df69d42015-10-22 15:40:58 -070070 }
71
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -080072 // Returns true if reference_ is a singleton and returned to the caller or
73 // used as an environment local of an HDeoptimize instruction.
74 bool IsSingletonAndNonRemovable() const {
75 return is_singleton_ &&
76 (!is_singleton_and_not_returned_ || !is_singleton_and_not_deopt_visible_);
77 }
78
Mingyao Yang86974902017-03-01 14:03:51 -080079 bool HasIndexAliasing() {
80 return has_index_aliasing_;
81 }
82
83 void SetHasIndexAliasing(bool has_index_aliasing) {
84 // Only allow setting to true.
85 DCHECK(has_index_aliasing);
86 has_index_aliasing_ = has_index_aliasing;
87 }
88
Mingyao Yang8df69d42015-10-22 15:40:58 -070089 private:
90 HInstruction* const reference_;
Aart Bik71bf7b42016-11-16 10:17:46 -080091 const size_t position_; // position in HeapLocationCollector's ref_info_array_.
Mingyao Yange58bdca2016-10-28 11:07:24 -070092
Mingyao Yang86974902017-03-01 14:03:51 -080093 // Can only be referred to by a single name in the method.
94 bool is_singleton_;
95 // Is singleton and not returned to caller.
96 bool is_singleton_and_not_returned_;
97 // Is singleton and not used as an environment local of HDeoptimize.
98 bool is_singleton_and_not_deopt_visible_;
99 // Some heap locations with reference_ have array index aliasing,
100 // e.g. arr[i] and arr[j] may be the same location.
101 bool has_index_aliasing_;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700102
103 DISALLOW_COPY_AND_ASSIGN(ReferenceInfo);
104};
105
106// A heap location is a reference-offset/index pair that a value can be loaded from
107// or stored to.
108class HeapLocation : public ArenaObject<kArenaAllocMisc> {
109 public:
110 static constexpr size_t kInvalidFieldOffset = -1;
111
112 // TODO: more fine-grained array types.
113 static constexpr int16_t kDeclaringClassDefIndexForArrays = -1;
114
115 HeapLocation(ReferenceInfo* ref_info,
116 size_t offset,
117 HInstruction* index,
118 int16_t declaring_class_def_index)
119 : ref_info_(ref_info),
120 offset_(offset),
121 index_(index),
Mingyao Yang803cbb92015-12-01 12:24:36 -0800122 declaring_class_def_index_(declaring_class_def_index),
123 value_killed_by_loop_side_effects_(true) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700124 DCHECK(ref_info != nullptr);
125 DCHECK((offset == kInvalidFieldOffset && index != nullptr) ||
126 (offset != kInvalidFieldOffset && index == nullptr));
Mingyao Yang803cbb92015-12-01 12:24:36 -0800127 if (ref_info->IsSingleton() && !IsArrayElement()) {
128 // Assume this location's value cannot be killed by loop side effects
129 // until proven otherwise.
130 value_killed_by_loop_side_effects_ = false;
131 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700132 }
133
134 ReferenceInfo* GetReferenceInfo() const { return ref_info_; }
135 size_t GetOffset() const { return offset_; }
136 HInstruction* GetIndex() const { return index_; }
137
138 // Returns the definition of declaring class' dex index.
139 // It's kDeclaringClassDefIndexForArrays for an array element.
140 int16_t GetDeclaringClassDefIndex() const {
141 return declaring_class_def_index_;
142 }
143
144 bool IsArrayElement() const {
145 return index_ != nullptr;
146 }
147
Mingyao Yang803cbb92015-12-01 12:24:36 -0800148 bool IsValueKilledByLoopSideEffects() const {
149 return value_killed_by_loop_side_effects_;
150 }
151
152 void SetValueKilledByLoopSideEffects(bool val) {
153 value_killed_by_loop_side_effects_ = val;
154 }
155
Mingyao Yang8df69d42015-10-22 15:40:58 -0700156 private:
157 ReferenceInfo* const ref_info_; // reference for instance/static field or array access.
158 const size_t offset_; // offset of static/instance field.
159 HInstruction* const index_; // index of an array element.
160 const int16_t declaring_class_def_index_; // declaring class's def's dex index.
Mingyao Yang803cbb92015-12-01 12:24:36 -0800161 bool value_killed_by_loop_side_effects_; // value of this location may be killed by loop
162 // side effects because this location is stored
Mingyao Yang0a845202016-10-14 16:26:08 -0700163 // into inside a loop. This gives
164 // better info on whether a singleton's location
165 // value may be killed by loop side effects.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700166
167 DISALLOW_COPY_AND_ASSIGN(HeapLocation);
168};
169
170static HInstruction* HuntForOriginalReference(HInstruction* ref) {
171 DCHECK(ref != nullptr);
172 while (ref->IsNullCheck() || ref->IsBoundType()) {
173 ref = ref->InputAt(0);
174 }
175 return ref;
176}
177
178// A HeapLocationCollector collects all relevant heap locations and keeps
179// an aliasing matrix for all locations.
180class HeapLocationCollector : public HGraphVisitor {
181 public:
182 static constexpr size_t kHeapLocationNotFound = -1;
183 // Start with a single uint32_t word. That's enough bits for pair-wise
184 // aliasing matrix of 8 heap locations.
185 static constexpr uint32_t kInitialAliasingMatrixBitVectorSize = 32;
186
187 explicit HeapLocationCollector(HGraph* graph)
188 : HGraphVisitor(graph),
189 ref_info_array_(graph->GetArena()->Adapter(kArenaAllocLSE)),
190 heap_locations_(graph->GetArena()->Adapter(kArenaAllocLSE)),
Vladimir Markof6a35de2016-03-21 12:01:50 +0000191 aliasing_matrix_(graph->GetArena(),
192 kInitialAliasingMatrixBitVectorSize,
193 true,
194 kArenaAllocLSE),
Mingyao Yang8df69d42015-10-22 15:40:58 -0700195 has_heap_stores_(false),
196 has_volatile_(false),
Mingyao Yange58bdca2016-10-28 11:07:24 -0700197 has_monitor_operations_(false) {}
Mingyao Yang8df69d42015-10-22 15:40:58 -0700198
199 size_t GetNumberOfHeapLocations() const {
200 return heap_locations_.size();
201 }
202
203 HeapLocation* GetHeapLocation(size_t index) const {
204 return heap_locations_[index];
205 }
206
207 ReferenceInfo* FindReferenceInfoOf(HInstruction* ref) const {
208 for (size_t i = 0; i < ref_info_array_.size(); i++) {
209 ReferenceInfo* ref_info = ref_info_array_[i];
210 if (ref_info->GetReference() == ref) {
211 DCHECK_EQ(i, ref_info->GetPosition());
212 return ref_info;
213 }
214 }
215 return nullptr;
216 }
217
218 bool HasHeapStores() const {
219 return has_heap_stores_;
220 }
221
222 bool HasVolatile() const {
223 return has_volatile_;
224 }
225
226 bool HasMonitorOps() const {
227 return has_monitor_operations_;
228 }
229
Mingyao Yang8df69d42015-10-22 15:40:58 -0700230 // Find and return the heap location index in heap_locations_.
231 size_t FindHeapLocationIndex(ReferenceInfo* ref_info,
232 size_t offset,
233 HInstruction* index,
234 int16_t declaring_class_def_index) const {
235 for (size_t i = 0; i < heap_locations_.size(); i++) {
236 HeapLocation* loc = heap_locations_[i];
237 if (loc->GetReferenceInfo() == ref_info &&
238 loc->GetOffset() == offset &&
239 loc->GetIndex() == index &&
240 loc->GetDeclaringClassDefIndex() == declaring_class_def_index) {
241 return i;
242 }
243 }
244 return kHeapLocationNotFound;
245 }
246
247 // Returns true if heap_locations_[index1] and heap_locations_[index2] may alias.
248 bool MayAlias(size_t index1, size_t index2) const {
249 if (index1 < index2) {
250 return aliasing_matrix_.IsBitSet(AliasingMatrixPosition(index1, index2));
251 } else if (index1 > index2) {
252 return aliasing_matrix_.IsBitSet(AliasingMatrixPosition(index2, index1));
253 } else {
254 DCHECK(false) << "index1 and index2 are expected to be different";
255 return true;
256 }
257 }
258
259 void BuildAliasingMatrix() {
260 const size_t number_of_locations = heap_locations_.size();
261 if (number_of_locations == 0) {
262 return;
263 }
264 size_t pos = 0;
265 // Compute aliasing info between every pair of different heap locations.
266 // Save the result in a matrix represented as a BitVector.
267 for (size_t i = 0; i < number_of_locations - 1; i++) {
268 for (size_t j = i + 1; j < number_of_locations; j++) {
269 if (ComputeMayAlias(i, j)) {
270 aliasing_matrix_.SetBit(CheckedAliasingMatrixPosition(i, j, pos));
271 }
272 pos++;
273 }
274 }
275 }
276
277 private:
278 // An allocation cannot alias with a name which already exists at the point
279 // of the allocation, such as a parameter or a load happening before the allocation.
280 bool MayAliasWithPreexistenceChecking(ReferenceInfo* ref_info1, ReferenceInfo* ref_info2) const {
281 if (ref_info1->GetReference()->IsNewInstance() || ref_info1->GetReference()->IsNewArray()) {
282 // Any reference that can alias with the allocation must appear after it in the block/in
283 // the block's successors. In reverse post order, those instructions will be visited after
284 // the allocation.
285 return ref_info2->GetPosition() >= ref_info1->GetPosition();
286 }
287 return true;
288 }
289
290 bool CanReferencesAlias(ReferenceInfo* ref_info1, ReferenceInfo* ref_info2) const {
291 if (ref_info1 == ref_info2) {
292 return true;
293 } else if (ref_info1->IsSingleton()) {
294 return false;
295 } else if (ref_info2->IsSingleton()) {
296 return false;
297 } else if (!MayAliasWithPreexistenceChecking(ref_info1, ref_info2) ||
298 !MayAliasWithPreexistenceChecking(ref_info2, ref_info1)) {
299 return false;
300 }
301 return true;
302 }
303
304 // `index1` and `index2` are indices in the array of collected heap locations.
305 // Returns the position in the bit vector that tracks whether the two heap
306 // locations may alias.
307 size_t AliasingMatrixPosition(size_t index1, size_t index2) const {
308 DCHECK(index2 > index1);
309 const size_t number_of_locations = heap_locations_.size();
310 // It's (num_of_locations - 1) + ... + (num_of_locations - index1) + (index2 - index1 - 1).
311 return (number_of_locations * index1 - (1 + index1) * index1 / 2 + (index2 - index1 - 1));
312 }
313
314 // An additional position is passed in to make sure the calculated position is correct.
315 size_t CheckedAliasingMatrixPosition(size_t index1, size_t index2, size_t position) {
316 size_t calculated_position = AliasingMatrixPosition(index1, index2);
317 DCHECK_EQ(calculated_position, position);
318 return calculated_position;
319 }
320
321 // Compute if two locations may alias to each other.
322 bool ComputeMayAlias(size_t index1, size_t index2) const {
323 HeapLocation* loc1 = heap_locations_[index1];
324 HeapLocation* loc2 = heap_locations_[index2];
325 if (loc1->GetOffset() != loc2->GetOffset()) {
326 // Either two different instance fields, or one is an instance
327 // field and the other is an array element.
328 return false;
329 }
330 if (loc1->GetDeclaringClassDefIndex() != loc2->GetDeclaringClassDefIndex()) {
331 // Different types.
332 return false;
333 }
334 if (!CanReferencesAlias(loc1->GetReferenceInfo(), loc2->GetReferenceInfo())) {
335 return false;
336 }
337 if (loc1->IsArrayElement() && loc2->IsArrayElement()) {
338 HInstruction* array_index1 = loc1->GetIndex();
339 HInstruction* array_index2 = loc2->GetIndex();
340 DCHECK(array_index1 != nullptr);
341 DCHECK(array_index2 != nullptr);
342 if (array_index1->IsIntConstant() &&
343 array_index2->IsIntConstant() &&
344 array_index1->AsIntConstant()->GetValue() != array_index2->AsIntConstant()->GetValue()) {
345 // Different constant indices do not alias.
346 return false;
347 }
Mingyao Yang86974902017-03-01 14:03:51 -0800348 ReferenceInfo* ref_info = loc1->GetReferenceInfo();
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800349 ref_info->SetHasIndexAliasing(true);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700350 }
351 return true;
352 }
353
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800354 ReferenceInfo* GetOrCreateReferenceInfo(HInstruction* instruction) {
355 ReferenceInfo* ref_info = FindReferenceInfoOf(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700356 if (ref_info == nullptr) {
357 size_t pos = ref_info_array_.size();
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800358 ref_info = new (GetGraph()->GetArena()) ReferenceInfo(instruction, pos);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700359 ref_info_array_.push_back(ref_info);
360 }
361 return ref_info;
362 }
363
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800364 void CreateReferenceInfoForReferenceType(HInstruction* instruction) {
365 if (instruction->GetType() != Primitive::kPrimNot) {
366 return;
367 }
368 DCHECK(FindReferenceInfoOf(instruction) == nullptr);
369 GetOrCreateReferenceInfo(instruction);
370 }
371
Mingyao Yang8df69d42015-10-22 15:40:58 -0700372 HeapLocation* GetOrCreateHeapLocation(HInstruction* ref,
373 size_t offset,
374 HInstruction* index,
375 int16_t declaring_class_def_index) {
376 HInstruction* original_ref = HuntForOriginalReference(ref);
377 ReferenceInfo* ref_info = GetOrCreateReferenceInfo(original_ref);
378 size_t heap_location_idx = FindHeapLocationIndex(
379 ref_info, offset, index, declaring_class_def_index);
380 if (heap_location_idx == kHeapLocationNotFound) {
381 HeapLocation* heap_loc = new (GetGraph()->GetArena())
382 HeapLocation(ref_info, offset, index, declaring_class_def_index);
383 heap_locations_.push_back(heap_loc);
384 return heap_loc;
385 }
386 return heap_locations_[heap_location_idx];
387 }
388
Mingyao Yang803cbb92015-12-01 12:24:36 -0800389 HeapLocation* VisitFieldAccess(HInstruction* ref, const FieldInfo& field_info) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700390 if (field_info.IsVolatile()) {
391 has_volatile_ = true;
392 }
393 const uint16_t declaring_class_def_index = field_info.GetDeclaringClassDefIndex();
394 const size_t offset = field_info.GetFieldOffset().SizeValue();
Mingyao Yang803cbb92015-12-01 12:24:36 -0800395 return GetOrCreateHeapLocation(ref, offset, nullptr, declaring_class_def_index);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700396 }
397
398 void VisitArrayAccess(HInstruction* array, HInstruction* index) {
399 GetOrCreateHeapLocation(array, HeapLocation::kInvalidFieldOffset,
400 index, HeapLocation::kDeclaringClassDefIndexForArrays);
401 }
402
403 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800404 VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800405 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700406 }
407
408 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800409 HeapLocation* location = VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700410 has_heap_stores_ = true;
Mingyao Yang0a845202016-10-14 16:26:08 -0700411 if (location->GetReferenceInfo()->IsSingleton()) {
412 // A singleton's location value may be killed by loop side effects if it's
413 // defined before that loop, and it's stored into inside that loop.
414 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
415 if (loop_info != nullptr) {
416 HInstruction* ref = location->GetReferenceInfo()->GetReference();
417 DCHECK(ref->IsNewInstance());
418 if (loop_info->IsDefinedOutOfTheLoop(ref)) {
419 // ref's location value may be killed by this loop's side effects.
420 location->SetValueKilledByLoopSideEffects(true);
421 } else {
422 // ref is defined inside this loop so this loop's side effects cannot
423 // kill its location value at the loop header since ref/its location doesn't
424 // exist yet at the loop header.
425 }
426 }
427 } else {
428 // For non-singletons, value_killed_by_loop_side_effects_ is inited to
429 // true.
430 DCHECK_EQ(location->IsValueKilledByLoopSideEffects(), true);
Mingyao Yang803cbb92015-12-01 12:24:36 -0800431 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700432 }
433
434 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800435 VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800436 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700437 }
438
439 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800440 VisitFieldAccess(instruction->InputAt(0), instruction->GetFieldInfo());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700441 has_heap_stores_ = true;
442 }
443
444 // We intentionally don't collect HUnresolvedInstanceField/HUnresolvedStaticField accesses
445 // since we cannot accurately track the fields.
446
447 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
448 VisitArrayAccess(instruction->InputAt(0), instruction->InputAt(1));
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800449 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700450 }
451
452 void VisitArraySet(HArraySet* instruction) OVERRIDE {
453 VisitArrayAccess(instruction->InputAt(0), instruction->InputAt(1));
454 has_heap_stores_ = true;
455 }
456
457 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
458 // Any references appearing in the ref_info_array_ so far cannot alias with new_instance.
Mingyao Yang8ab1d642015-12-03 14:11:15 -0800459 CreateReferenceInfoForReferenceType(new_instance);
460 }
461
462 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* instruction) OVERRIDE {
463 CreateReferenceInfoForReferenceType(instruction);
464 }
465
466 void VisitInvokeVirtual(HInvokeVirtual* instruction) OVERRIDE {
467 CreateReferenceInfoForReferenceType(instruction);
468 }
469
470 void VisitInvokeInterface(HInvokeInterface* instruction) OVERRIDE {
471 CreateReferenceInfoForReferenceType(instruction);
472 }
473
474 void VisitParameterValue(HParameterValue* instruction) OVERRIDE {
475 CreateReferenceInfoForReferenceType(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700476 }
477
Mingyao Yang40bcb932016-02-03 05:46:57 -0800478 void VisitSelect(HSelect* instruction) OVERRIDE {
479 CreateReferenceInfoForReferenceType(instruction);
480 }
481
Mingyao Yang8df69d42015-10-22 15:40:58 -0700482 void VisitMonitorOperation(HMonitorOperation* monitor ATTRIBUTE_UNUSED) OVERRIDE {
483 has_monitor_operations_ = true;
484 }
485
486 ArenaVector<ReferenceInfo*> ref_info_array_; // All references used for heap accesses.
487 ArenaVector<HeapLocation*> heap_locations_; // All heap locations.
488 ArenaBitVector aliasing_matrix_; // aliasing info between each pair of locations.
489 bool has_heap_stores_; // If there is no heap stores, LSE acts as GVN with better
490 // alias analysis and won't be as effective.
491 bool has_volatile_; // If there are volatile field accesses.
492 bool has_monitor_operations_; // If there are monitor operations.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700493
494 DISALLOW_COPY_AND_ASSIGN(HeapLocationCollector);
495};
496
497// An unknown heap value. Loads with such a value in the heap location cannot be eliminated.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800498// A heap location can be set to kUnknownHeapValue when:
499// - initially set a value.
500// - killed due to aliasing, merging, invocation, or loop side effects.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700501static HInstruction* const kUnknownHeapValue =
502 reinterpret_cast<HInstruction*>(static_cast<uintptr_t>(-1));
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800503
Mingyao Yang8df69d42015-10-22 15:40:58 -0700504// Default heap value after an allocation.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800505// A heap location can be set to that value right after an allocation.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700506static HInstruction* const kDefaultHeapValue =
507 reinterpret_cast<HInstruction*>(static_cast<uintptr_t>(-2));
508
509class LSEVisitor : public HGraphVisitor {
510 public:
511 LSEVisitor(HGraph* graph,
512 const HeapLocationCollector& heap_locations_collector,
513 const SideEffectsAnalysis& side_effects)
514 : HGraphVisitor(graph),
515 heap_location_collector_(heap_locations_collector),
516 side_effects_(side_effects),
517 heap_values_for_(graph->GetBlocks().size(),
518 ArenaVector<HInstruction*>(heap_locations_collector.
519 GetNumberOfHeapLocations(),
520 kUnknownHeapValue,
521 graph->GetArena()->Adapter(kArenaAllocLSE)),
522 graph->GetArena()->Adapter(kArenaAllocLSE)),
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800523 removed_loads_(graph->GetArena()->Adapter(kArenaAllocLSE)),
524 substitute_instructions_for_loads_(graph->GetArena()->Adapter(kArenaAllocLSE)),
525 possibly_removed_stores_(graph->GetArena()->Adapter(kArenaAllocLSE)),
Mingyao Yang86974902017-03-01 14:03:51 -0800526 singleton_new_instances_(graph->GetArena()->Adapter(kArenaAllocLSE)),
527 singleton_new_arrays_(graph->GetArena()->Adapter(kArenaAllocLSE)) {
Mingyao Yang8df69d42015-10-22 15:40:58 -0700528 }
529
530 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800531 // Populate the heap_values array for this block.
Mingyao Yang8df69d42015-10-22 15:40:58 -0700532 // TODO: try to reuse the heap_values array from one predecessor if possible.
533 if (block->IsLoopHeader()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800534 HandleLoopSideEffects(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700535 } else {
536 MergePredecessorValues(block);
537 }
538 HGraphVisitor::VisitBasicBlock(block);
539 }
540
541 // Remove recorded instructions that should be eliminated.
542 void RemoveInstructions() {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800543 size_t size = removed_loads_.size();
544 DCHECK_EQ(size, substitute_instructions_for_loads_.size());
Mingyao Yang8df69d42015-10-22 15:40:58 -0700545 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800546 HInstruction* load = removed_loads_[i];
547 DCHECK(load != nullptr);
548 DCHECK(load->IsInstanceFieldGet() ||
549 load->IsStaticFieldGet() ||
550 load->IsArrayGet());
551 HInstruction* substitute = substitute_instructions_for_loads_[i];
552 DCHECK(substitute != nullptr);
553 // Keep tracing substitute till one that's not removed.
554 HInstruction* sub_sub = FindSubstitute(substitute);
555 while (sub_sub != substitute) {
556 substitute = sub_sub;
557 sub_sub = FindSubstitute(substitute);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700558 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800559 load->ReplaceWith(substitute);
560 load->GetBlock()->RemoveInstruction(load);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700561 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800562
563 // At this point, stores in possibly_removed_stores_ can be safely removed.
Mingyao Yang86974902017-03-01 14:03:51 -0800564 for (HInstruction* store : possibly_removed_stores_) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800565 DCHECK(store->IsInstanceFieldSet() || store->IsStaticFieldSet() || store->IsArraySet());
566 store->GetBlock()->RemoveInstruction(store);
567 }
568
Igor Murashkind01745e2017-04-05 16:40:31 -0700569 // Eliminate singleton-classified instructions:
570 // * - Constructor fences (they never escape this thread).
571 // * - Allocations (if they are unused).
Mingyao Yang86974902017-03-01 14:03:51 -0800572 for (HInstruction* new_instance : singleton_new_instances_) {
Igor Murashkind01745e2017-04-05 16:40:31 -0700573 HConstructorFence::RemoveConstructorFences(new_instance);
574
Mingyao Yang062157f2016-03-02 10:15:36 -0800575 if (!new_instance->HasNonEnvironmentUses()) {
576 new_instance->RemoveEnvironmentUsers();
577 new_instance->GetBlock()->RemoveInstruction(new_instance);
578 }
579 }
Mingyao Yang86974902017-03-01 14:03:51 -0800580 for (HInstruction* new_array : singleton_new_arrays_) {
Igor Murashkind01745e2017-04-05 16:40:31 -0700581 // TODO: Delete constructor fences for new-array
582 // In the future HNewArray instructions will have HConstructorFence's for them.
583 // HConstructorFence::RemoveConstructorFences(new_array);
584
Mingyao Yang86974902017-03-01 14:03:51 -0800585 if (!new_array->HasNonEnvironmentUses()) {
586 new_array->RemoveEnvironmentUsers();
587 new_array->GetBlock()->RemoveInstruction(new_array);
588 }
589 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700590 }
591
592 private:
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800593 // If heap_values[index] is an instance field store, need to keep the store.
594 // This is necessary if a heap value is killed due to merging, or loop side
595 // effects (which is essentially merging also), since a load later from the
596 // location won't be eliminated.
597 void KeepIfIsStore(HInstruction* heap_value) {
598 if (heap_value == kDefaultHeapValue ||
599 heap_value == kUnknownHeapValue ||
Mingyao Yang86974902017-03-01 14:03:51 -0800600 !(heap_value->IsInstanceFieldSet() || heap_value->IsArraySet())) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800601 return;
602 }
603 auto idx = std::find(possibly_removed_stores_.begin(),
604 possibly_removed_stores_.end(), heap_value);
605 if (idx != possibly_removed_stores_.end()) {
606 // Make sure the store is kept.
607 possibly_removed_stores_.erase(idx);
608 }
609 }
610
611 void HandleLoopSideEffects(HBasicBlock* block) {
612 DCHECK(block->IsLoopHeader());
613 int block_id = block->GetBlockId();
614 ArenaVector<HInstruction*>& heap_values = heap_values_for_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000615
616 // Don't eliminate loads in irreducible loops. This is safe for singletons, because
617 // they are always used by the non-eliminated loop-phi.
618 if (block->GetLoopInformation()->IsIrreducible()) {
619 if (kIsDebugBuild) {
620 for (size_t i = 0; i < heap_values.size(); i++) {
621 DCHECK_EQ(heap_values[i], kUnknownHeapValue);
622 }
623 }
624 return;
625 }
626
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800627 HBasicBlock* pre_header = block->GetLoopInformation()->GetPreHeader();
628 ArenaVector<HInstruction*>& pre_header_heap_values =
629 heap_values_for_[pre_header->GetBlockId()];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000630
Mingyao Yang803cbb92015-12-01 12:24:36 -0800631 // Inherit the values from pre-header.
632 for (size_t i = 0; i < heap_values.size(); i++) {
633 heap_values[i] = pre_header_heap_values[i];
634 }
635
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800636 // We do a single pass in reverse post order. For loops, use the side effects as a hint
637 // to see if the heap values should be killed.
638 if (side_effects_.GetLoopEffects(block).DoesAnyWrite()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800639 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800640 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
641 ReferenceInfo* ref_info = location->GetReferenceInfo();
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800642 if (ref_info->IsSingletonAndRemovable() &&
643 !location->IsValueKilledByLoopSideEffects()) {
644 // A removable singleton's field that's not stored into inside a loop is
645 // invariant throughout the loop. Nothing to do.
646 DCHECK(ref_info->IsSingletonAndRemovable());
647 } else {
648 // heap value is killed by loop side effects (stored into directly, or
649 // due to aliasing). Or the heap value may be needed after method return
650 // or deoptimization.
Mingyao Yang803cbb92015-12-01 12:24:36 -0800651 KeepIfIsStore(pre_header_heap_values[i]);
652 heap_values[i] = kUnknownHeapValue;
Mingyao Yang803cbb92015-12-01 12:24:36 -0800653 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800654 }
655 }
656 }
657
Mingyao Yang8df69d42015-10-22 15:40:58 -0700658 void MergePredecessorValues(HBasicBlock* block) {
659 const ArenaVector<HBasicBlock*>& predecessors = block->GetPredecessors();
660 if (predecessors.size() == 0) {
661 return;
662 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700663
Mingyao Yang8df69d42015-10-22 15:40:58 -0700664 ArenaVector<HInstruction*>& heap_values = heap_values_for_[block->GetBlockId()];
665 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700666 HInstruction* merged_value = nullptr;
667 // Whether merged_value is a result that's merged from all predecessors.
668 bool from_all_predecessors = true;
669 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
670 HInstruction* singleton_ref = nullptr;
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800671 if (ref_info->IsSingleton()) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700672 // We do more analysis of liveness when merging heap values for such
673 // cases since stores into such references may potentially be eliminated.
674 singleton_ref = ref_info->GetReference();
675 }
676
677 for (HBasicBlock* predecessor : predecessors) {
678 HInstruction* pred_value = heap_values_for_[predecessor->GetBlockId()][i];
679 if ((singleton_ref != nullptr) &&
680 !singleton_ref->GetBlock()->Dominates(predecessor)) {
681 // singleton_ref is not live in this predecessor. Skip this predecessor since
682 // it does not really have the location.
683 DCHECK_EQ(pred_value, kUnknownHeapValue);
684 from_all_predecessors = false;
685 continue;
686 }
687 if (merged_value == nullptr) {
688 // First seen heap value.
689 merged_value = pred_value;
690 } else if (pred_value != merged_value) {
691 // There are conflicting values.
692 merged_value = kUnknownHeapValue;
693 break;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700694 }
695 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800696
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800697 if (merged_value == kUnknownHeapValue || ref_info->IsSingletonAndNonRemovable()) {
698 // There are conflicting heap values from different predecessors,
699 // or the heap value may be needed after method return or deoptimization.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800700 // Keep the last store in each predecessor since future loads cannot be eliminated.
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700701 for (HBasicBlock* predecessor : predecessors) {
702 ArenaVector<HInstruction*>& pred_values = heap_values_for_[predecessor->GetBlockId()];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800703 KeepIfIsStore(pred_values[i]);
704 }
705 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700706
707 if ((merged_value == nullptr) || !from_all_predecessors) {
708 DCHECK(singleton_ref != nullptr);
709 DCHECK((singleton_ref->GetBlock() == block) ||
710 !singleton_ref->GetBlock()->Dominates(block));
711 // singleton_ref is not defined before block or defined only in some of its
712 // predecessors, so block doesn't really have the location at its entry.
713 heap_values[i] = kUnknownHeapValue;
714 } else {
715 heap_values[i] = merged_value;
716 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700717 }
718 }
719
720 // `instruction` is being removed. Try to see if the null check on it
721 // can be removed. This can happen if the same value is set in two branches
722 // but not in dominators. Such as:
723 // int[] a = foo();
724 // if () {
725 // a[0] = 2;
726 // } else {
727 // a[0] = 2;
728 // }
729 // // a[0] can now be replaced with constant 2, and the null check on it can be removed.
730 void TryRemovingNullCheck(HInstruction* instruction) {
731 HInstruction* prev = instruction->GetPrevious();
732 if ((prev != nullptr) && prev->IsNullCheck() && (prev == instruction->InputAt(0))) {
733 // Previous instruction is a null check for this instruction. Remove the null check.
734 prev->ReplaceWith(prev->InputAt(0));
735 prev->GetBlock()->RemoveInstruction(prev);
736 }
737 }
738
739 HInstruction* GetDefaultValue(Primitive::Type type) {
740 switch (type) {
741 case Primitive::kPrimNot:
742 return GetGraph()->GetNullConstant();
743 case Primitive::kPrimBoolean:
744 case Primitive::kPrimByte:
745 case Primitive::kPrimChar:
746 case Primitive::kPrimShort:
747 case Primitive::kPrimInt:
748 return GetGraph()->GetIntConstant(0);
749 case Primitive::kPrimLong:
750 return GetGraph()->GetLongConstant(0);
751 case Primitive::kPrimFloat:
752 return GetGraph()->GetFloatConstant(0);
753 case Primitive::kPrimDouble:
754 return GetGraph()->GetDoubleConstant(0);
755 default:
756 UNREACHABLE();
757 }
758 }
759
760 void VisitGetLocation(HInstruction* instruction,
761 HInstruction* ref,
762 size_t offset,
763 HInstruction* index,
764 int16_t declaring_class_def_index) {
765 HInstruction* original_ref = HuntForOriginalReference(ref);
766 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
767 size_t idx = heap_location_collector_.FindHeapLocationIndex(
768 ref_info, offset, index, declaring_class_def_index);
769 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
770 ArenaVector<HInstruction*>& heap_values =
771 heap_values_for_[instruction->GetBlock()->GetBlockId()];
772 HInstruction* heap_value = heap_values[idx];
773 if (heap_value == kDefaultHeapValue) {
774 HInstruction* constant = GetDefaultValue(instruction->GetType());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800775 removed_loads_.push_back(instruction);
776 substitute_instructions_for_loads_.push_back(constant);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700777 heap_values[idx] = constant;
778 return;
779 }
Mingyao Yang86974902017-03-01 14:03:51 -0800780 if (heap_value != kUnknownHeapValue) {
781 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
782 HInstruction* store = heap_value;
783 // This load must be from a singleton since it's from the same
784 // field/element that a "removed" store puts the value. That store
785 // must be to a singleton's field/element.
786 DCHECK(ref_info->IsSingleton());
787 // Get the real heap value of the store.
788 heap_value = heap_value->IsInstanceFieldSet() ? store->InputAt(1) : store->InputAt(2);
789 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800790 }
David Brazdil15693bf2015-12-16 10:30:45 +0000791 if (heap_value == kUnknownHeapValue) {
792 // Load isn't eliminated. Put the load as the value into the HeapLocation.
793 // This acts like GVN but with better aliasing analysis.
794 heap_values[idx] = instruction;
795 } else {
Nicolas Geoffray03971632016-03-17 10:44:24 +0000796 if (Primitive::PrimitiveKind(heap_value->GetType())
797 != Primitive::PrimitiveKind(instruction->GetType())) {
798 // The only situation where the same heap location has different type is when
Nicolas Geoffray65fef302016-05-04 14:00:12 +0100799 // we do an array get on an instruction that originates from the null constant
800 // (the null could be behind a field access, an array access, a null check or
801 // a bound type).
802 // In order to stay properly typed on primitive types, we do not eliminate
803 // the array gets.
Nicolas Geoffray03971632016-03-17 10:44:24 +0000804 if (kIsDebugBuild) {
805 DCHECK(heap_value->IsArrayGet()) << heap_value->DebugName();
806 DCHECK(instruction->IsArrayGet()) << instruction->DebugName();
Nicolas Geoffray03971632016-03-17 10:44:24 +0000807 }
808 return;
809 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800810 removed_loads_.push_back(instruction);
811 substitute_instructions_for_loads_.push_back(heap_value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700812 TryRemovingNullCheck(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700813 }
814 }
815
816 bool Equal(HInstruction* heap_value, HInstruction* value) {
817 if (heap_value == value) {
818 return true;
819 }
820 if (heap_value == kDefaultHeapValue && GetDefaultValue(value->GetType()) == value) {
821 return true;
822 }
823 return false;
824 }
825
826 void VisitSetLocation(HInstruction* instruction,
827 HInstruction* ref,
828 size_t offset,
829 HInstruction* index,
830 int16_t declaring_class_def_index,
831 HInstruction* value) {
832 HInstruction* original_ref = HuntForOriginalReference(ref);
833 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
834 size_t idx = heap_location_collector_.FindHeapLocationIndex(
835 ref_info, offset, index, declaring_class_def_index);
836 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
837 ArenaVector<HInstruction*>& heap_values =
838 heap_values_for_[instruction->GetBlock()->GetBlockId()];
839 HInstruction* heap_value = heap_values[idx];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800840 bool same_value = false;
841 bool possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700842 if (Equal(heap_value, value)) {
843 // Store into the heap location with the same value.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800844 same_value = true;
Mingyao Yang86974902017-03-01 14:03:51 -0800845 } else if (index != nullptr && ref_info->HasIndexAliasing()) {
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800846 // For array element, don't eliminate stores if the index can be aliased.
847 } else if (ref_info->IsSingleton()) {
848 // Store into a field of a singleton. The value cannot be killed due to
849 // aliasing/invocation. It can be redundant since future loads can
850 // directly get the value set by this instruction. The value can still be killed due to
851 // merging or loop side effects. Stores whose values are killed due to merging/loop side
852 // effects later will be removed from possibly_removed_stores_ when that is detected.
853 // Stores whose values may be needed after method return or deoptimization
854 // are also removed from possibly_removed_stores_ when that is detected.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800855 possibly_redundant = true;
856 HNewInstance* new_instance = ref_info->GetReference()->AsNewInstance();
Mingyao Yang86974902017-03-01 14:03:51 -0800857 if (new_instance != nullptr && new_instance->IsFinalizable()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800858 // Finalizable objects escape globally. Need to keep the store.
859 possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700860 } else {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800861 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
862 if (loop_info != nullptr) {
863 // instruction is a store in the loop so the loop must does write.
864 DCHECK(side_effects_.GetLoopEffects(loop_info->GetHeader()).DoesAnyWrite());
865
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800866 if (loop_info->IsDefinedOutOfTheLoop(original_ref)) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800867 DCHECK(original_ref->GetBlock()->Dominates(loop_info->GetPreHeader()));
868 // Keep the store since its value may be needed at the loop header.
869 possibly_redundant = false;
870 } else {
871 // The singleton is created inside the loop. Value stored to it isn't needed at
872 // the loop header. This is true for outer loops also.
873 }
874 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700875 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700876 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800877 if (same_value || possibly_redundant) {
878 possibly_removed_stores_.push_back(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700879 }
Mingyao Yange9d6e602015-10-23 17:08:42 -0700880
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800881 if (!same_value) {
882 if (possibly_redundant) {
Mingyao Yang86974902017-03-01 14:03:51 -0800883 DCHECK(instruction->IsInstanceFieldSet() || instruction->IsArraySet());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800884 // Put the store as the heap value. If the value is loaded from heap
885 // by a load later, this store isn't really redundant.
886 heap_values[idx] = instruction;
887 } else {
888 heap_values[idx] = value;
889 }
890 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700891 // This store may kill values in other heap locations due to aliasing.
892 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800893 if (i == idx) {
894 continue;
895 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700896 if (heap_values[i] == value) {
897 // Same value should be kept even if aliasing happens.
898 continue;
899 }
900 if (heap_values[i] == kUnknownHeapValue) {
901 // Value is already unknown, no need for aliasing check.
902 continue;
903 }
904 if (heap_location_collector_.MayAlias(i, idx)) {
905 // Kill heap locations that may alias.
906 heap_values[i] = kUnknownHeapValue;
907 }
908 }
909 }
910
911 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
912 HInstruction* obj = instruction->InputAt(0);
913 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
914 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
915 VisitGetLocation(instruction, obj, offset, nullptr, declaring_class_def_index);
916 }
917
918 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
919 HInstruction* obj = instruction->InputAt(0);
920 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
921 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
922 HInstruction* value = instruction->InputAt(1);
923 VisitSetLocation(instruction, obj, offset, nullptr, declaring_class_def_index, value);
924 }
925
926 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
927 HInstruction* cls = instruction->InputAt(0);
928 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
929 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
930 VisitGetLocation(instruction, cls, offset, nullptr, declaring_class_def_index);
931 }
932
933 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
934 HInstruction* cls = instruction->InputAt(0);
935 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
936 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
937 HInstruction* value = instruction->InputAt(1);
938 VisitSetLocation(instruction, cls, offset, nullptr, declaring_class_def_index, value);
939 }
940
941 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
942 HInstruction* array = instruction->InputAt(0);
943 HInstruction* index = instruction->InputAt(1);
944 VisitGetLocation(instruction,
945 array,
946 HeapLocation::kInvalidFieldOffset,
947 index,
948 HeapLocation::kDeclaringClassDefIndexForArrays);
949 }
950
951 void VisitArraySet(HArraySet* instruction) OVERRIDE {
952 HInstruction* array = instruction->InputAt(0);
953 HInstruction* index = instruction->InputAt(1);
954 HInstruction* value = instruction->InputAt(2);
955 VisitSetLocation(instruction,
956 array,
957 HeapLocation::kInvalidFieldOffset,
958 index,
959 HeapLocation::kDeclaringClassDefIndexForArrays,
960 value);
961 }
962
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800963 void VisitDeoptimize(HDeoptimize* instruction) {
964 const ArenaVector<HInstruction*>& heap_values =
965 heap_values_for_[instruction->GetBlock()->GetBlockId()];
966 for (HInstruction* heap_value : heap_values) {
967 // Filter out fake instructions before checking instruction kind below.
968 if (heap_value == kUnknownHeapValue || heap_value == kDefaultHeapValue) {
969 continue;
970 }
971 // A store is kept as the heap value for possibly removed stores.
972 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
973 // Check whether the reference for a store is used by an environment local of
974 // HDeoptimize.
975 HInstruction* reference = heap_value->InputAt(0);
976 DCHECK(heap_location_collector_.FindReferenceInfoOf(reference)->IsSingleton());
977 for (const HUseListNode<HEnvironment*>& use : reference->GetEnvUses()) {
978 HEnvironment* user = use.GetUser();
979 if (user->GetHolder() == instruction) {
980 // The singleton for the store is visible at this deoptimization
981 // point. Need to keep the store so that the heap value is
982 // seen by the interpreter.
983 KeepIfIsStore(heap_value);
984 }
985 }
986 }
987 }
988 }
989
Mingyao Yang8df69d42015-10-22 15:40:58 -0700990 void HandleInvoke(HInstruction* invoke) {
991 ArenaVector<HInstruction*>& heap_values =
992 heap_values_for_[invoke->GetBlock()->GetBlockId()];
993 for (size_t i = 0; i < heap_values.size(); i++) {
994 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
995 if (ref_info->IsSingleton()) {
996 // Singleton references cannot be seen by the callee.
997 } else {
998 heap_values[i] = kUnknownHeapValue;
999 }
1000 }
1001 }
1002
1003 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) OVERRIDE {
1004 HandleInvoke(invoke);
1005 }
1006
1007 void VisitInvokeVirtual(HInvokeVirtual* invoke) OVERRIDE {
1008 HandleInvoke(invoke);
1009 }
1010
1011 void VisitInvokeInterface(HInvokeInterface* invoke) OVERRIDE {
1012 HandleInvoke(invoke);
1013 }
1014
1015 void VisitInvokeUnresolved(HInvokeUnresolved* invoke) OVERRIDE {
1016 HandleInvoke(invoke);
1017 }
1018
Orion Hodsonac141392017-01-13 11:53:47 +00001019 void VisitInvokePolymorphic(HInvokePolymorphic* invoke) OVERRIDE {
1020 HandleInvoke(invoke);
1021 }
1022
Mingyao Yang8df69d42015-10-22 15:40:58 -07001023 void VisitClinitCheck(HClinitCheck* clinit) OVERRIDE {
1024 HandleInvoke(clinit);
1025 }
1026
1027 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* instruction) OVERRIDE {
1028 // Conservatively treat it as an invocation.
1029 HandleInvoke(instruction);
1030 }
1031
1032 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* instruction) OVERRIDE {
1033 // Conservatively treat it as an invocation.
1034 HandleInvoke(instruction);
1035 }
1036
1037 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* instruction) OVERRIDE {
1038 // Conservatively treat it as an invocation.
1039 HandleInvoke(instruction);
1040 }
1041
1042 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* instruction) OVERRIDE {
1043 // Conservatively treat it as an invocation.
1044 HandleInvoke(instruction);
1045 }
1046
1047 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
1048 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_instance);
1049 if (ref_info == nullptr) {
1050 // new_instance isn't used for field accesses. No need to process it.
1051 return;
1052 }
Aart Bik71bf7b42016-11-16 10:17:46 -08001053 if (ref_info->IsSingletonAndRemovable() &&
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001054 !new_instance->IsFinalizable() &&
Nicolas Geoffray5247c082017-01-13 14:17:29 +00001055 !new_instance->NeedsChecks()) {
Mingyao Yang062157f2016-03-02 10:15:36 -08001056 singleton_new_instances_.push_back(new_instance);
Mingyao Yang8df69d42015-10-22 15:40:58 -07001057 }
1058 ArenaVector<HInstruction*>& heap_values =
1059 heap_values_for_[new_instance->GetBlock()->GetBlockId()];
1060 for (size_t i = 0; i < heap_values.size(); i++) {
1061 HInstruction* ref =
1062 heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo()->GetReference();
1063 size_t offset = heap_location_collector_.GetHeapLocation(i)->GetOffset();
1064 if (ref == new_instance && offset >= mirror::kObjectHeaderSize) {
1065 // Instance fields except the header fields are set to default heap values.
1066 heap_values[i] = kDefaultHeapValue;
1067 }
1068 }
1069 }
1070
Mingyao Yang86974902017-03-01 14:03:51 -08001071 void VisitNewArray(HNewArray* new_array) OVERRIDE {
1072 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_array);
1073 if (ref_info == nullptr) {
1074 // new_array isn't used for array accesses. No need to process it.
1075 return;
1076 }
1077 if (ref_info->IsSingletonAndRemovable()) {
1078 singleton_new_arrays_.push_back(new_array);
1079 }
1080 ArenaVector<HInstruction*>& heap_values =
1081 heap_values_for_[new_array->GetBlock()->GetBlockId()];
1082 for (size_t i = 0; i < heap_values.size(); i++) {
1083 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
1084 HInstruction* ref = location->GetReferenceInfo()->GetReference();
1085 if (ref == new_array && location->GetIndex() != nullptr) {
1086 // Array elements are set to default heap values.
1087 heap_values[i] = kDefaultHeapValue;
1088 }
1089 }
1090 }
1091
Mingyao Yang8df69d42015-10-22 15:40:58 -07001092 // Find an instruction's substitute if it should be removed.
1093 // Return the same instruction if it should not be removed.
1094 HInstruction* FindSubstitute(HInstruction* instruction) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001095 size_t size = removed_loads_.size();
Mingyao Yang8df69d42015-10-22 15:40:58 -07001096 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001097 if (removed_loads_[i] == instruction) {
1098 return substitute_instructions_for_loads_[i];
Mingyao Yang8df69d42015-10-22 15:40:58 -07001099 }
1100 }
1101 return instruction;
1102 }
1103
1104 const HeapLocationCollector& heap_location_collector_;
1105 const SideEffectsAnalysis& side_effects_;
1106
1107 // One array of heap values for each block.
1108 ArenaVector<ArenaVector<HInstruction*>> heap_values_for_;
1109
1110 // We record the instructions that should be eliminated but may be
1111 // used by heap locations. They'll be removed in the end.
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001112 ArenaVector<HInstruction*> removed_loads_;
1113 ArenaVector<HInstruction*> substitute_instructions_for_loads_;
1114
1115 // Stores in this list may be removed from the list later when it's
1116 // found that the store cannot be eliminated.
1117 ArenaVector<HInstruction*> possibly_removed_stores_;
1118
Mingyao Yang8df69d42015-10-22 15:40:58 -07001119 ArenaVector<HInstruction*> singleton_new_instances_;
Mingyao Yang86974902017-03-01 14:03:51 -08001120 ArenaVector<HInstruction*> singleton_new_arrays_;
Mingyao Yang8df69d42015-10-22 15:40:58 -07001121
1122 DISALLOW_COPY_AND_ASSIGN(LSEVisitor);
1123};
1124
1125void LoadStoreElimination::Run() {
David Brazdil8993caf2015-12-07 10:04:40 +00001126 if (graph_->IsDebuggable() || graph_->HasTryCatch()) {
Mingyao Yang8df69d42015-10-22 15:40:58 -07001127 // Debugger may set heap values or trigger deoptimization of callers.
David Brazdil8993caf2015-12-07 10:04:40 +00001128 // Try/catch support not implemented yet.
Mingyao Yang8df69d42015-10-22 15:40:58 -07001129 // Skip this optimization.
1130 return;
1131 }
1132 HeapLocationCollector heap_location_collector(graph_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001133 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1134 heap_location_collector.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -07001135 }
1136 if (heap_location_collector.GetNumberOfHeapLocations() > kMaxNumberOfHeapLocations) {
1137 // Bail out if there are too many heap locations to deal with.
1138 return;
1139 }
1140 if (!heap_location_collector.HasHeapStores()) {
1141 // Without heap stores, this pass would act mostly as GVN on heap accesses.
1142 return;
1143 }
1144 if (heap_location_collector.HasVolatile() || heap_location_collector.HasMonitorOps()) {
1145 // Don't do load/store elimination if the method has volatile field accesses or
1146 // monitor operations, for now.
1147 // TODO: do it right.
1148 return;
1149 }
1150 heap_location_collector.BuildAliasingMatrix();
1151 LSEVisitor lse_visitor(graph_, heap_location_collector, side_effects_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001152 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1153 lse_visitor.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -07001154 }
1155 lse_visitor.RemoveInstructions();
1156}
1157
1158} // namespace art