blob: 76c9d2324b4408d0f814083ad8aa5bff38d6a1dd [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 Murashkin79d8fa72017-04-18 09:37:23 -0700581 HConstructorFence::RemoveConstructorFences(new_array);
Igor Murashkind01745e2017-04-05 16:40:31 -0700582
Mingyao Yang86974902017-03-01 14:03:51 -0800583 if (!new_array->HasNonEnvironmentUses()) {
584 new_array->RemoveEnvironmentUsers();
585 new_array->GetBlock()->RemoveInstruction(new_array);
586 }
587 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700588 }
589
590 private:
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800591 // If heap_values[index] is an instance field store, need to keep the store.
592 // This is necessary if a heap value is killed due to merging, or loop side
593 // effects (which is essentially merging also), since a load later from the
594 // location won't be eliminated.
595 void KeepIfIsStore(HInstruction* heap_value) {
596 if (heap_value == kDefaultHeapValue ||
597 heap_value == kUnknownHeapValue ||
Mingyao Yang86974902017-03-01 14:03:51 -0800598 !(heap_value->IsInstanceFieldSet() || heap_value->IsArraySet())) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800599 return;
600 }
601 auto idx = std::find(possibly_removed_stores_.begin(),
602 possibly_removed_stores_.end(), heap_value);
603 if (idx != possibly_removed_stores_.end()) {
604 // Make sure the store is kept.
605 possibly_removed_stores_.erase(idx);
606 }
607 }
608
609 void HandleLoopSideEffects(HBasicBlock* block) {
610 DCHECK(block->IsLoopHeader());
611 int block_id = block->GetBlockId();
612 ArenaVector<HInstruction*>& heap_values = heap_values_for_[block_id];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000613
614 // Don't eliminate loads in irreducible loops. This is safe for singletons, because
615 // they are always used by the non-eliminated loop-phi.
616 if (block->GetLoopInformation()->IsIrreducible()) {
617 if (kIsDebugBuild) {
618 for (size_t i = 0; i < heap_values.size(); i++) {
619 DCHECK_EQ(heap_values[i], kUnknownHeapValue);
620 }
621 }
622 return;
623 }
624
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800625 HBasicBlock* pre_header = block->GetLoopInformation()->GetPreHeader();
626 ArenaVector<HInstruction*>& pre_header_heap_values =
627 heap_values_for_[pre_header->GetBlockId()];
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000628
Mingyao Yang803cbb92015-12-01 12:24:36 -0800629 // Inherit the values from pre-header.
630 for (size_t i = 0; i < heap_values.size(); i++) {
631 heap_values[i] = pre_header_heap_values[i];
632 }
633
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800634 // We do a single pass in reverse post order. For loops, use the side effects as a hint
635 // to see if the heap values should be killed.
636 if (side_effects_.GetLoopEffects(block).DoesAnyWrite()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800637 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang803cbb92015-12-01 12:24:36 -0800638 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
639 ReferenceInfo* ref_info = location->GetReferenceInfo();
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800640 if (ref_info->IsSingletonAndRemovable() &&
641 !location->IsValueKilledByLoopSideEffects()) {
642 // A removable singleton's field that's not stored into inside a loop is
643 // invariant throughout the loop. Nothing to do.
644 DCHECK(ref_info->IsSingletonAndRemovable());
645 } else {
646 // heap value is killed by loop side effects (stored into directly, or
647 // due to aliasing). Or the heap value may be needed after method return
648 // or deoptimization.
Mingyao Yang803cbb92015-12-01 12:24:36 -0800649 KeepIfIsStore(pre_header_heap_values[i]);
650 heap_values[i] = kUnknownHeapValue;
Mingyao Yang803cbb92015-12-01 12:24:36 -0800651 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800652 }
653 }
654 }
655
Mingyao Yang8df69d42015-10-22 15:40:58 -0700656 void MergePredecessorValues(HBasicBlock* block) {
657 const ArenaVector<HBasicBlock*>& predecessors = block->GetPredecessors();
658 if (predecessors.size() == 0) {
659 return;
660 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700661
Mingyao Yang8df69d42015-10-22 15:40:58 -0700662 ArenaVector<HInstruction*>& heap_values = heap_values_for_[block->GetBlockId()];
663 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700664 HInstruction* merged_value = nullptr;
665 // Whether merged_value is a result that's merged from all predecessors.
666 bool from_all_predecessors = true;
667 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
668 HInstruction* singleton_ref = nullptr;
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800669 if (ref_info->IsSingleton()) {
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700670 // We do more analysis of liveness when merging heap values for such
671 // cases since stores into such references may potentially be eliminated.
672 singleton_ref = ref_info->GetReference();
673 }
674
675 for (HBasicBlock* predecessor : predecessors) {
676 HInstruction* pred_value = heap_values_for_[predecessor->GetBlockId()][i];
677 if ((singleton_ref != nullptr) &&
678 !singleton_ref->GetBlock()->Dominates(predecessor)) {
679 // singleton_ref is not live in this predecessor. Skip this predecessor since
680 // it does not really have the location.
681 DCHECK_EQ(pred_value, kUnknownHeapValue);
682 from_all_predecessors = false;
683 continue;
684 }
685 if (merged_value == nullptr) {
686 // First seen heap value.
687 merged_value = pred_value;
688 } else if (pred_value != merged_value) {
689 // There are conflicting values.
690 merged_value = kUnknownHeapValue;
691 break;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700692 }
693 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800694
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800695 if (merged_value == kUnknownHeapValue || ref_info->IsSingletonAndNonRemovable()) {
696 // There are conflicting heap values from different predecessors,
697 // or the heap value may be needed after method return or deoptimization.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800698 // Keep the last store in each predecessor since future loads cannot be eliminated.
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700699 for (HBasicBlock* predecessor : predecessors) {
700 ArenaVector<HInstruction*>& pred_values = heap_values_for_[predecessor->GetBlockId()];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800701 KeepIfIsStore(pred_values[i]);
702 }
703 }
Mingyao Yang58d9bfc2016-11-01 13:31:58 -0700704
705 if ((merged_value == nullptr) || !from_all_predecessors) {
706 DCHECK(singleton_ref != nullptr);
707 DCHECK((singleton_ref->GetBlock() == block) ||
708 !singleton_ref->GetBlock()->Dominates(block));
709 // singleton_ref is not defined before block or defined only in some of its
710 // predecessors, so block doesn't really have the location at its entry.
711 heap_values[i] = kUnknownHeapValue;
712 } else {
713 heap_values[i] = merged_value;
714 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700715 }
716 }
717
718 // `instruction` is being removed. Try to see if the null check on it
719 // can be removed. This can happen if the same value is set in two branches
720 // but not in dominators. Such as:
721 // int[] a = foo();
722 // if () {
723 // a[0] = 2;
724 // } else {
725 // a[0] = 2;
726 // }
727 // // a[0] can now be replaced with constant 2, and the null check on it can be removed.
728 void TryRemovingNullCheck(HInstruction* instruction) {
729 HInstruction* prev = instruction->GetPrevious();
730 if ((prev != nullptr) && prev->IsNullCheck() && (prev == instruction->InputAt(0))) {
731 // Previous instruction is a null check for this instruction. Remove the null check.
732 prev->ReplaceWith(prev->InputAt(0));
733 prev->GetBlock()->RemoveInstruction(prev);
734 }
735 }
736
737 HInstruction* GetDefaultValue(Primitive::Type type) {
738 switch (type) {
739 case Primitive::kPrimNot:
740 return GetGraph()->GetNullConstant();
741 case Primitive::kPrimBoolean:
742 case Primitive::kPrimByte:
743 case Primitive::kPrimChar:
744 case Primitive::kPrimShort:
745 case Primitive::kPrimInt:
746 return GetGraph()->GetIntConstant(0);
747 case Primitive::kPrimLong:
748 return GetGraph()->GetLongConstant(0);
749 case Primitive::kPrimFloat:
750 return GetGraph()->GetFloatConstant(0);
751 case Primitive::kPrimDouble:
752 return GetGraph()->GetDoubleConstant(0);
753 default:
754 UNREACHABLE();
755 }
756 }
757
758 void VisitGetLocation(HInstruction* instruction,
759 HInstruction* ref,
760 size_t offset,
761 HInstruction* index,
762 int16_t declaring_class_def_index) {
763 HInstruction* original_ref = HuntForOriginalReference(ref);
764 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
765 size_t idx = heap_location_collector_.FindHeapLocationIndex(
766 ref_info, offset, index, declaring_class_def_index);
767 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
768 ArenaVector<HInstruction*>& heap_values =
769 heap_values_for_[instruction->GetBlock()->GetBlockId()];
770 HInstruction* heap_value = heap_values[idx];
771 if (heap_value == kDefaultHeapValue) {
772 HInstruction* constant = GetDefaultValue(instruction->GetType());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800773 removed_loads_.push_back(instruction);
774 substitute_instructions_for_loads_.push_back(constant);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700775 heap_values[idx] = constant;
776 return;
777 }
Mingyao Yang86974902017-03-01 14:03:51 -0800778 if (heap_value != kUnknownHeapValue) {
779 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
780 HInstruction* store = heap_value;
781 // This load must be from a singleton since it's from the same
782 // field/element that a "removed" store puts the value. That store
783 // must be to a singleton's field/element.
784 DCHECK(ref_info->IsSingleton());
785 // Get the real heap value of the store.
786 heap_value = heap_value->IsInstanceFieldSet() ? store->InputAt(1) : store->InputAt(2);
787 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800788 }
David Brazdil15693bf2015-12-16 10:30:45 +0000789 if (heap_value == kUnknownHeapValue) {
790 // Load isn't eliminated. Put the load as the value into the HeapLocation.
791 // This acts like GVN but with better aliasing analysis.
792 heap_values[idx] = instruction;
793 } else {
Nicolas Geoffray03971632016-03-17 10:44:24 +0000794 if (Primitive::PrimitiveKind(heap_value->GetType())
795 != Primitive::PrimitiveKind(instruction->GetType())) {
796 // The only situation where the same heap location has different type is when
Nicolas Geoffray65fef302016-05-04 14:00:12 +0100797 // we do an array get on an instruction that originates from the null constant
798 // (the null could be behind a field access, an array access, a null check or
799 // a bound type).
800 // In order to stay properly typed on primitive types, we do not eliminate
801 // the array gets.
Nicolas Geoffray03971632016-03-17 10:44:24 +0000802 if (kIsDebugBuild) {
803 DCHECK(heap_value->IsArrayGet()) << heap_value->DebugName();
804 DCHECK(instruction->IsArrayGet()) << instruction->DebugName();
Nicolas Geoffray03971632016-03-17 10:44:24 +0000805 }
806 return;
807 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800808 removed_loads_.push_back(instruction);
809 substitute_instructions_for_loads_.push_back(heap_value);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700810 TryRemovingNullCheck(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700811 }
812 }
813
814 bool Equal(HInstruction* heap_value, HInstruction* value) {
815 if (heap_value == value) {
816 return true;
817 }
818 if (heap_value == kDefaultHeapValue && GetDefaultValue(value->GetType()) == value) {
819 return true;
820 }
821 return false;
822 }
823
824 void VisitSetLocation(HInstruction* instruction,
825 HInstruction* ref,
826 size_t offset,
827 HInstruction* index,
828 int16_t declaring_class_def_index,
829 HInstruction* value) {
830 HInstruction* original_ref = HuntForOriginalReference(ref);
831 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(original_ref);
832 size_t idx = heap_location_collector_.FindHeapLocationIndex(
833 ref_info, offset, index, declaring_class_def_index);
834 DCHECK_NE(idx, HeapLocationCollector::kHeapLocationNotFound);
835 ArenaVector<HInstruction*>& heap_values =
836 heap_values_for_[instruction->GetBlock()->GetBlockId()];
837 HInstruction* heap_value = heap_values[idx];
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800838 bool same_value = false;
839 bool possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700840 if (Equal(heap_value, value)) {
841 // Store into the heap location with the same value.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800842 same_value = true;
Mingyao Yang86974902017-03-01 14:03:51 -0800843 } else if (index != nullptr && ref_info->HasIndexAliasing()) {
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800844 // For array element, don't eliminate stores if the index can be aliased.
845 } else if (ref_info->IsSingleton()) {
846 // Store into a field of a singleton. The value cannot be killed due to
847 // aliasing/invocation. It can be redundant since future loads can
848 // directly get the value set by this instruction. The value can still be killed due to
849 // merging or loop side effects. Stores whose values are killed due to merging/loop side
850 // effects later will be removed from possibly_removed_stores_ when that is detected.
851 // Stores whose values may be needed after method return or deoptimization
852 // are also removed from possibly_removed_stores_ when that is detected.
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800853 possibly_redundant = true;
854 HNewInstance* new_instance = ref_info->GetReference()->AsNewInstance();
Mingyao Yang86974902017-03-01 14:03:51 -0800855 if (new_instance != nullptr && new_instance->IsFinalizable()) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800856 // Finalizable objects escape globally. Need to keep the store.
857 possibly_redundant = false;
Mingyao Yang8df69d42015-10-22 15:40:58 -0700858 } else {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800859 HLoopInformation* loop_info = instruction->GetBlock()->GetLoopInformation();
860 if (loop_info != nullptr) {
861 // instruction is a store in the loop so the loop must does write.
862 DCHECK(side_effects_.GetLoopEffects(loop_info->GetHeader()).DoesAnyWrite());
863
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800864 if (loop_info->IsDefinedOutOfTheLoop(original_ref)) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800865 DCHECK(original_ref->GetBlock()->Dominates(loop_info->GetPreHeader()));
866 // Keep the store since its value may be needed at the loop header.
867 possibly_redundant = false;
868 } else {
869 // The singleton is created inside the loop. Value stored to it isn't needed at
870 // the loop header. This is true for outer loops also.
871 }
872 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700873 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700874 }
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800875 if (same_value || possibly_redundant) {
876 possibly_removed_stores_.push_back(instruction);
Mingyao Yang8df69d42015-10-22 15:40:58 -0700877 }
Mingyao Yange9d6e602015-10-23 17:08:42 -0700878
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800879 if (!same_value) {
880 if (possibly_redundant) {
Mingyao Yang86974902017-03-01 14:03:51 -0800881 DCHECK(instruction->IsInstanceFieldSet() || instruction->IsArraySet());
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800882 // Put the store as the heap value. If the value is loaded from heap
883 // by a load later, this store isn't really redundant.
884 heap_values[idx] = instruction;
885 } else {
886 heap_values[idx] = value;
887 }
888 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700889 // This store may kill values in other heap locations due to aliasing.
890 for (size_t i = 0; i < heap_values.size(); i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -0800891 if (i == idx) {
892 continue;
893 }
Mingyao Yang8df69d42015-10-22 15:40:58 -0700894 if (heap_values[i] == value) {
895 // Same value should be kept even if aliasing happens.
896 continue;
897 }
898 if (heap_values[i] == kUnknownHeapValue) {
899 // Value is already unknown, no need for aliasing check.
900 continue;
901 }
902 if (heap_location_collector_.MayAlias(i, idx)) {
903 // Kill heap locations that may alias.
904 heap_values[i] = kUnknownHeapValue;
905 }
906 }
907 }
908
909 void VisitInstanceFieldGet(HInstanceFieldGet* instruction) OVERRIDE {
910 HInstruction* obj = instruction->InputAt(0);
911 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
912 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
913 VisitGetLocation(instruction, obj, offset, nullptr, declaring_class_def_index);
914 }
915
916 void VisitInstanceFieldSet(HInstanceFieldSet* instruction) OVERRIDE {
917 HInstruction* obj = instruction->InputAt(0);
918 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
919 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
920 HInstruction* value = instruction->InputAt(1);
921 VisitSetLocation(instruction, obj, offset, nullptr, declaring_class_def_index, value);
922 }
923
924 void VisitStaticFieldGet(HStaticFieldGet* instruction) OVERRIDE {
925 HInstruction* cls = instruction->InputAt(0);
926 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
927 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
928 VisitGetLocation(instruction, cls, offset, nullptr, declaring_class_def_index);
929 }
930
931 void VisitStaticFieldSet(HStaticFieldSet* instruction) OVERRIDE {
932 HInstruction* cls = instruction->InputAt(0);
933 size_t offset = instruction->GetFieldInfo().GetFieldOffset().SizeValue();
934 int16_t declaring_class_def_index = instruction->GetFieldInfo().GetDeclaringClassDefIndex();
935 HInstruction* value = instruction->InputAt(1);
936 VisitSetLocation(instruction, cls, offset, nullptr, declaring_class_def_index, value);
937 }
938
939 void VisitArrayGet(HArrayGet* instruction) OVERRIDE {
940 HInstruction* array = instruction->InputAt(0);
941 HInstruction* index = instruction->InputAt(1);
942 VisitGetLocation(instruction,
943 array,
944 HeapLocation::kInvalidFieldOffset,
945 index,
946 HeapLocation::kDeclaringClassDefIndexForArrays);
947 }
948
949 void VisitArraySet(HArraySet* instruction) OVERRIDE {
950 HInstruction* array = instruction->InputAt(0);
951 HInstruction* index = instruction->InputAt(1);
952 HInstruction* value = instruction->InputAt(2);
953 VisitSetLocation(instruction,
954 array,
955 HeapLocation::kInvalidFieldOffset,
956 index,
957 HeapLocation::kDeclaringClassDefIndexForArrays,
958 value);
959 }
960
Mingyao Yangeb2d2d346e2017-03-02 13:26:17 -0800961 void VisitDeoptimize(HDeoptimize* instruction) {
962 const ArenaVector<HInstruction*>& heap_values =
963 heap_values_for_[instruction->GetBlock()->GetBlockId()];
964 for (HInstruction* heap_value : heap_values) {
965 // Filter out fake instructions before checking instruction kind below.
966 if (heap_value == kUnknownHeapValue || heap_value == kDefaultHeapValue) {
967 continue;
968 }
969 // A store is kept as the heap value for possibly removed stores.
970 if (heap_value->IsInstanceFieldSet() || heap_value->IsArraySet()) {
971 // Check whether the reference for a store is used by an environment local of
972 // HDeoptimize.
973 HInstruction* reference = heap_value->InputAt(0);
974 DCHECK(heap_location_collector_.FindReferenceInfoOf(reference)->IsSingleton());
975 for (const HUseListNode<HEnvironment*>& use : reference->GetEnvUses()) {
976 HEnvironment* user = use.GetUser();
977 if (user->GetHolder() == instruction) {
978 // The singleton for the store is visible at this deoptimization
979 // point. Need to keep the store so that the heap value is
980 // seen by the interpreter.
981 KeepIfIsStore(heap_value);
982 }
983 }
984 }
985 }
986 }
987
Mingyao Yang8df69d42015-10-22 15:40:58 -0700988 void HandleInvoke(HInstruction* invoke) {
989 ArenaVector<HInstruction*>& heap_values =
990 heap_values_for_[invoke->GetBlock()->GetBlockId()];
991 for (size_t i = 0; i < heap_values.size(); i++) {
992 ReferenceInfo* ref_info = heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo();
993 if (ref_info->IsSingleton()) {
994 // Singleton references cannot be seen by the callee.
995 } else {
996 heap_values[i] = kUnknownHeapValue;
997 }
998 }
999 }
1000
1001 void VisitInvokeStaticOrDirect(HInvokeStaticOrDirect* invoke) OVERRIDE {
1002 HandleInvoke(invoke);
1003 }
1004
1005 void VisitInvokeVirtual(HInvokeVirtual* invoke) OVERRIDE {
1006 HandleInvoke(invoke);
1007 }
1008
1009 void VisitInvokeInterface(HInvokeInterface* invoke) OVERRIDE {
1010 HandleInvoke(invoke);
1011 }
1012
1013 void VisitInvokeUnresolved(HInvokeUnresolved* invoke) OVERRIDE {
1014 HandleInvoke(invoke);
1015 }
1016
Orion Hodsonac141392017-01-13 11:53:47 +00001017 void VisitInvokePolymorphic(HInvokePolymorphic* invoke) OVERRIDE {
1018 HandleInvoke(invoke);
1019 }
1020
Mingyao Yang8df69d42015-10-22 15:40:58 -07001021 void VisitClinitCheck(HClinitCheck* clinit) OVERRIDE {
1022 HandleInvoke(clinit);
1023 }
1024
1025 void VisitUnresolvedInstanceFieldGet(HUnresolvedInstanceFieldGet* instruction) OVERRIDE {
1026 // Conservatively treat it as an invocation.
1027 HandleInvoke(instruction);
1028 }
1029
1030 void VisitUnresolvedInstanceFieldSet(HUnresolvedInstanceFieldSet* instruction) OVERRIDE {
1031 // Conservatively treat it as an invocation.
1032 HandleInvoke(instruction);
1033 }
1034
1035 void VisitUnresolvedStaticFieldGet(HUnresolvedStaticFieldGet* instruction) OVERRIDE {
1036 // Conservatively treat it as an invocation.
1037 HandleInvoke(instruction);
1038 }
1039
1040 void VisitUnresolvedStaticFieldSet(HUnresolvedStaticFieldSet* instruction) OVERRIDE {
1041 // Conservatively treat it as an invocation.
1042 HandleInvoke(instruction);
1043 }
1044
1045 void VisitNewInstance(HNewInstance* new_instance) OVERRIDE {
1046 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_instance);
1047 if (ref_info == nullptr) {
1048 // new_instance isn't used for field accesses. No need to process it.
1049 return;
1050 }
Aart Bik71bf7b42016-11-16 10:17:46 -08001051 if (ref_info->IsSingletonAndRemovable() &&
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001052 !new_instance->IsFinalizable() &&
Nicolas Geoffray5247c082017-01-13 14:17:29 +00001053 !new_instance->NeedsChecks()) {
Mingyao Yang062157f2016-03-02 10:15:36 -08001054 singleton_new_instances_.push_back(new_instance);
Mingyao Yang8df69d42015-10-22 15:40:58 -07001055 }
1056 ArenaVector<HInstruction*>& heap_values =
1057 heap_values_for_[new_instance->GetBlock()->GetBlockId()];
1058 for (size_t i = 0; i < heap_values.size(); i++) {
1059 HInstruction* ref =
1060 heap_location_collector_.GetHeapLocation(i)->GetReferenceInfo()->GetReference();
1061 size_t offset = heap_location_collector_.GetHeapLocation(i)->GetOffset();
1062 if (ref == new_instance && offset >= mirror::kObjectHeaderSize) {
1063 // Instance fields except the header fields are set to default heap values.
1064 heap_values[i] = kDefaultHeapValue;
1065 }
1066 }
1067 }
1068
Mingyao Yang86974902017-03-01 14:03:51 -08001069 void VisitNewArray(HNewArray* new_array) OVERRIDE {
1070 ReferenceInfo* ref_info = heap_location_collector_.FindReferenceInfoOf(new_array);
1071 if (ref_info == nullptr) {
1072 // new_array isn't used for array accesses. No need to process it.
1073 return;
1074 }
1075 if (ref_info->IsSingletonAndRemovable()) {
1076 singleton_new_arrays_.push_back(new_array);
1077 }
1078 ArenaVector<HInstruction*>& heap_values =
1079 heap_values_for_[new_array->GetBlock()->GetBlockId()];
1080 for (size_t i = 0; i < heap_values.size(); i++) {
1081 HeapLocation* location = heap_location_collector_.GetHeapLocation(i);
1082 HInstruction* ref = location->GetReferenceInfo()->GetReference();
1083 if (ref == new_array && location->GetIndex() != nullptr) {
1084 // Array elements are set to default heap values.
1085 heap_values[i] = kDefaultHeapValue;
1086 }
1087 }
1088 }
1089
Mingyao Yang8df69d42015-10-22 15:40:58 -07001090 // Find an instruction's substitute if it should be removed.
1091 // Return the same instruction if it should not be removed.
1092 HInstruction* FindSubstitute(HInstruction* instruction) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001093 size_t size = removed_loads_.size();
Mingyao Yang8df69d42015-10-22 15:40:58 -07001094 for (size_t i = 0; i < size; i++) {
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001095 if (removed_loads_[i] == instruction) {
1096 return substitute_instructions_for_loads_[i];
Mingyao Yang8df69d42015-10-22 15:40:58 -07001097 }
1098 }
1099 return instruction;
1100 }
1101
1102 const HeapLocationCollector& heap_location_collector_;
1103 const SideEffectsAnalysis& side_effects_;
1104
1105 // One array of heap values for each block.
1106 ArenaVector<ArenaVector<HInstruction*>> heap_values_for_;
1107
1108 // We record the instructions that should be eliminated but may be
1109 // used by heap locations. They'll be removed in the end.
Mingyao Yangfb8464a2015-11-02 10:56:59 -08001110 ArenaVector<HInstruction*> removed_loads_;
1111 ArenaVector<HInstruction*> substitute_instructions_for_loads_;
1112
1113 // Stores in this list may be removed from the list later when it's
1114 // found that the store cannot be eliminated.
1115 ArenaVector<HInstruction*> possibly_removed_stores_;
1116
Mingyao Yang8df69d42015-10-22 15:40:58 -07001117 ArenaVector<HInstruction*> singleton_new_instances_;
Mingyao Yang86974902017-03-01 14:03:51 -08001118 ArenaVector<HInstruction*> singleton_new_arrays_;
Mingyao Yang8df69d42015-10-22 15:40:58 -07001119
1120 DISALLOW_COPY_AND_ASSIGN(LSEVisitor);
1121};
1122
1123void LoadStoreElimination::Run() {
David Brazdil8993caf2015-12-07 10:04:40 +00001124 if (graph_->IsDebuggable() || graph_->HasTryCatch()) {
Mingyao Yang8df69d42015-10-22 15:40:58 -07001125 // Debugger may set heap values or trigger deoptimization of callers.
David Brazdil8993caf2015-12-07 10:04:40 +00001126 // Try/catch support not implemented yet.
Mingyao Yang8df69d42015-10-22 15:40:58 -07001127 // Skip this optimization.
1128 return;
1129 }
1130 HeapLocationCollector heap_location_collector(graph_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001131 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1132 heap_location_collector.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -07001133 }
1134 if (heap_location_collector.GetNumberOfHeapLocations() > kMaxNumberOfHeapLocations) {
1135 // Bail out if there are too many heap locations to deal with.
1136 return;
1137 }
1138 if (!heap_location_collector.HasHeapStores()) {
1139 // Without heap stores, this pass would act mostly as GVN on heap accesses.
1140 return;
1141 }
1142 if (heap_location_collector.HasVolatile() || heap_location_collector.HasMonitorOps()) {
1143 // Don't do load/store elimination if the method has volatile field accesses or
1144 // monitor operations, for now.
1145 // TODO: do it right.
1146 return;
1147 }
1148 heap_location_collector.BuildAliasingMatrix();
1149 LSEVisitor lse_visitor(graph_, heap_location_collector, side_effects_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001150 for (HBasicBlock* block : graph_->GetReversePostOrder()) {
1151 lse_visitor.VisitBasicBlock(block);
Mingyao Yang8df69d42015-10-22 15:40:58 -07001152 }
1153 lse_visitor.RemoveInstructions();
1154}
1155
1156} // namespace art