-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
escape.cpp
5071 lines (4800 loc) · 193 KB
/
escape.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "ci/bcEscapeAnalyzer.hpp"
#include "compiler/compileLog.hpp"
#include "gc/shared/barrierSet.hpp"
#include "gc/shared/c2/barrierSetC2.hpp"
#include "libadt/vectset.hpp"
#include "memory/allocation.hpp"
#include "memory/resourceArea.hpp"
#include "opto/c2compiler.hpp"
#include "opto/arraycopynode.hpp"
#include "opto/callnode.hpp"
#include "opto/cfgnode.hpp"
#include "opto/compile.hpp"
#include "opto/escape.hpp"
#include "opto/macro.hpp"
#include "opto/locknode.hpp"
#include "opto/phaseX.hpp"
#include "opto/movenode.hpp"
#include "opto/narrowptrnode.hpp"
#include "opto/castnode.hpp"
#include "opto/rootnode.hpp"
#include "utilities/macros.hpp"
ConnectionGraph::ConnectionGraph(Compile * C, PhaseIterGVN *igvn, int invocation) :
// If ReduceAllocationMerges is enabled we might call split_through_phi during
// split_unique_types and that will create additional nodes that need to be
// pushed to the ConnectionGraph. The code below bumps the initial capacity of
// _nodes by 10% to account for these additional nodes. If capacity is exceeded
// the array will be reallocated.
_nodes(C->comp_arena(), C->do_reduce_allocation_merges() ? C->unique()*1.10 : C->unique(), C->unique(), nullptr),
_in_worklist(C->comp_arena()),
_next_pidx(0),
_collecting(true),
_verify(false),
_compile(C),
_igvn(igvn),
_invocation(invocation),
_build_iterations(0),
_build_time(0.),
_node_map(C->comp_arena()) {
// Add unknown java object.
add_java_object(C->top(), PointsToNode::GlobalEscape);
phantom_obj = ptnode_adr(C->top()->_idx)->as_JavaObject();
set_not_scalar_replaceable(phantom_obj NOT_PRODUCT(COMMA "Phantom object"));
// Add ConP and ConN null oop nodes
Node* oop_null = igvn->zerocon(T_OBJECT);
assert(oop_null->_idx < nodes_size(), "should be created already");
add_java_object(oop_null, PointsToNode::NoEscape);
null_obj = ptnode_adr(oop_null->_idx)->as_JavaObject();
set_not_scalar_replaceable(null_obj NOT_PRODUCT(COMMA "Null object"));
if (UseCompressedOops) {
Node* noop_null = igvn->zerocon(T_NARROWOOP);
assert(noop_null->_idx < nodes_size(), "should be created already");
map_ideal_node(noop_null, null_obj);
}
}
bool ConnectionGraph::has_candidates(Compile *C) {
// EA brings benefits only when the code has allocations and/or locks which
// are represented by ideal Macro nodes.
int cnt = C->macro_count();
for (int i = 0; i < cnt; i++) {
Node *n = C->macro_node(i);
if (n->is_Allocate()) {
return true;
}
if (n->is_Lock()) {
Node* obj = n->as_Lock()->obj_node()->uncast();
if (!(obj->is_Parm() || obj->is_Con())) {
return true;
}
}
if (n->is_CallStaticJava() &&
n->as_CallStaticJava()->is_boxing_method()) {
return true;
}
}
return false;
}
void ConnectionGraph::do_analysis(Compile *C, PhaseIterGVN *igvn) {
Compile::TracePhase tp("escapeAnalysis", &Phase::timers[Phase::_t_escapeAnalysis]);
ResourceMark rm;
// Add ConP and ConN null oop nodes before ConnectionGraph construction
// to create space for them in ConnectionGraph::_nodes[].
Node* oop_null = igvn->zerocon(T_OBJECT);
Node* noop_null = igvn->zerocon(T_NARROWOOP);
int invocation = 0;
if (C->congraph() != nullptr) {
invocation = C->congraph()->_invocation + 1;
}
ConnectionGraph* congraph = new(C->comp_arena()) ConnectionGraph(C, igvn, invocation);
// Perform escape analysis
if (congraph->compute_escape()) {
// There are non escaping objects.
C->set_congraph(congraph);
}
// Cleanup.
if (oop_null->outcnt() == 0) {
igvn->hash_delete(oop_null);
}
if (noop_null->outcnt() == 0) {
igvn->hash_delete(noop_null);
}
}
bool ConnectionGraph::compute_escape() {
Compile* C = _compile;
PhaseGVN* igvn = _igvn;
// Worklists used by EA.
Unique_Node_List delayed_worklist;
Unique_Node_List reducible_merges;
GrowableArray<Node*> alloc_worklist;
GrowableArray<Node*> ptr_cmp_worklist;
GrowableArray<MemBarStoreStoreNode*> storestore_worklist;
GrowableArray<ArrayCopyNode*> arraycopy_worklist;
GrowableArray<PointsToNode*> ptnodes_worklist;
GrowableArray<JavaObjectNode*> java_objects_worklist;
GrowableArray<JavaObjectNode*> non_escaped_allocs_worklist;
GrowableArray<FieldNode*> oop_fields_worklist;
GrowableArray<SafePointNode*> sfn_worklist;
GrowableArray<MergeMemNode*> mergemem_worklist;
DEBUG_ONLY( GrowableArray<Node*> addp_worklist; )
{ Compile::TracePhase tp("connectionGraph", &Phase::timers[Phase::_t_connectionGraph]);
// 1. Populate Connection Graph (CG) with PointsTo nodes.
ideal_nodes.map(C->live_nodes(), nullptr); // preallocate space
// Initialize worklist
if (C->root() != nullptr) {
ideal_nodes.push(C->root());
}
// Processed ideal nodes are unique on ideal_nodes list
// but several ideal nodes are mapped to the phantom_obj.
// To avoid duplicated entries on the following worklists
// add the phantom_obj only once to them.
ptnodes_worklist.append(phantom_obj);
java_objects_worklist.append(phantom_obj);
for( uint next = 0; next < ideal_nodes.size(); ++next ) {
Node* n = ideal_nodes.at(next);
// Create PointsTo nodes and add them to Connection Graph. Called
// only once per ideal node since ideal_nodes is Unique_Node list.
add_node_to_connection_graph(n, &delayed_worklist);
PointsToNode* ptn = ptnode_adr(n->_idx);
if (ptn != nullptr && ptn != phantom_obj) {
ptnodes_worklist.append(ptn);
if (ptn->is_JavaObject()) {
java_objects_worklist.append(ptn->as_JavaObject());
if ((n->is_Allocate() || n->is_CallStaticJava()) &&
(ptn->escape_state() < PointsToNode::GlobalEscape)) {
// Only allocations and java static calls results are interesting.
non_escaped_allocs_worklist.append(ptn->as_JavaObject());
}
} else if (ptn->is_Field() && ptn->as_Field()->is_oop()) {
oop_fields_worklist.append(ptn->as_Field());
}
}
// Collect some interesting nodes for further use.
switch (n->Opcode()) {
case Op_MergeMem:
// Collect all MergeMem nodes to add memory slices for
// scalar replaceable objects in split_unique_types().
mergemem_worklist.append(n->as_MergeMem());
break;
case Op_CmpP:
case Op_CmpN:
// Collect compare pointers nodes.
if (OptimizePtrCompare) {
ptr_cmp_worklist.append(n);
}
break;
case Op_MemBarStoreStore:
// Collect all MemBarStoreStore nodes so that depending on the
// escape status of the associated Allocate node some of them
// may be eliminated.
if (!UseStoreStoreForCtor || n->req() > MemBarNode::Precedent) {
storestore_worklist.append(n->as_MemBarStoreStore());
}
break;
case Op_MemBarRelease:
if (n->req() > MemBarNode::Precedent) {
record_for_optimizer(n);
}
break;
#ifdef ASSERT
case Op_AddP:
// Collect address nodes for graph verification.
addp_worklist.append(n);
break;
#endif
case Op_ArrayCopy:
// Keep a list of ArrayCopy nodes so if one of its input is non
// escaping, we can record a unique type
arraycopy_worklist.append(n->as_ArrayCopy());
break;
default:
// not interested now, ignore...
break;
}
for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
Node* m = n->fast_out(i); // Get user
ideal_nodes.push(m);
}
if (n->is_SafePoint()) {
sfn_worklist.append(n->as_SafePoint());
}
}
#ifndef PRODUCT
if (_compile->directive()->TraceEscapeAnalysisOption) {
tty->print("+++++ Initial worklist for ");
_compile->method()->print_name();
tty->print_cr(" (ea_inv=%d)", _invocation);
for (int i = 0; i < ptnodes_worklist.length(); i++) {
PointsToNode* ptn = ptnodes_worklist.at(i);
ptn->dump();
}
tty->print_cr("+++++ Calculating escape states and scalar replaceability");
}
#endif
if (non_escaped_allocs_worklist.length() == 0) {
_collecting = false;
NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
return false; // Nothing to do.
}
// Add final simple edges to graph.
while(delayed_worklist.size() > 0) {
Node* n = delayed_worklist.pop();
add_final_edges(n);
}
#ifdef ASSERT
if (VerifyConnectionGraph) {
// Verify that no new simple edges could be created and all
// local vars has edges.
_verify = true;
int ptnodes_length = ptnodes_worklist.length();
for (int next = 0; next < ptnodes_length; ++next) {
PointsToNode* ptn = ptnodes_worklist.at(next);
add_final_edges(ptn->ideal_node());
if (ptn->is_LocalVar() && ptn->edge_count() == 0) {
ptn->dump();
assert(ptn->as_LocalVar()->edge_count() > 0, "sanity");
}
}
_verify = false;
}
#endif
// Bytecode analyzer BCEscapeAnalyzer, used for Call nodes
// processing, calls to CI to resolve symbols (types, fields, methods)
// referenced in bytecode. During symbol resolution VM may throw
// an exception which CI cleans and converts to compilation failure.
if (C->failing()) {
NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
return false;
}
// 2. Finish Graph construction by propagating references to all
// java objects through graph.
if (!complete_connection_graph(ptnodes_worklist, non_escaped_allocs_worklist,
java_objects_worklist, oop_fields_worklist)) {
// All objects escaped or hit time or iterations limits.
_collecting = false;
NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
return false;
}
// 3. Adjust scalar_replaceable state of nonescaping objects and push
// scalar replaceable allocations on alloc_worklist for processing
// in split_unique_types().
GrowableArray<JavaObjectNode*> jobj_worklist;
int non_escaped_length = non_escaped_allocs_worklist.length();
bool found_nsr_alloc = false;
for (int next = 0; next < non_escaped_length; next++) {
JavaObjectNode* ptn = non_escaped_allocs_worklist.at(next);
bool noescape = (ptn->escape_state() == PointsToNode::NoEscape);
Node* n = ptn->ideal_node();
if (n->is_Allocate()) {
n->as_Allocate()->_is_non_escaping = noescape;
}
if (noescape && ptn->scalar_replaceable()) {
adjust_scalar_replaceable_state(ptn, reducible_merges);
if (ptn->scalar_replaceable()) {
jobj_worklist.push(ptn);
} else {
found_nsr_alloc = true;
}
}
}
// Propagate NSR (Not Scalar Replaceable) state.
if (found_nsr_alloc) {
find_scalar_replaceable_allocs(jobj_worklist);
}
// alloc_worklist will be processed in reverse push order.
// Therefore the reducible Phis will be processed for last and that's what we
// want because by then the scalarizable inputs of the merge will already have
// an unique instance type.
for (uint i = 0; i < reducible_merges.size(); i++ ) {
Node* n = reducible_merges.at(i);
alloc_worklist.append(n);
}
for (int next = 0; next < jobj_worklist.length(); ++next) {
JavaObjectNode* jobj = jobj_worklist.at(next);
if (jobj->scalar_replaceable()) {
alloc_worklist.append(jobj->ideal_node());
}
}
#ifdef ASSERT
if (VerifyConnectionGraph) {
// Verify that graph is complete - no new edges could be added or needed.
verify_connection_graph(ptnodes_worklist, non_escaped_allocs_worklist,
java_objects_worklist, addp_worklist);
}
assert(C->unique() == nodes_size(), "no new ideal nodes should be added during ConnectionGraph build");
assert(null_obj->escape_state() == PointsToNode::NoEscape &&
null_obj->edge_count() == 0 &&
!null_obj->arraycopy_src() &&
!null_obj->arraycopy_dst(), "sanity");
#endif
_collecting = false;
} // TracePhase t3("connectionGraph")
// 4. Optimize ideal graph based on EA information.
bool has_non_escaping_obj = (non_escaped_allocs_worklist.length() > 0);
if (has_non_escaping_obj) {
optimize_ideal_graph(ptr_cmp_worklist, storestore_worklist);
}
#ifndef PRODUCT
if (PrintEscapeAnalysis) {
dump(ptnodes_worklist); // Dump ConnectionGraph
}
#endif
#ifdef ASSERT
if (VerifyConnectionGraph) {
int alloc_length = alloc_worklist.length();
for (int next = 0; next < alloc_length; ++next) {
Node* n = alloc_worklist.at(next);
PointsToNode* ptn = ptnode_adr(n->_idx);
assert(ptn->escape_state() == PointsToNode::NoEscape && ptn->scalar_replaceable(), "sanity");
}
}
if (VerifyReduceAllocationMerges) {
for (uint i = 0; i < reducible_merges.size(); i++ ) {
Node* n = reducible_merges.at(i);
if (!can_reduce_phi(n->as_Phi())) {
TraceReduceAllocationMerges = true;
n->dump(2);
n->dump(-2);
assert(can_reduce_phi(n->as_Phi()), "Sanity: previous reducible Phi is no longer reducible before SUT.");
}
}
}
#endif
// 5. Separate memory graph for scalar replaceable allcations.
bool has_scalar_replaceable_candidates = (alloc_worklist.length() > 0);
if (has_scalar_replaceable_candidates && EliminateAllocations) {
assert(C->do_aliasing(), "Aliasing should be enabled");
// Now use the escape information to create unique types for
// scalar replaceable objects.
split_unique_types(alloc_worklist, arraycopy_worklist, mergemem_worklist, reducible_merges);
if (C->failing()) {
NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
return false;
}
C->print_method(PHASE_AFTER_EA, 2);
#ifdef ASSERT
} else if (Verbose && (PrintEscapeAnalysis || PrintEliminateAllocations)) {
tty->print("=== No allocations eliminated for ");
C->method()->print_short_name();
if (!EliminateAllocations) {
tty->print(" since EliminateAllocations is off ===");
} else if(!has_scalar_replaceable_candidates) {
tty->print(" since there are no scalar replaceable candidates ===");
}
tty->cr();
#endif
}
// 6. Reduce allocation merges used as debug information. This is done after
// split_unique_types because the methods used to create SafePointScalarObject
// need to traverse the memory graph to find values for object fields. We also
// set to null the scalarized inputs of reducible Phis so that the Allocate
// that they point can be later scalar replaced.
bool delay = _igvn->delay_transform();
_igvn->set_delay_transform(true);
for (uint i = 0; i < reducible_merges.size(); i++) {
Node* n = reducible_merges.at(i);
if (n->outcnt() > 0) {
if (!reduce_phi_on_safepoints(n->as_Phi())) {
NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
C->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
return false;
}
// Now we set the scalar replaceable inputs of ophi to null, which is
// the last piece that would prevent it from being scalar replaceable.
reset_scalar_replaceable_entries(n->as_Phi());
}
}
_igvn->set_delay_transform(delay);
// Annotate at safepoints if they have <= ArgEscape objects in their scope and at
// java calls if they pass ArgEscape objects as parameters.
if (has_non_escaping_obj &&
(C->env()->should_retain_local_variables() ||
C->env()->jvmti_can_get_owned_monitor_info() ||
C->env()->jvmti_can_walk_any_space() ||
DeoptimizeObjectsALot)) {
int sfn_length = sfn_worklist.length();
for (int next = 0; next < sfn_length; next++) {
SafePointNode* sfn = sfn_worklist.at(next);
sfn->set_has_ea_local_in_scope(has_ea_local_in_scope(sfn));
if (sfn->is_CallJava()) {
CallJavaNode* call = sfn->as_CallJava();
call->set_arg_escape(has_arg_escape(call));
}
}
}
NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
return has_non_escaping_obj;
}
// Check if it's profitable to reduce the Phi passed as parameter. Returns true
// if at least one scalar replaceable allocation participates in the merge.
bool ConnectionGraph::can_reduce_phi_check_inputs(PhiNode* ophi) const {
bool found_sr_allocate = false;
for (uint i = 1; i < ophi->req(); i++) {
JavaObjectNode* ptn = unique_java_object(ophi->in(i));
if (ptn != nullptr && ptn->scalar_replaceable()) {
AllocateNode* alloc = ptn->ideal_node()->as_Allocate();
// Don't handle arrays.
if (alloc->Opcode() != Op_Allocate) {
assert(alloc->Opcode() == Op_AllocateArray, "Unexpected type of allocation.");
continue;
}
if (PhaseMacroExpand::can_eliminate_allocation(_igvn, alloc, nullptr)) {
found_sr_allocate = true;
} else {
NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("%dth input of Phi %d is SR but can't be eliminated.", i, ophi->_idx);)
ptn->set_scalar_replaceable(false);
}
}
}
NOT_PRODUCT(if (TraceReduceAllocationMerges && !found_sr_allocate) tty->print_cr("Can NOT reduce Phi %d on invocation %d. No SR Allocate as input.", ophi->_idx, _invocation);)
return found_sr_allocate;
}
// We can reduce the Cmp if it's a comparison between the Phi and a constant.
// I require the 'other' input to be a constant so that I can move the Cmp
// around safely.
bool ConnectionGraph::can_reduce_cmp(Node* n, Node* cmp) const {
assert(cmp->Opcode() == Op_CmpP || cmp->Opcode() == Op_CmpN, "not expected node: %s", cmp->Name());
Node* left = cmp->in(1);
Node* right = cmp->in(2);
return (left == n || right == n) &&
(left->is_Con() || right->is_Con()) &&
cmp->outcnt() == 1;
}
// We are going to check if any of the SafePointScalarMerge entries
// in the SafePoint reference the Phi that we are checking.
bool ConnectionGraph::has_been_reduced(PhiNode* n, SafePointNode* sfpt) const {
JVMState *jvms = sfpt->jvms();
for (uint i = jvms->debug_start(); i < jvms->debug_end(); i++) {
Node* sfpt_in = sfpt->in(i);
if (sfpt_in->is_SafePointScalarMerge()) {
SafePointScalarMergeNode* smerge = sfpt_in->as_SafePointScalarMerge();
Node* nsr_ptr = sfpt->in(smerge->merge_pointer_idx(jvms));
if (nsr_ptr == n) {
return true;
}
}
}
return false;
}
// Check if we are able to untangle the merge. The following patterns are
// supported:
// - Phi -> SafePoints
// - Phi -> CmpP/N
// - Phi -> AddP -> Load
// - Phi -> CastPP -> SafePoints
// - Phi -> CastPP -> AddP -> Load
bool ConnectionGraph::can_reduce_check_users(Node* n, uint nesting) const {
for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
Node* use = n->fast_out(i);
if (use->is_SafePoint()) {
if (use->is_Call() && use->as_Call()->has_non_debug_use(n)) {
NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. Call has non_debug_use().", n->_idx, _invocation);)
return false;
} else if (has_been_reduced(n->is_Phi() ? n->as_Phi() : n->as_CastPP()->in(1)->as_Phi(), use->as_SafePoint())) {
NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. It has already been reduced.", n->_idx, _invocation);)
return false;
}
} else if (use->is_AddP()) {
Node* addp = use;
for (DUIterator_Fast jmax, j = addp->fast_outs(jmax); j < jmax; j++) {
Node* use_use = addp->fast_out(j);
const Type* load_type = _igvn->type(use_use);
if (!use_use->is_Load() || !use_use->as_Load()->can_split_through_phi_base(_igvn)) {
NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. AddP user isn't a [splittable] Load(): %s", n->_idx, _invocation, use_use->Name());)
return false;
} else if (load_type->isa_narrowklass() || load_type->isa_klassptr()) {
NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. [Narrow] Klass Load: %s", n->_idx, _invocation, use_use->Name());)
return false;
}
}
} else if (nesting > 0) {
NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. Unsupported user %s at nesting level %d.", n->_idx, _invocation, use->Name(), nesting);)
return false;
} else if (use->is_CastPP()) {
const Type* cast_t = _igvn->type(use);
if (cast_t == nullptr || cast_t->make_ptr()->isa_instptr() == nullptr) {
#ifndef PRODUCT
if (TraceReduceAllocationMerges) {
tty->print_cr("Can NOT reduce Phi %d on invocation %d. CastPP is not to an instance.", n->_idx, _invocation);
use->dump();
}
#endif
return false;
}
bool is_trivial_control = use->in(0) == nullptr || use->in(0) == n->in(0);
if (!is_trivial_control) {
// If it's not a trivial control then we check if we can reduce the
// CmpP/N used by the If controlling the cast.
if (use->in(0)->is_IfTrue() || use->in(0)->is_IfFalse()) {
Node* iff = use->in(0)->in(0);
if (iff->Opcode() == Op_If && iff->in(1)->is_Bool() && iff->in(1)->in(1)->is_Cmp()) {
Node* iff_cmp = iff->in(1)->in(1);
int opc = iff_cmp->Opcode();
if ((opc == Op_CmpP || opc == Op_CmpN) && !can_reduce_cmp(n, iff_cmp)) {
#ifndef PRODUCT
if (TraceReduceAllocationMerges) {
tty->print_cr("Can NOT reduce Phi %d on invocation %d. CastPP %d doesn't have simple control.", n->_idx, _invocation, use->_idx);
n->dump(5);
}
#endif
return false;
}
}
}
}
if (!can_reduce_check_users(use, nesting+1)) {
return false;
}
} else if (use->Opcode() == Op_CmpP || use->Opcode() == Op_CmpN) {
if (!can_reduce_cmp(n, use)) {
NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. CmpP/N %d isn't reducible.", n->_idx, _invocation, use->_idx);)
return false;
}
} else {
NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. One of the uses is: %d %s", n->_idx, _invocation, use->_idx, use->Name());)
return false;
}
}
return true;
}
// Returns true if: 1) It's profitable to reduce the merge, and 2) The Phi is
// only used in some certain code shapes. Check comments in
// 'can_reduce_phi_inputs' and 'can_reduce_phi_users' for more
// details.
bool ConnectionGraph::can_reduce_phi(PhiNode* ophi) const {
// If there was an error attempting to reduce allocation merges for this
// method we might have disabled the compilation and be retrying with RAM
// disabled.
if (!_compile->do_reduce_allocation_merges() || ophi->region()->Opcode() != Op_Region) {
return false;
}
const Type* phi_t = _igvn->type(ophi);
if (phi_t == nullptr ||
phi_t->make_ptr() == nullptr ||
phi_t->make_ptr()->isa_aryptr() != nullptr) {
return false;
}
if (!can_reduce_phi_check_inputs(ophi) || !can_reduce_check_users(ophi, /* nesting: */ 0)) {
return false;
}
NOT_PRODUCT(if (TraceReduceAllocationMerges) { tty->print_cr("Can reduce Phi %d during invocation %d: ", ophi->_idx, _invocation); })
return true;
}
// This method will return a CmpP/N that we need to use on the If controlling a
// CastPP after it was split. This method is only called on bases that are
// nullable therefore we always need a controlling if for the splitted CastPP.
//
// 'curr_ctrl' is the control of the CastPP that we want to split through phi.
// If the CastPP currently doesn't have a control then the CmpP/N will be
// against the NULL constant, otherwise it will be against the constant input of
// the existing CmpP/N. It's guaranteed that there will be a CmpP/N in the later
// case because we have constraints on it and because the CastPP has a control
// input.
Node* ConnectionGraph::specialize_cmp(Node* base, Node* curr_ctrl) {
const Type* t = base->bottom_type();
Node* con = nullptr;
if (curr_ctrl == nullptr || curr_ctrl->is_Region()) {
con = _igvn->zerocon(t->basic_type());
} else {
Node* curr_cmp = curr_ctrl->in(0)->in(1)->in(1); // true/false -> if -> bool -> cmp
con = curr_cmp->in(1)->is_Con() ? curr_cmp->in(1) : curr_cmp->in(2);
}
return CmpNode::make(base, con, t->basic_type());
}
// This method 'specializes' the CastPP passed as parameter to the base passed
// as parameter. Note that the existing CastPP input is a Phi. "Specialize"
// means that the CastPP now will be specific for a given base instead of a Phi.
// An If-Then-Else-Region block is inserted to control the CastPP. The control
// of the CastPP is a copy of the current one (if there is one) or a check
// against NULL.
//
// Before:
//
// C1 C2 ... Cn
// \ | /
// \ | /
// \ | /
// \ | /
// \ | /
// \ | /
// \|/
// Region B1 B2 ... Bn
// | \ | /
// | \ | /
// | \ | /
// | \ | /
// | \ | /
// | \ | /
// ---------------> Phi
// |
// X |
// | |
// | |
// ------> CastPP
//
// After (only partial illustration; base = B2, current_control = C2):
//
// C2
// |
// If
// / \
// / \
// T F
// /\ /
// / \ /
// / \ /
// C1 CastPP Reg Cn
// | | |
// | | |
// | | |
// -------------- | ----------
// | | |
// Region
//
Node* ConnectionGraph::specialize_castpp(Node* castpp, Node* base, Node* current_control) {
Node* control_successor = current_control->unique_ctrl_out();
Node* cmp = _igvn->transform(specialize_cmp(base, castpp->in(0)));
Node* bol = _igvn->transform(new BoolNode(cmp, BoolTest::ne));
IfNode* if_ne = _igvn->transform(new IfNode(current_control, bol, PROB_MIN, COUNT_UNKNOWN))->as_If();
Node* not_eq_control = _igvn->transform(new IfTrueNode(if_ne));
Node* yes_eq_control = _igvn->transform(new IfFalseNode(if_ne));
Node* end_region = _igvn->transform(new RegionNode(3));
// Insert the new if-else-region block into the graph
end_region->set_req(1, not_eq_control);
end_region->set_req(2, yes_eq_control);
control_successor->replace_edge(current_control, end_region, _igvn);
_igvn->_worklist.push(current_control);
_igvn->_worklist.push(control_successor);
return _igvn->transform(ConstraintCastNode::make_cast_for_type(not_eq_control, base, _igvn->type(castpp), ConstraintCastNode::UnconditionalDependency, nullptr));
}
Node* ConnectionGraph::split_castpp_load_through_phi(Node* curr_addp, Node* curr_load, Node* region, GrowableArray<Node*>* bases_for_loads, GrowableArray<Node *> &alloc_worklist) {
const Type* load_type = _igvn->type(curr_load);
Node* nsr_value = _igvn->zerocon(load_type->basic_type());
Node* memory = curr_load->in(MemNode::Memory);
// The data_phi merging the loads needs to be nullable if
// we are loading pointers.
if (load_type->make_ptr() != nullptr) {
if (load_type->isa_narrowoop()) {
load_type = load_type->meet(TypeNarrowOop::NULL_PTR);
} else if (load_type->isa_ptr()) {
load_type = load_type->meet(TypePtr::NULL_PTR);
} else {
assert(false, "Unexpected load ptr type.");
}
}
Node* data_phi = PhiNode::make(region, nsr_value, load_type);
for (int i = 1; i < bases_for_loads->length(); i++) {
Node* base = bases_for_loads->at(i);
Node* cmp_region = nullptr;
if (base != nullptr) {
if (base->is_CFG()) { // means that we added a CastPP as child of this CFG node
cmp_region = base->unique_ctrl_out_or_null();
assert(cmp_region != nullptr, "There should be.");
base = base->find_out_with(Op_CastPP);
}
Node* addr = _igvn->transform(new AddPNode(base, base, curr_addp->in(AddPNode::Offset)));
Node* mem = (memory->is_Phi() && (memory->in(0) == region)) ? memory->in(i) : memory;
Node* load = curr_load->clone();
load->set_req(0, nullptr);
load->set_req(1, mem);
load->set_req(2, addr);
if (cmp_region != nullptr) { // see comment on previous if
Node* intermediate_phi = PhiNode::make(cmp_region, nsr_value, load_type);
intermediate_phi->set_req(1, _igvn->transform(load));
load = intermediate_phi;
}
data_phi->set_req(i, _igvn->transform(load));
} else {
// Just use the default, which is already in phi
}
}
// Takes care of updating CG and split_unique_types worklists due
// to cloned AddP->Load.
updates_after_load_split(data_phi, curr_load, alloc_worklist);
return _igvn->transform(data_phi);
}
// This method only reduces CastPP fields loads; SafePoints are handled
// separately. The idea here is basically to clone the CastPP and place copies
// on each input of the Phi, including non-scalar replaceable inputs.
// Experimentation shows that the resulting IR graph is simpler that way than if
// we just split the cast through scalar-replaceable inputs.
//
// The reduction process requires that CastPP's control be one of:
// 1) no control,
// 2) the same region as Ophi, or
// 3) an IfTrue/IfFalse coming from an CmpP/N between Ophi and a constant.
//
// After splitting the CastPP we'll put it under an If-Then-Else-Region control
// flow. If the CastPP originally had an IfTrue/False control input then we'll
// use a similar CmpP/N to control the new If-Then-Else-Region. Otherwise, we'll
// juse use a CmpP/N against the NULL constant.
//
// The If-Then-Else-Region isn't always needed. For instance, if input to
// splitted cast was not nullable (or if it was the NULL constant) then we don't
// need (shouldn't) use a CastPP at all.
//
// After the casts are splitted we'll split the AddP->Loads through the Phi and
// connect them to the just split CastPPs.
//
// Before (CastPP control is same as Phi):
//
// Region Allocate Null Call
// | \ | /
// | \ | /
// | \ | /
// | \ | /
// | \ | /
// | \ | /
// ------------------> Phi # Oop Phi
// | |
// | |
// | |
// | |
// ----------------> CastPP
// |
// AddP
// |
// Load
//
// After (Very much simplified):
//
// Call NULL
// \ /
// CmpP
// |
// Bool#NE
// |
// If
// / \
// T F
// / \ /
// / R
// CastPP |
// | |
// AddP |
// | |
// Load |
// \ | 0
// Allocate \ | /
// \ \ | /
// AddP Phi
// \ /
// Load /
// \ 0 /
// \ | /
// \|/
// Phi # "Field" Phi
//
void ConnectionGraph::reduce_phi_on_castpp_field_load(Node* curr_castpp, GrowableArray<Node *> &alloc_worklist, GrowableArray<Node *> &memnode_worklist) {
Node* ophi = curr_castpp->in(1);
assert(ophi->is_Phi(), "Expected this to be a Phi node.");
// Identify which base should be used for AddP->Load later when spliting the
// CastPP->Loads through ophi. Three kind of values may be stored in this
// array, depending on the nullability status of the corresponding input in
// ophi.
//
// - nullptr: Meaning that the base is actually the NULL constant and therefore
// we won't try to load from it.
//
// - CFG Node: Meaning that the base is a CastPP that was specialized for
// this input of Ophi. I.e., we added an If->Then->Else-Region
// that will 'activate' the CastPp only when the input is not Null.
//
// - Other Node: Meaning that the base is not nullable and therefore we'll try
// to load directly from it.
GrowableArray<Node*> bases_for_loads(ophi->req(), ophi->req(), nullptr);
for (uint i = 1; i < ophi->req(); i++) {
Node* base = ophi->in(i);
const Type* base_t = _igvn->type(base);
if (base_t->maybe_null()) {
if (base->is_Con()) {
// Nothing todo as bases_for_loads[i] is already nullptr
} else {
Node* new_castpp = specialize_castpp(curr_castpp, base, ophi->in(0)->in(i));
bases_for_loads.at_put(i, new_castpp->in(0)); // Use the ctrl of the new node just as a flag
}
} else {
bases_for_loads.at_put(i, base);
}
}
// Now let's split the CastPP->Loads through the Phi
for (int i = curr_castpp->outcnt()-1; i >= 0;) {
Node* use = curr_castpp->raw_out(i);
if (use->is_AddP()) {
for (int j = use->outcnt()-1; j >= 0;) {
Node* use_use = use->raw_out(j);
assert(use_use->is_Load(), "Expected this to be a Load node.");
// We can't make an unconditional load from a nullable input. The
// 'split_castpp_load_through_phi` method will add an
// 'If-Then-Else-Region` around nullable bases and only load from them
// when the input is not null.
Node* phi = split_castpp_load_through_phi(use, use_use, ophi->in(0), &bases_for_loads, alloc_worklist);
_igvn->replace_node(use_use, phi);
--j;
j = MIN2(j, (int)use->outcnt()-1);
}
_igvn->remove_dead_node(use);
}
--i;
i = MIN2(i, (int)curr_castpp->outcnt()-1);
}
}
// This method split a given CmpP/N through the Phi used in one of its inputs.
// As a result we convert a comparison with a pointer to a comparison with an
// integer.
// The only requirement is that one of the inputs of the CmpP/N must be a Phi
// while the other must be a constant.
// The splitting process is basically just cloning the CmpP/N above the input
// Phi. However, some (most) of the cloned CmpP/Ns won't be requred because we
// can prove at compile time the result of the comparison.
//
// Before:
//
// in1 in2 ... inN
// \ | /
// \ | /
// \ | /
// \ | /
// \ | /
// \ | /
// Phi
// | Other
// | /
// | /
// | /
// CmpP/N
//
// After:
//
// in1 Other in2 Other inN Other
// | | | | | |
// \ | | | | |
// \ / | / | /
// CmpP/N CmpP/N CmpP/N
// Bool Bool Bool
// \ | /
// \ | /
// \ | /
// \ | /
// \ | /
// \ | /
// \ | /
// \ | /
// Phi
// |
// | Zero
// | /
// | /
// | /
// CmpI
//
//
void ConnectionGraph::reduce_phi_on_cmp(Node* cmp) {
Node* ophi = cmp->in(1)->is_Con() ? cmp->in(2) : cmp->in(1);
assert(ophi->is_Phi(), "Expected this to be a Phi node.");
Node* other = cmp->in(1)->is_Con() ? cmp->in(1) : cmp->in(2);
Node* zero = _igvn->intcon(0);
BoolTest::mask mask = cmp->unique_out()->as_Bool()->_test._test;
// This Phi will merge the result of the Cmps split through the Phi
Node* res_phi = _igvn->transform(PhiNode::make(ophi->in(0), zero, TypeInt::INT));
for (uint i=1; i<ophi->req(); i++) {
Node* ophi_input = ophi->in(i);
Node* res_phi_input = nullptr;
const TypeInt* tcmp = optimize_ptr_compare(ophi_input, other);
if (tcmp->singleton()) {
res_phi_input = _igvn->makecon(tcmp);
} else {
Node* ncmp = _igvn->transform(cmp->clone());
ncmp->set_req(1, ophi_input);
ncmp->set_req(2, other);
Node* bol = _igvn->transform(new BoolNode(ncmp, mask));
res_phi_input = bol->as_Bool()->as_int_value(_igvn);
}
res_phi->set_req(i, res_phi_input);
}
Node* new_cmp = _igvn->transform(new CmpINode(res_phi, zero));
_igvn->replace_node(cmp, new_cmp);