1 /*
2 * Copyright (c) 2005, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "ci/bcEscapeAnalyzer.hpp"
26 #include "compiler/compileLog.hpp"
27 #include "gc/shared/barrierSet.hpp"
28 #include "gc/shared/c2/barrierSetC2.hpp"
29 #include "libadt/vectset.hpp"
30 #include "memory/allocation.hpp"
31 #include "memory/resourceArea.hpp"
32 #include "opto/arraycopynode.hpp"
33 #include "opto/c2compiler.hpp"
34 #include "opto/callnode.hpp"
35 #include "opto/castnode.hpp"
36 #include "opto/cfgnode.hpp"
37 #include "opto/compile.hpp"
38 #include "opto/escape.hpp"
39 #include "opto/locknode.hpp"
40 #include "opto/macro.hpp"
41 #include "opto/movenode.hpp"
42 #include "opto/narrowptrnode.hpp"
43 #include "opto/phaseX.hpp"
44 #include "opto/rootnode.hpp"
45 #include "utilities/macros.hpp"
46
47 ConnectionGraph::ConnectionGraph(Compile * C, PhaseIterGVN *igvn, int invocation) :
48 // If ReduceAllocationMerges is enabled we might call split_through_phi during
49 // split_unique_types and that will create additional nodes that need to be
50 // pushed to the ConnectionGraph. The code below bumps the initial capacity of
51 // _nodes by 10% to account for these additional nodes. If capacity is exceeded
52 // the array will be reallocated.
53 _nodes(C->comp_arena(), C->do_reduce_allocation_merges() ? C->unique()*1.10 : C->unique(), C->unique(), nullptr),
54 _in_worklist(C->comp_arena()),
55 _next_pidx(0),
56 _collecting(true),
57 _verify(false),
58 _compile(C),
59 _igvn(igvn),
60 _invocation(invocation),
61 _build_iterations(0),
62 _build_time(0.),
63 _node_map(C->comp_arena()) {
64 // Add unknown java object.
65 add_java_object(C->top(), PointsToNode::GlobalEscape);
66 phantom_obj = ptnode_adr(C->top()->_idx)->as_JavaObject();
67 set_not_scalar_replaceable(phantom_obj NOT_PRODUCT(COMMA "Phantom object"));
68 // Add ConP and ConN null oop nodes
69 Node* oop_null = igvn->zerocon(T_OBJECT);
70 assert(oop_null->_idx < nodes_size(), "should be created already");
71 add_java_object(oop_null, PointsToNode::NoEscape);
72 null_obj = ptnode_adr(oop_null->_idx)->as_JavaObject();
73 set_not_scalar_replaceable(null_obj NOT_PRODUCT(COMMA "Null object"));
74 if (UseCompressedOops) {
75 Node* noop_null = igvn->zerocon(T_NARROWOOP);
76 assert(noop_null->_idx < nodes_size(), "should be created already");
77 map_ideal_node(noop_null, null_obj);
78 }
79 }
80
81 bool ConnectionGraph::has_candidates(Compile *C) {
82 // EA brings benefits only when the code has allocations and/or locks which
83 // are represented by ideal Macro nodes.
84 int cnt = C->macro_count();
85 for (int i = 0; i < cnt; i++) {
86 Node *n = C->macro_node(i);
87 if (n->is_Allocate()) {
88 return true;
89 }
90 if (n->is_Lock()) {
91 Node* obj = n->as_Lock()->obj_node()->uncast();
92 if (!(obj->is_Parm() || obj->is_Con())) {
93 return true;
94 }
95 }
96 if (n->is_CallStaticJava() &&
97 n->as_CallStaticJava()->is_boxing_method()) {
98 return true;
99 }
100 }
101 return false;
102 }
103
104 void ConnectionGraph::do_analysis(Compile *C, PhaseIterGVN *igvn) {
105 Compile::TracePhase tp(Phase::_t_escapeAnalysis);
106 ResourceMark rm;
107
108 // Add ConP and ConN null oop nodes before ConnectionGraph construction
109 // to create space for them in ConnectionGraph::_nodes[].
110 Node* oop_null = igvn->zerocon(T_OBJECT);
111 Node* noop_null = igvn->zerocon(T_NARROWOOP);
112 int invocation = 0;
113 if (C->congraph() != nullptr) {
114 invocation = C->congraph()->_invocation + 1;
115 }
116 ConnectionGraph* congraph = new(C->comp_arena()) ConnectionGraph(C, igvn, invocation);
117 NOT_PRODUCT(if (C->should_print_igv(/* Any level */ 1)) C->igv_printer()->set_congraph(congraph);)
118 // Perform escape analysis
119 if (congraph->compute_escape()) {
120 // There are non escaping objects.
121 C->set_congraph(congraph);
122 }
123 NOT_PRODUCT(if (C->should_print_igv(/* Any level */ 1)) C->igv_printer()->set_congraph(nullptr);)
124 // Cleanup.
125 if (oop_null->outcnt() == 0) {
126 igvn->hash_delete(oop_null);
127 }
128 if (noop_null->outcnt() == 0) {
129 igvn->hash_delete(noop_null);
130 }
131
132 C->print_method(PHASE_AFTER_EA, 2);
133 }
134
135 bool ConnectionGraph::compute_escape() {
136 Compile* C = _compile;
137 PhaseGVN* igvn = _igvn;
138
139 // Worklists used by EA.
140 Unique_Node_List delayed_worklist;
141 Unique_Node_List reducible_merges;
142 GrowableArray<Node*> alloc_worklist;
143 GrowableArray<Node*> ptr_cmp_worklist;
144 GrowableArray<MemBarStoreStoreNode*> storestore_worklist;
145 GrowableArray<ArrayCopyNode*> arraycopy_worklist;
146 GrowableArray<PointsToNode*> ptnodes_worklist;
147 GrowableArray<JavaObjectNode*> java_objects_worklist;
148 GrowableArray<JavaObjectNode*> non_escaped_allocs_worklist;
149 GrowableArray<FieldNode*> oop_fields_worklist;
150 GrowableArray<SafePointNode*> sfn_worklist;
151 GrowableArray<MergeMemNode*> mergemem_worklist;
152 DEBUG_ONLY( GrowableArray<Node*> addp_worklist; )
153
154 { Compile::TracePhase tp(Phase::_t_connectionGraph);
155
156 // 1. Populate Connection Graph (CG) with PointsTo nodes.
157 ideal_nodes.map(C->live_nodes(), nullptr); // preallocate space
158 // Initialize worklist
159 if (C->root() != nullptr) {
160 ideal_nodes.push(C->root());
161 }
162 // Processed ideal nodes are unique on ideal_nodes list
163 // but several ideal nodes are mapped to the phantom_obj.
164 // To avoid duplicated entries on the following worklists
165 // add the phantom_obj only once to them.
166 ptnodes_worklist.append(phantom_obj);
167 java_objects_worklist.append(phantom_obj);
168 for( uint next = 0; next < ideal_nodes.size(); ++next ) {
169 Node* n = ideal_nodes.at(next);
170 // Create PointsTo nodes and add them to Connection Graph. Called
171 // only once per ideal node since ideal_nodes is Unique_Node list.
172 add_node_to_connection_graph(n, &delayed_worklist);
173 PointsToNode* ptn = ptnode_adr(n->_idx);
174 if (ptn != nullptr && ptn != phantom_obj) {
175 ptnodes_worklist.append(ptn);
176 if (ptn->is_JavaObject()) {
177 java_objects_worklist.append(ptn->as_JavaObject());
178 if ((n->is_Allocate() || n->is_CallStaticJava()) &&
179 (ptn->escape_state() < PointsToNode::GlobalEscape)) {
180 // Only allocations and java static calls results are interesting.
181 non_escaped_allocs_worklist.append(ptn->as_JavaObject());
182 }
183 } else if (ptn->is_Field() && ptn->as_Field()->is_oop()) {
184 oop_fields_worklist.append(ptn->as_Field());
185 }
186 }
187 // Collect some interesting nodes for further use.
188 switch (n->Opcode()) {
189 case Op_MergeMem:
190 // Collect all MergeMem nodes to add memory slices for
191 // scalar replaceable objects in split_unique_types().
192 mergemem_worklist.append(n->as_MergeMem());
193 break;
194 case Op_CmpP:
195 case Op_CmpN:
196 // Collect compare pointers nodes.
197 if (OptimizePtrCompare) {
198 ptr_cmp_worklist.append(n);
199 }
200 break;
201 case Op_MemBarStoreStore:
202 // Collect all MemBarStoreStore nodes so that depending on the
203 // escape status of the associated Allocate node some of them
204 // may be eliminated.
205 if (!UseStoreStoreForCtor || n->req() > MemBarNode::Precedent) {
206 storestore_worklist.append(n->as_MemBarStoreStore());
207 }
208 // If MemBarStoreStore has a precedent edge add it to the worklist (like MemBarRelease)
209 case Op_MemBarRelease:
210 if (n->req() > MemBarNode::Precedent) {
211 record_for_optimizer(n);
212 }
213 break;
214 #ifdef ASSERT
215 case Op_AddP:
216 // Collect address nodes for graph verification.
217 addp_worklist.append(n);
218 break;
219 #endif
220 case Op_ArrayCopy:
221 // Keep a list of ArrayCopy nodes so if one of its input is non
222 // escaping, we can record a unique type
223 arraycopy_worklist.append(n->as_ArrayCopy());
224 break;
225 default:
226 // not interested now, ignore...
227 break;
228 }
229 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
230 Node* m = n->fast_out(i); // Get user
231 ideal_nodes.push(m);
232 }
233 if (n->is_SafePoint()) {
234 sfn_worklist.append(n->as_SafePoint());
235 }
236 }
237
238 #ifndef PRODUCT
239 if (_compile->directive()->TraceEscapeAnalysisOption) {
240 tty->print("+++++ Initial worklist for ");
241 _compile->method()->print_name();
242 tty->print_cr(" (ea_inv=%d)", _invocation);
243 for (int i = 0; i < ptnodes_worklist.length(); i++) {
244 PointsToNode* ptn = ptnodes_worklist.at(i);
245 ptn->dump();
246 }
247 tty->print_cr("+++++ Calculating escape states and scalar replaceability");
248 }
249 #endif
250
251 if (non_escaped_allocs_worklist.length() == 0) {
252 _collecting = false;
253 NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
254 return false; // Nothing to do.
255 }
256 // Add final simple edges to graph.
257 while(delayed_worklist.size() > 0) {
258 Node* n = delayed_worklist.pop();
259 add_final_edges(n);
260 }
261
262 #ifdef ASSERT
263 if (VerifyConnectionGraph) {
264 // Verify that no new simple edges could be created and all
265 // local vars has edges.
266 _verify = true;
267 int ptnodes_length = ptnodes_worklist.length();
268 for (int next = 0; next < ptnodes_length; ++next) {
269 PointsToNode* ptn = ptnodes_worklist.at(next);
270 add_final_edges(ptn->ideal_node());
271 if (ptn->is_LocalVar() && ptn->edge_count() == 0) {
272 ptn->dump();
273 assert(ptn->as_LocalVar()->edge_count() > 0, "sanity");
274 }
275 }
276 _verify = false;
277 }
278 #endif
279 // Bytecode analyzer BCEscapeAnalyzer, used for Call nodes
280 // processing, calls to CI to resolve symbols (types, fields, methods)
281 // referenced in bytecode. During symbol resolution VM may throw
282 // an exception which CI cleans and converts to compilation failure.
283 if (C->failing()) {
284 NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
285 return false;
286 }
287
288 _compile->print_method(PHASE_EA_AFTER_INITIAL_CONGRAPH, 4);
289
290 // 2. Finish Graph construction by propagating references to all
291 // java objects through graph.
292 if (!complete_connection_graph(ptnodes_worklist, non_escaped_allocs_worklist,
293 java_objects_worklist, oop_fields_worklist)) {
294 // All objects escaped or hit time or iterations limits.
295 _collecting = false;
296 NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
297 return false;
298 }
299
300 _compile->print_method(PHASE_EA_AFTER_COMPLETE_CONGRAPH, 4);
301
302 // 3. Adjust scalar_replaceable state of nonescaping objects and push
303 // scalar replaceable allocations on alloc_worklist for processing
304 // in split_unique_types().
305 GrowableArray<JavaObjectNode*> jobj_worklist;
306 int non_escaped_length = non_escaped_allocs_worklist.length();
307 bool found_nsr_alloc = false;
308 for (int next = 0; next < non_escaped_length; next++) {
309 JavaObjectNode* ptn = non_escaped_allocs_worklist.at(next);
310 bool noescape = (ptn->escape_state() == PointsToNode::NoEscape);
311 Node* n = ptn->ideal_node();
312 if (n->is_Allocate()) {
313 n->as_Allocate()->_is_non_escaping = noescape;
314 }
315 if (noescape && ptn->scalar_replaceable()) {
316 adjust_scalar_replaceable_state(ptn, reducible_merges);
317 if (ptn->scalar_replaceable()) {
318 jobj_worklist.push(ptn);
319 } else {
320 found_nsr_alloc = true;
321 }
322 }
323 _compile->print_method(PHASE_EA_ADJUST_SCALAR_REPLACEABLE_ITER, 6, n);
324 }
325
326 // Propagate NSR (Not Scalar Replaceable) state.
327 if (found_nsr_alloc) {
328 find_scalar_replaceable_allocs(jobj_worklist, reducible_merges);
329 }
330
331 // alloc_worklist will be processed in reverse push order.
332 // Therefore the reducible Phis will be processed for last and that's what we
333 // want because by then the scalarizable inputs of the merge will already have
334 // an unique instance type.
335 for (uint i = 0; i < reducible_merges.size(); i++ ) {
336 Node* n = reducible_merges.at(i);
337 alloc_worklist.append(n);
338 }
339
340 for (int next = 0; next < jobj_worklist.length(); ++next) {
341 JavaObjectNode* jobj = jobj_worklist.at(next);
342 if (jobj->scalar_replaceable()) {
343 alloc_worklist.append(jobj->ideal_node());
344 }
345 }
346
347 #ifdef ASSERT
348 if (VerifyConnectionGraph) {
349 // Verify that graph is complete - no new edges could be added or needed.
350 verify_connection_graph(ptnodes_worklist, non_escaped_allocs_worklist,
351 java_objects_worklist, addp_worklist);
352 }
353 assert(C->unique() == nodes_size(), "no new ideal nodes should be added during ConnectionGraph build");
354 assert(null_obj->escape_state() == PointsToNode::NoEscape &&
355 null_obj->edge_count() == 0 &&
356 !null_obj->arraycopy_src() &&
357 !null_obj->arraycopy_dst(), "sanity");
358 #endif
359
360 _collecting = false;
361
362 _compile->print_method(PHASE_EA_AFTER_PROPAGATE_NSR, 4);
363 } // TracePhase t3("connectionGraph")
364
365 // 4. Optimize ideal graph based on EA information.
366 bool has_non_escaping_obj = (non_escaped_allocs_worklist.length() > 0);
367 if (has_non_escaping_obj) {
368 optimize_ideal_graph(ptr_cmp_worklist, storestore_worklist);
369 }
370
371 #ifndef PRODUCT
372 if (PrintEscapeAnalysis) {
373 dump(ptnodes_worklist); // Dump ConnectionGraph
374 }
375 #endif
376
377 #ifdef ASSERT
378 if (VerifyConnectionGraph) {
379 int alloc_length = alloc_worklist.length();
380 for (int next = 0; next < alloc_length; ++next) {
381 Node* n = alloc_worklist.at(next);
382 PointsToNode* ptn = ptnode_adr(n->_idx);
383 assert(ptn->escape_state() == PointsToNode::NoEscape && ptn->scalar_replaceable(), "sanity");
384 }
385 }
386
387 if (VerifyReduceAllocationMerges) {
388 for (uint i = 0; i < reducible_merges.size(); i++ ) {
389 Node* n = reducible_merges.at(i);
390 if (!can_reduce_phi(n->as_Phi())) {
391 TraceReduceAllocationMerges = true;
392 n->dump(2);
393 n->dump(-2);
394 assert(can_reduce_phi(n->as_Phi()), "Sanity: previous reducible Phi is no longer reducible before SUT.");
395 }
396 }
397 }
398 #endif
399
400 _compile->print_method(PHASE_EA_AFTER_GRAPH_OPTIMIZATION, 4);
401
402 // 5. Separate memory graph for scalar replaceable allcations.
403 bool has_scalar_replaceable_candidates = (alloc_worklist.length() > 0);
404 if (has_scalar_replaceable_candidates && EliminateAllocations) {
405 assert(C->do_aliasing(), "Aliasing should be enabled");
406 // Now use the escape information to create unique types for
407 // scalar replaceable objects.
408 split_unique_types(alloc_worklist, arraycopy_worklist, mergemem_worklist, reducible_merges);
409 if (C->failing()) {
410 NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
411 return false;
412 }
413
414 #ifdef ASSERT
415 } else if (Verbose && (PrintEscapeAnalysis || PrintEliminateAllocations)) {
416 tty->print("=== No allocations eliminated for ");
417 C->method()->print_short_name();
418 if (!EliminateAllocations) {
419 tty->print(" since EliminateAllocations is off ===");
420 } else if(!has_scalar_replaceable_candidates) {
421 tty->print(" since there are no scalar replaceable candidates ===");
422 }
423 tty->cr();
424 #endif
425 }
426
427 _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES, 4);
428
429 // 6. Reduce allocation merges used as debug information. This is done after
430 // split_unique_types because the methods used to create SafePointScalarObject
431 // need to traverse the memory graph to find values for object fields. We also
432 // set to null the scalarized inputs of reducible Phis so that the Allocate
433 // that they point can be later scalar replaced.
434 bool delay = _igvn->delay_transform();
435 _igvn->set_delay_transform(true);
436 for (uint i = 0; i < reducible_merges.size(); i++) {
437 Node* n = reducible_merges.at(i);
438 if (n->outcnt() > 0) {
439 if (!reduce_phi_on_safepoints(n->as_Phi())) {
440 NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
441 C->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
442 return false;
443 }
444
445 // Now we set the scalar replaceable inputs of ophi to null, which is
446 // the last piece that would prevent it from being scalar replaceable.
447 reset_scalar_replaceable_entries(n->as_Phi());
448 }
449 }
450 _igvn->set_delay_transform(delay);
451
452 // Annotate at safepoints if they have <= ArgEscape objects in their scope and at
453 // java calls if they pass ArgEscape objects as parameters.
454 if (has_non_escaping_obj &&
455 (C->env()->should_retain_local_variables() ||
456 C->env()->jvmti_can_get_owned_monitor_info() ||
457 C->env()->jvmti_can_walk_any_space() ||
458 DeoptimizeObjectsALot)) {
459 int sfn_length = sfn_worklist.length();
460 for (int next = 0; next < sfn_length; next++) {
461 SafePointNode* sfn = sfn_worklist.at(next);
462 sfn->set_has_ea_local_in_scope(has_ea_local_in_scope(sfn));
463 if (sfn->is_CallJava()) {
464 CallJavaNode* call = sfn->as_CallJava();
465 call->set_arg_escape(has_arg_escape(call));
466 }
467 }
468 }
469
470 _compile->print_method(PHASE_EA_AFTER_REDUCE_PHI_ON_SAFEPOINTS, 4);
471
472 NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
473 return has_non_escaping_obj;
474 }
475
476 // Check if it's profitable to reduce the Phi passed as parameter. Returns true
477 // if at least one scalar replaceable allocation participates in the merge.
478 bool ConnectionGraph::can_reduce_phi_check_inputs(PhiNode* ophi) const {
479 bool found_sr_allocate = false;
480
481 for (uint i = 1; i < ophi->req(); i++) {
482 JavaObjectNode* ptn = unique_java_object(ophi->in(i));
483 if (ptn != nullptr && ptn->scalar_replaceable()) {
484 AllocateNode* alloc = ptn->ideal_node()->as_Allocate();
485
486 // Don't handle arrays.
487 if (alloc->Opcode() != Op_Allocate) {
488 assert(alloc->Opcode() == Op_AllocateArray, "Unexpected type of allocation.");
489 continue;
490 }
491
492 if (PhaseMacroExpand::can_eliminate_allocation(_igvn, alloc, nullptr)) {
493 found_sr_allocate = true;
494 } else {
495 NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("%dth input of Phi %d is SR but can't be eliminated.", i, ophi->_idx);)
496 ptn->set_scalar_replaceable(false);
497 }
498 }
499 }
500
501 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);)
502 return found_sr_allocate;
503 }
504
505 // We can reduce the Cmp if it's a comparison between the Phi and a constant.
506 // I require the 'other' input to be a constant so that I can move the Cmp
507 // around safely.
508 bool ConnectionGraph::can_reduce_cmp(PhiNode* phi, Node* cmp) const {
509 assert(cmp->Opcode() == Op_CmpP || cmp->Opcode() == Op_CmpN, "not expected node: %s", cmp->Name());
510 Node* left = cmp->in(1);
511 Node* right = cmp->in(2);
512
513 return (left == phi || right == phi) &&
514 (left->is_Con() || right->is_Con()) &&
515 cmp->outcnt() == 1;
516 }
517
518 // We are going to check if any of the SafePointScalarMerge entries
519 // in the SafePoint reference the Phi that we are checking.
520 bool ConnectionGraph::has_been_reduced(PhiNode* phi, SafePointNode* sfpt) const {
521 JVMState *jvms = sfpt->jvms();
522
523 for (uint i = jvms->debug_start(); i < jvms->debug_end(); i++) {
524 Node* sfpt_in = sfpt->in(i);
525 if (sfpt_in->is_SafePointScalarMerge()) {
526 SafePointScalarMergeNode* smerge = sfpt_in->as_SafePointScalarMerge();
527 Node* nsr_ptr = sfpt->in(smerge->merge_pointer_idx(jvms));
528 if (nsr_ptr == phi) {
529 return true;
530 }
531 }
532 }
533
534 return false;
535 }
536
537 // Check if we are able to untangle the merge. The following patterns are
538 // supported:
539 // - Phi -> SafePoints
540 // - Phi -> CmpP/N
541 // - Phi -> AddP -> Load
542 // - Phi -> CastPP -> SafePoints
543 // - Phi -> CastPP -> AddP -> Load
544 bool ConnectionGraph::can_reduce_check_users(Node* n, uint nesting) const {
545 assert((n->is_Phi() && nesting == 0) || (n->is_CastPP() && nesting > 0),
546 "invalid node class %s and nesting %d combination", n->Name(), nesting);
547 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
548 Node* use = n->fast_out(i);
549
550 if (use->is_SafePoint()) {
551 if (use->is_Call() && use->as_Call()->has_non_debug_use(n)) {
552 NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. Call has non_debug_use().", n->_idx, _invocation);)
553 return false;
554 } else if (has_been_reduced(n->is_Phi() ? n->as_Phi() : n->as_CastPP()->in(1)->as_Phi(), use->as_SafePoint())) {
555 NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. It has already been reduced.", n->_idx, _invocation);)
556 return false;
557 }
558 } else if (use->is_AddP()) {
559 Node* addp = use;
560 for (DUIterator_Fast jmax, j = addp->fast_outs(jmax); j < jmax; j++) {
561 Node* use_use = addp->fast_out(j);
562 const Type* load_type = _igvn->type(use_use);
563
564 if (!use_use->is_Load() || !use_use->as_Load()->can_split_through_phi_base(_igvn)) {
565 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());)
566 return false;
567 } else if (load_type->isa_narrowklass() || load_type->isa_klassptr()) {
568 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());)
569 return false;
570 }
571 }
572 } else if (nesting > 0) {
573 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);)
574 return false;
575 } else if (use->is_CastPP()) {
576 const Type* cast_t = _igvn->type(use);
577 if (cast_t == nullptr || cast_t->make_ptr()->isa_instptr() == nullptr) {
578 #ifndef PRODUCT
579 if (TraceReduceAllocationMerges) {
580 tty->print_cr("Can NOT reduce Phi %d on invocation %d. CastPP is not to an instance.", n->_idx, _invocation);
581 use->dump();
582 }
583 #endif
584 return false;
585 }
586
587 if (!can_reduce_phi_at_castpp(n->as_Phi(), use->as_CastPP())) {
588 #ifdef ASSERT
589 if (TraceReduceAllocationMerges) {
590 tty->print_cr("Can NOT reduce Phi %d on invocation %d. CastPP %d doesn't have simple control.", n->_idx, _invocation, use->_idx);
591 n->dump(5);
592 }
593 #endif
594 return false;
595 }
596
597 if (!can_reduce_check_users(use, nesting+1)) {
598 return false;
599 }
600 } else if (use->Opcode() == Op_CmpP || use->Opcode() == Op_CmpN) {
601 if (!can_reduce_cmp(n->as_Phi(), use)) {
602 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);)
603 return false;
604 }
605 } else {
606 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());)
607 return false;
608 }
609 }
610
611 return true;
612 }
613
614 // Returns true if the CastPP's control is simple enough to reduce the Phi:
615 // 1) no control,
616 // 2) control is the same Region as the Phi, or
617 // 3) an IfTrue/IfFalse coming from an CmpP/N between the phi and a constant.
618 bool ConnectionGraph::can_reduce_phi_at_castpp(PhiNode* phi, CastPPNode* castpp) const {
619 if (castpp->in(0) == nullptr || castpp->in(0) == phi->in(0)) {
620 return true;
621 }
622 // If it's not a trivial control then we check if we can reduce the
623 // CmpP/N used by the If controlling the cast.
624 if (!(castpp->in(0)->is_IfTrue() || castpp->in(0)->is_IfFalse())) {
625 return false; // Only If control is considered
626 } else {
627 Node* iff = castpp->in(0)->in(0);
628 // We may have an OpaqueConstantBool node between If and Bool nodes. But we could also have a sub class of IfNode,
629 // for example, an OuterStripMinedLoopEnd or a Parse Predicate. Bail out in all these cases.
630 if (iff->Opcode() == Op_If && iff->in(1)->is_Bool() && iff->in(1)->in(1)->is_Cmp()) {
631 Node* iff_cmp = iff->in(1)->in(1);
632 int opc = iff_cmp->Opcode();
633 if ((opc == Op_CmpP || opc == Op_CmpN) && can_reduce_cmp(phi, iff_cmp)) {
634 return true;
635 }
636 }
637 }
638 return false;
639 }
640
641 // Returns true if: 1) It's profitable to reduce the merge, and 2) The Phi is
642 // only used in some certain code shapes. Check comments in
643 // 'can_reduce_phi_inputs' and 'can_reduce_phi_users' for more
644 // details.
645 bool ConnectionGraph::can_reduce_phi(PhiNode* ophi) const {
646 // If there was an error attempting to reduce allocation merges for this
647 // method we might have disabled the compilation and be retrying with RAM
648 // disabled.
649 if (!_compile->do_reduce_allocation_merges() || ophi->region()->Opcode() != Op_Region) {
650 return false;
651 }
652
653 const Type* phi_t = _igvn->type(ophi);
654 if (phi_t == nullptr ||
655 phi_t->make_ptr() == nullptr ||
656 phi_t->make_ptr()->isa_aryptr() != nullptr) {
657 return false;
658 }
659
660 if (!can_reduce_phi_check_inputs(ophi) || !can_reduce_check_users(ophi, /* nesting: */ 0)) {
661 return false;
662 }
663
664 NOT_PRODUCT(if (TraceReduceAllocationMerges) { tty->print_cr("Can reduce Phi %d during invocation %d: ", ophi->_idx, _invocation); })
665 return true;
666 }
667
668 // This method will return a CmpP/N that we need to use on the If controlling a
669 // CastPP after it was split. This method is only called on bases that are
670 // nullable therefore we always need a controlling if for the splitted CastPP.
671 //
672 // 'curr_ctrl' is the control of the CastPP that we want to split through phi.
673 // If the CastPP currently doesn't have a control then the CmpP/N will be
674 // against the null constant, otherwise it will be against the constant input of
675 // the existing CmpP/N. It's guaranteed that there will be a CmpP/N in the later
676 // case because we have constraints on it and because the CastPP has a control
677 // input.
678 Node* ConnectionGraph::specialize_cmp(Node* base, Node* curr_ctrl) {
679 const Type* t = base->bottom_type();
680 Node* con = nullptr;
681
682 if (curr_ctrl == nullptr || curr_ctrl->is_Region()) {
683 con = _igvn->zerocon(t->basic_type());
684 } else {
685 // can_reduce_check_users() verified graph: true/false -> if -> bool -> cmp
686 assert(curr_ctrl->in(0)->Opcode() == Op_If, "unexpected node %s", curr_ctrl->in(0)->Name());
687 Node* bol = curr_ctrl->in(0)->in(1);
688 assert(bol->is_Bool(), "unexpected node %s", bol->Name());
689 Node* curr_cmp = bol->in(1);
690 assert(curr_cmp->Opcode() == Op_CmpP || curr_cmp->Opcode() == Op_CmpN, "unexpected node %s", curr_cmp->Name());
691 con = curr_cmp->in(1)->is_Con() ? curr_cmp->in(1) : curr_cmp->in(2);
692 }
693
694 return CmpNode::make(base, con, t->basic_type());
695 }
696
697 // This method 'specializes' the CastPP passed as parameter to the base passed
698 // as parameter. Note that the existing CastPP input is a Phi. "Specialize"
699 // means that the CastPP now will be specific for a given base instead of a Phi.
700 // An If-Then-Else-Region block is inserted to control the CastPP. The control
701 // of the CastPP is a copy of the current one (if there is one) or a check
702 // against null.
703 //
704 // Before:
705 //
706 // C1 C2 ... Cn
707 // \ | /
708 // \ | /
709 // \ | /
710 // \ | /
711 // \ | /
712 // \ | /
713 // \|/
714 // Region B1 B2 ... Bn
715 // | \ | /
716 // | \ | /
717 // | \ | /
718 // | \ | /
719 // | \ | /
720 // | \ | /
721 // ---------------> Phi
722 // |
723 // X |
724 // | |
725 // | |
726 // ------> CastPP
727 //
728 // After (only partial illustration; base = B2, current_control = C2):
729 //
730 // C2
731 // |
732 // If
733 // / \
734 // / \
735 // T F
736 // /\ /
737 // / \ /
738 // / \ /
739 // C1 CastPP Reg Cn
740 // | | |
741 // | | |
742 // | | |
743 // -------------- | ----------
744 // | | |
745 // Region
746 //
747 Node* ConnectionGraph::specialize_castpp(Node* castpp, Node* base, Node* current_control) {
748 Node* control_successor = current_control->unique_ctrl_out();
749 Node* cmp = _igvn->transform(specialize_cmp(base, castpp->in(0)));
750 Node* bol = _igvn->transform(new BoolNode(cmp, BoolTest::ne));
751 IfNode* if_ne = _igvn->transform(new IfNode(current_control, bol, PROB_MIN, COUNT_UNKNOWN))->as_If();
752 Node* not_eq_control = _igvn->transform(new IfTrueNode(if_ne));
753 Node* yes_eq_control = _igvn->transform(new IfFalseNode(if_ne));
754 Node* end_region = _igvn->transform(new RegionNode(3));
755
756 // Insert the new if-else-region block into the graph
757 end_region->set_req(1, not_eq_control);
758 end_region->set_req(2, yes_eq_control);
759 control_successor->replace_edge(current_control, end_region, _igvn);
760
761 _igvn->_worklist.push(current_control);
762 _igvn->_worklist.push(control_successor);
763
764 return _igvn->transform(ConstraintCastNode::make_cast_for_type(not_eq_control, base, _igvn->type(castpp), ConstraintCastNode::DependencyType::NonFloatingNonNarrowing, nullptr));
765 }
766
767 Node* ConnectionGraph::split_castpp_load_through_phi(Node* curr_addp, Node* curr_load, Node* region, GrowableArray<Node*>* bases_for_loads, GrowableArray<Node *> &alloc_worklist) {
768 const Type* load_type = _igvn->type(curr_load);
769 Node* nsr_value = _igvn->zerocon(load_type->basic_type());
770 Node* memory = curr_load->in(MemNode::Memory);
771
772 // The data_phi merging the loads needs to be nullable if
773 // we are loading pointers.
774 if (load_type->make_ptr() != nullptr) {
775 if (load_type->isa_narrowoop()) {
776 load_type = load_type->meet(TypeNarrowOop::NULL_PTR);
777 } else if (load_type->isa_ptr()) {
778 load_type = load_type->meet(TypePtr::NULL_PTR);
779 } else {
780 assert(false, "Unexpected load ptr type.");
781 }
782 }
783
784 Node* data_phi = PhiNode::make(region, nsr_value, load_type);
785
786 for (int i = 1; i < bases_for_loads->length(); i++) {
787 Node* base = bases_for_loads->at(i);
788 Node* cmp_region = nullptr;
789 if (base != nullptr) {
790 if (base->is_CFG()) { // means that we added a CastPP as child of this CFG node
791 cmp_region = base->unique_ctrl_out_or_null();
792 assert(cmp_region != nullptr, "There should be.");
793 base = base->find_out_with(Op_CastPP);
794 }
795
796 Node* addr = _igvn->transform(AddPNode::make_with_base(base, curr_addp->in(AddPNode::Offset)));
797 Node* mem = (memory->is_Phi() && (memory->in(0) == region)) ? memory->in(i) : memory;
798 Node* load = curr_load->clone();
799 load->set_req(0, nullptr);
800 load->set_req(1, mem);
801 load->set_req(2, addr);
802
803 if (cmp_region != nullptr) { // see comment on previous if
804 Node* intermediate_phi = PhiNode::make(cmp_region, nsr_value, load_type);
805 intermediate_phi->set_req(1, _igvn->transform(load));
806 load = intermediate_phi;
807 }
808
809 data_phi->set_req(i, _igvn->transform(load));
810 } else {
811 // Just use the default, which is already in phi
812 }
813 }
814
815 // Takes care of updating CG and split_unique_types worklists due
816 // to cloned AddP->Load.
817 updates_after_load_split(data_phi, curr_load, alloc_worklist);
818
819 return _igvn->transform(data_phi);
820 }
821
822 // This method only reduces CastPP fields loads; SafePoints are handled
823 // separately. The idea here is basically to clone the CastPP and place copies
824 // on each input of the Phi, including non-scalar replaceable inputs.
825 // Experimentation shows that the resulting IR graph is simpler that way than if
826 // we just split the cast through scalar-replaceable inputs.
827 //
828 // The reduction process requires that CastPP's control be one of:
829 // 1) no control,
830 // 2) the same region as Ophi, or
831 // 3) an IfTrue/IfFalse coming from an CmpP/N between Ophi and a constant.
832 //
833 // After splitting the CastPP we'll put it under an If-Then-Else-Region control
834 // flow. If the CastPP originally had an IfTrue/False control input then we'll
835 // use a similar CmpP/N to control the new If-Then-Else-Region. Otherwise, we'll
836 // juse use a CmpP/N against the null constant.
837 //
838 // The If-Then-Else-Region isn't always needed. For instance, if input to
839 // splitted cast was not nullable (or if it was the null constant) then we don't
840 // need (shouldn't) use a CastPP at all.
841 //
842 // After the casts are splitted we'll split the AddP->Loads through the Phi and
843 // connect them to the just split CastPPs.
844 //
845 // Before (CastPP control is same as Phi):
846 //
847 // Region Allocate Null Call
848 // | \ | /
849 // | \ | /
850 // | \ | /
851 // | \ | /
852 // | \ | /
853 // | \ | /
854 // ------------------> Phi # Oop Phi
855 // | |
856 // | |
857 // | |
858 // | |
859 // ----------------> CastPP
860 // |
861 // AddP
862 // |
863 // Load
864 //
865 // After (Very much simplified):
866 //
867 // Call Null
868 // \ /
869 // CmpP
870 // |
871 // Bool#NE
872 // |
873 // If
874 // / \
875 // T F
876 // / \ /
877 // / R
878 // CastPP |
879 // | |
880 // AddP |
881 // | |
882 // Load |
883 // \ | 0
884 // Allocate \ | /
885 // \ \ | /
886 // AddP Phi
887 // \ /
888 // Load /
889 // \ 0 /
890 // \ | /
891 // \|/
892 // Phi # "Field" Phi
893 //
894 void ConnectionGraph::reduce_phi_on_castpp_field_load(CastPPNode* curr_castpp, GrowableArray<Node*> &alloc_worklist) {
895 PhiNode* ophi = curr_castpp->in(1)->as_Phi();
896 precond(can_reduce_phi_at_castpp(ophi, curr_castpp));
897
898 // Identify which base should be used for AddP->Load later when spliting the
899 // CastPP->Loads through ophi. Three kind of values may be stored in this
900 // array, depending on the nullability status of the corresponding input in
901 // ophi.
902 //
903 // - nullptr: Meaning that the base is actually the null constant and therefore
904 // we won't try to load from it.
905 //
906 // - CFG Node: Meaning that the base is a CastPP that was specialized for
907 // this input of Ophi. I.e., we added an If->Then->Else-Region
908 // that will 'activate' the CastPp only when the input is not Null.
909 //
910 // - Other Node: Meaning that the base is not nullable and therefore we'll try
911 // to load directly from it.
912 GrowableArray<Node*> bases_for_loads(ophi->req(), ophi->req(), nullptr);
913
914 for (uint i = 1; i < ophi->req(); i++) {
915 Node* base = ophi->in(i);
916 const Type* base_t = _igvn->type(base);
917
918 if (base_t->maybe_null()) {
919 if (base->is_Con()) {
920 // Nothing todo as bases_for_loads[i] is already null
921 } else {
922 Node* new_castpp = specialize_castpp(curr_castpp, base, ophi->in(0)->in(i));
923 bases_for_loads.at_put(i, new_castpp->in(0)); // Use the ctrl of the new node just as a flag
924 }
925 } else {
926 bases_for_loads.at_put(i, base);
927 }
928 }
929
930 // Now let's split the CastPP->Loads through the Phi
931 for (int i = curr_castpp->outcnt()-1; i >= 0;) {
932 Node* use = curr_castpp->raw_out(i);
933 if (use->is_AddP()) {
934 for (int j = use->outcnt()-1; j >= 0;) {
935 Node* use_use = use->raw_out(j);
936 assert(use_use->is_Load(), "Expected this to be a Load node.");
937
938 // We can't make an unconditional load from a nullable input. The
939 // 'split_castpp_load_through_phi` method will add an
940 // 'If-Then-Else-Region` around nullable bases and only load from them
941 // when the input is not null.
942 Node* phi = split_castpp_load_through_phi(use, use_use, ophi->in(0), &bases_for_loads, alloc_worklist);
943 _igvn->replace_node(use_use, phi);
944
945 --j;
946 j = MIN2(j, (int)use->outcnt()-1);
947 }
948
949 _igvn->remove_dead_node(use, PhaseIterGVN::NodeOrigin::Graph);
950 }
951 --i;
952 i = MIN2(i, (int)curr_castpp->outcnt()-1);
953 }
954 }
955
956 // This method split a given CmpP/N through the Phi used in one of its inputs.
957 // As a result we convert a comparison with a pointer to a comparison with an
958 // integer.
959 // The only requirement is that one of the inputs of the CmpP/N must be a Phi
960 // while the other must be a constant.
961 // The splitting process is basically just cloning the CmpP/N above the input
962 // Phi. However, some (most) of the cloned CmpP/Ns won't be requred because we
963 // can prove at compile time the result of the comparison.
964 //
965 // Before:
966 //
967 // in1 in2 ... inN
968 // \ | /
969 // \ | /
970 // \ | /
971 // \ | /
972 // \ | /
973 // \ | /
974 // Phi
975 // | Other
976 // | /
977 // | /
978 // | /
979 // CmpP/N
980 //
981 // After:
982 //
983 // in1 Other in2 Other inN Other
984 // | | | | | |
985 // \ | | | | |
986 // \ / | / | /
987 // CmpP/N CmpP/N CmpP/N
988 // Bool Bool Bool
989 // \ | /
990 // \ | /
991 // \ | /
992 // \ | /
993 // \ | /
994 // \ | /
995 // \ | /
996 // \ | /
997 // Phi
998 // |
999 // | Zero
1000 // | /
1001 // | /
1002 // | /
1003 // CmpI
1004 //
1005 //
1006 void ConnectionGraph::reduce_phi_on_cmp(Node* cmp) {
1007 Node* ophi = cmp->in(1)->is_Con() ? cmp->in(2) : cmp->in(1);
1008 assert(ophi->is_Phi(), "Expected this to be a Phi node.");
1009
1010 Node* other = cmp->in(1)->is_Con() ? cmp->in(1) : cmp->in(2);
1011 Node* zero = _igvn->intcon(0);
1012 Node* one = _igvn->intcon(1);
1013 BoolTest::mask mask = cmp->unique_out()->as_Bool()->_test._test;
1014
1015 // This Phi will merge the result of the Cmps split through the Phi
1016 Node* res_phi = PhiNode::make(ophi->in(0), zero, TypeInt::INT);
1017
1018 for (uint i=1; i<ophi->req(); i++) {
1019 Node* ophi_input = ophi->in(i);
1020 Node* res_phi_input = nullptr;
1021
1022 const TypeInt* tcmp = optimize_ptr_compare(ophi_input, other);
1023 if (tcmp->singleton()) {
1024 if ((mask == BoolTest::mask::eq && tcmp == TypeInt::CC_EQ) ||
1025 (mask == BoolTest::mask::ne && tcmp == TypeInt::CC_GT)) {
1026 res_phi_input = one;
1027 } else {
1028 res_phi_input = zero;
1029 }
1030 } else {
1031 Node* ncmp = _igvn->transform(cmp->clone());
1032 ncmp->set_req(1, ophi_input);
1033 ncmp->set_req(2, other);
1034 Node* bol = _igvn->transform(new BoolNode(ncmp, mask));
1035 res_phi_input = bol->as_Bool()->as_int_value(_igvn);
1036 }
1037
1038 res_phi->set_req(i, res_phi_input);
1039 }
1040
1041 // This CMP always compares whether the output of "res_phi" is TRUE as far as the "mask".
1042 Node* new_cmp = _igvn->transform(new CmpINode(_igvn->transform(res_phi), (mask == BoolTest::mask::eq) ? one : zero));
1043 _igvn->replace_node(cmp, new_cmp);
1044 }
1045
1046 // Push the newly created AddP on alloc_worklist and patch
1047 // the connection graph. Note that the changes in the CG below
1048 // won't affect the ES of objects since the new nodes have the
1049 // same status as the old ones.
1050 void ConnectionGraph::updates_after_load_split(Node* data_phi, Node* previous_load, GrowableArray<Node *> &alloc_worklist) {
1051 assert(data_phi != nullptr, "Output of split_through_phi is null.");
1052 assert(data_phi != previous_load, "Output of split_through_phi is same as input.");
1053 assert(data_phi->is_Phi(), "Output of split_through_phi isn't a Phi.");
1054
1055 if (data_phi == nullptr || !data_phi->is_Phi()) {
1056 // Make this a retry?
1057 return ;
1058 }
1059
1060 Node* previous_addp = previous_load->in(MemNode::Address);
1061 FieldNode* fn = ptnode_adr(previous_addp->_idx)->as_Field();
1062 for (uint i = 1; i < data_phi->req(); i++) {
1063 Node* new_load = data_phi->in(i);
1064
1065 if (new_load->is_Phi()) {
1066 // new_load is currently the "intermediate_phi" from an specialized
1067 // CastPP.
1068 new_load = new_load->in(1);
1069 }
1070
1071 // "new_load" might actually be a constant, parameter, etc.
1072 if (new_load->is_Load()) {
1073 Node* new_addp = new_load->in(MemNode::Address);
1074
1075 // If new_load is a Load but not from an AddP, it means that the load is folded into another
1076 // load. And since this load is not from a field, we cannot create a unique type for it.
1077 // For example:
1078 //
1079 // if (b) {
1080 // Holder h1 = new Holder();
1081 // Object o = ...;
1082 // h.o = o.getClass();
1083 // } else {
1084 // Holder h2 = ...;
1085 // }
1086 // Holder h = Phi(h1, h2);
1087 // Object r = h.o;
1088 //
1089 // Then, splitting r through the merge point results in:
1090 //
1091 // if (b) {
1092 // Holder h1 = new Holder();
1093 // Object o = ...;
1094 // h.o = o.getClass();
1095 // Object o1 = h.o;
1096 // } else {
1097 // Holder h2 = ...;
1098 // Object o2 = h2.o;
1099 // }
1100 // Object r = Phi(o1, o2);
1101 //
1102 // In this case, o1 is folded to o.getClass() which is a Load but not from an AddP, but from
1103 // an OopHandle that is loaded from the Klass of o.
1104 if (!new_addp->is_AddP()) {
1105 continue;
1106 }
1107 Node* base = get_addp_base(new_addp);
1108
1109 // The base might not be something that we can create an unique
1110 // type for. If that's the case we are done with that input.
1111 PointsToNode* jobj_ptn = unique_java_object(base);
1112 if (jobj_ptn == nullptr || !jobj_ptn->scalar_replaceable()) {
1113 continue;
1114 }
1115
1116 // Push to alloc_worklist since the base has an unique_type
1117 alloc_worklist.append_if_missing(new_addp);
1118
1119 // Now let's add the node to the connection graph
1120 _nodes.at_grow(new_addp->_idx, nullptr);
1121 add_field(new_addp, fn->escape_state(), fn->offset());
1122 add_base(ptnode_adr(new_addp->_idx)->as_Field(), ptnode_adr(base->_idx));
1123
1124 // If the load doesn't load an object then it won't be
1125 // part of the connection graph
1126 PointsToNode* curr_load_ptn = ptnode_adr(previous_load->_idx);
1127 if (curr_load_ptn != nullptr) {
1128 _nodes.at_grow(new_load->_idx, nullptr);
1129 add_local_var(new_load, curr_load_ptn->escape_state());
1130 add_edge(ptnode_adr(new_load->_idx), ptnode_adr(new_addp->_idx)->as_Field());
1131 }
1132 }
1133 }
1134 }
1135
1136 void ConnectionGraph::reduce_phi_on_field_access(Node* previous_addp, GrowableArray<Node *> &alloc_worklist) {
1137 // We'll pass this to 'split_through_phi' so that it'll do the split even
1138 // though the load doesn't have an unique instance type.
1139 bool ignore_missing_instance_id = true;
1140
1141 // All AddPs are present in the connection graph
1142 FieldNode* fn = ptnode_adr(previous_addp->_idx)->as_Field();
1143
1144 // Iterate over AddP looking for a Load
1145 for (int k = previous_addp->outcnt()-1; k >= 0;) {
1146 Node* previous_load = previous_addp->raw_out(k);
1147 if (previous_load->is_Load()) {
1148 Node* data_phi = previous_load->as_Load()->split_through_phi(_igvn, ignore_missing_instance_id);
1149
1150 // Takes care of updating CG and split_unique_types worklists due to cloned
1151 // AddP->Load.
1152 updates_after_load_split(data_phi, previous_load, alloc_worklist);
1153
1154 _igvn->replace_node(previous_load, data_phi);
1155 }
1156 --k;
1157 k = MIN2(k, (int)previous_addp->outcnt()-1);
1158 }
1159
1160 // Remove the old AddP from the processing list because it's dead now
1161 assert(previous_addp->outcnt() == 0, "AddP should be dead now.");
1162 alloc_worklist.remove_if_existing(previous_addp);
1163 }
1164
1165 // Create a 'selector' Phi based on the inputs of 'ophi'. If index 'i' of the
1166 // selector is:
1167 // -> a '-1' constant, the i'th input of the original Phi is NSR.
1168 // -> a 'x' constant >=0, the i'th input of of original Phi will be SR and
1169 // the info about the scalarized object will be at index x of ObjectMergeValue::possible_objects
1170 PhiNode* ConnectionGraph::create_selector(PhiNode* ophi) const {
1171 Node* minus_one = _igvn->register_new_node_with_optimizer(ConINode::make(-1));
1172 Node* selector = _igvn->register_new_node_with_optimizer(PhiNode::make(ophi->region(), minus_one, TypeInt::INT));
1173 uint number_of_sr_objects = 0;
1174 for (uint i = 1; i < ophi->req(); i++) {
1175 Node* base = ophi->in(i);
1176 JavaObjectNode* ptn = unique_java_object(base);
1177
1178 if (ptn != nullptr && ptn->scalar_replaceable()) {
1179 Node* sr_obj_idx = _igvn->register_new_node_with_optimizer(ConINode::make(number_of_sr_objects));
1180 selector->set_req(i, sr_obj_idx);
1181 number_of_sr_objects++;
1182 }
1183 }
1184
1185 return selector->as_Phi();
1186 }
1187
1188 // Returns true if the AddP node 'n' has at least one base that is a reducible
1189 // merge. If the base is a CastPP/CheckCastPP then the input of the cast is
1190 // checked instead.
1191 bool ConnectionGraph::has_reducible_merge_base(AddPNode* n, Unique_Node_List &reducible_merges) {
1192 PointsToNode* ptn = ptnode_adr(n->_idx);
1193 if (ptn == nullptr || !ptn->is_Field() || ptn->as_Field()->base_count() < 2) {
1194 return false;
1195 }
1196
1197 for (BaseIterator i(ptn->as_Field()); i.has_next(); i.next()) {
1198 Node* base = i.get()->ideal_node();
1199
1200 if (reducible_merges.member(base)) {
1201 return true;
1202 }
1203
1204 if (base->is_CastPP() || base->is_CheckCastPP()) {
1205 base = base->in(1);
1206 if (reducible_merges.member(base)) {
1207 return true;
1208 }
1209 }
1210 }
1211
1212 return false;
1213 }
1214
1215 // This method will call its helper method to reduce SafePoint nodes that use
1216 // 'ophi' or a casted version of 'ophi'. All SafePoint nodes using the same
1217 // "version" of Phi use the same debug information (regarding the Phi).
1218 // Therefore, I collect all safepoints and patch them all at once.
1219 //
1220 // The safepoints using the Phi node have to be processed before safepoints of
1221 // CastPP nodes. The reason is, when reducing a CastPP we add a reference (the
1222 // NSR merge pointer) to the input of the CastPP (i.e., the Phi) in the
1223 // safepoint. If we process CastPP's safepoints before Phi's safepoints the
1224 // algorithm that process Phi's safepoints will think that the added Phi
1225 // reference is a regular reference.
1226 bool ConnectionGraph::reduce_phi_on_safepoints(PhiNode* ophi) {
1227 PhiNode* selector = create_selector(ophi);
1228 Unique_Node_List safepoints;
1229 Unique_Node_List casts;
1230
1231 // Just collect the users of the Phis for later processing
1232 // in the needed order.
1233 for (uint i = 0; i < ophi->outcnt(); i++) {
1234 Node* use = ophi->raw_out(i);
1235 if (use->is_SafePoint()) {
1236 safepoints.push(use);
1237 } else if (use->is_CastPP()) {
1238 casts.push(use);
1239 } else {
1240 assert(use->outcnt() == 0, "Only CastPP & SafePoint users should be left.");
1241 }
1242 }
1243
1244 // Need to process safepoints using the Phi first
1245 if (!reduce_phi_on_safepoints_helper(ophi, nullptr, selector, safepoints)) {
1246 return false;
1247 }
1248
1249 // Now process CastPP->safepoints
1250 for (uint i = 0; i < casts.size(); i++) {
1251 Node* cast = casts.at(i);
1252 Unique_Node_List cast_sfpts;
1253
1254 for (DUIterator_Fast jmax, j = cast->fast_outs(jmax); j < jmax; j++) {
1255 Node* use_use = cast->fast_out(j);
1256 if (use_use->is_SafePoint()) {
1257 cast_sfpts.push(use_use);
1258 } else {
1259 assert(use_use->outcnt() == 0, "Only SafePoint users should be left.");
1260 }
1261 }
1262
1263 if (!reduce_phi_on_safepoints_helper(ophi, cast, selector, cast_sfpts)) {
1264 return false;
1265 }
1266 }
1267
1268 return true;
1269 }
1270
1271 // This method will create a SafePointScalarMERGEnode for each SafePoint in
1272 // 'safepoints'. It then will iterate on the inputs of 'ophi' and create a
1273 // SafePointScalarObjectNode for each scalar replaceable input. Each
1274 // SafePointScalarMergeNode may describe multiple scalar replaced objects -
1275 // check detailed description in SafePointScalarMergeNode class header.
1276 bool ConnectionGraph::reduce_phi_on_safepoints_helper(Node* ophi, Node* cast, Node* selector, Unique_Node_List& safepoints) {
1277 PhaseMacroExpand mexp(*_igvn);
1278 Node* original_sfpt_parent = cast != nullptr ? cast : ophi;
1279 const TypeOopPtr* merge_t = _igvn->type(original_sfpt_parent)->make_oopptr();
1280
1281 Node* nsr_merge_pointer = ophi;
1282 if (cast != nullptr) {
1283 const Type* new_t = merge_t->meet(TypePtr::NULL_PTR);
1284 nsr_merge_pointer = _igvn->transform(ConstraintCastNode::make_cast_for_type(cast->in(0), cast->in(1), new_t, ConstraintCastNode::DependencyType::FloatingNarrowing, nullptr));
1285 }
1286
1287 for (uint spi = 0; spi < safepoints.size(); spi++) {
1288 SafePointNode* sfpt = safepoints.at(spi)->as_SafePoint();
1289
1290 SafePointNode::NodeEdgeTempStorage non_debug_edges_worklist(*_igvn);
1291
1292 // All sfpt inputs are implicitly included into debug info during the scalarization process below.
1293 // Keep non-debug inputs separately, so they stay non-debug.
1294 sfpt->remove_non_debug_edges(non_debug_edges_worklist);
1295
1296 JVMState* jvms = sfpt->jvms();
1297 uint merge_idx = (sfpt->req() - jvms->scloff());
1298 int debug_start = jvms->debug_start();
1299
1300 SafePointScalarMergeNode* smerge = new SafePointScalarMergeNode(merge_t, merge_idx);
1301 smerge->init_req(0, _compile->root());
1302 _igvn->register_new_node_with_optimizer(smerge);
1303
1304 assert(sfpt->jvms()->endoff() == sfpt->req(), "no extra edges past debug info allowed");
1305
1306 // The next two inputs are:
1307 // (1) A copy of the original pointer to NSR objects.
1308 // (2) A selector, used to decide if we need to rematerialize an object
1309 // or use the pointer to a NSR object.
1310 // See more details of these fields in the declaration of SafePointScalarMergeNode.
1311 // It is safe to include them into debug info straight away since create_scalarized_object_description()
1312 // will include all newly added inputs into debug info anyway.
1313 sfpt->add_req(nsr_merge_pointer);
1314 sfpt->add_req(selector);
1315 sfpt->jvms()->set_endoff(sfpt->req());
1316
1317 for (uint i = 1; i < ophi->req(); i++) {
1318 Node* base = ophi->in(i);
1319 JavaObjectNode* ptn = unique_java_object(base);
1320
1321 // If the base is not scalar replaceable we don't need to register information about
1322 // it at this time.
1323 if (ptn == nullptr || !ptn->scalar_replaceable()) {
1324 continue;
1325 }
1326
1327 AllocateNode* alloc = ptn->ideal_node()->as_Allocate();
1328 SafePointScalarObjectNode* sobj = mexp.create_scalarized_object_description(alloc, sfpt);
1329 if (sobj == nullptr) {
1330 sfpt->restore_non_debug_edges(non_debug_edges_worklist);
1331 return false; // non-recoverable failure; recompile
1332 }
1333
1334 // Now make a pass over the debug information replacing any references
1335 // to the allocated object with "sobj"
1336 Node* ccpp = alloc->result_cast();
1337 sfpt->replace_edges_in_range(ccpp, sobj, debug_start, jvms->debug_end(), _igvn);
1338 non_debug_edges_worklist.remove_edge_if_present(ccpp); // drop scalarized input from non-debug info
1339
1340 // Register the scalarized object as a candidate for reallocation
1341 smerge->add_req(sobj);
1342 }
1343
1344 // Replaces debug information references to "original_sfpt_parent" in "sfpt" with references to "smerge"
1345 sfpt->replace_edges_in_range(original_sfpt_parent, smerge, debug_start, jvms->debug_end(), _igvn);
1346 non_debug_edges_worklist.remove_edge_if_present(original_sfpt_parent); // drop scalarized input from non-debug info
1347
1348 // The call to 'replace_edges_in_range' above might have removed the
1349 // reference to ophi that we need at _merge_pointer_idx. The line below make
1350 // sure the reference is maintained.
1351 sfpt->set_req(smerge->merge_pointer_idx(jvms), nsr_merge_pointer);
1352
1353 sfpt->restore_non_debug_edges(non_debug_edges_worklist);
1354
1355 _igvn->_worklist.push(sfpt);
1356 }
1357
1358 return true;
1359 }
1360
1361 void ConnectionGraph::reduce_phi(PhiNode* ophi, GrowableArray<Node*> &alloc_worklist) {
1362 bool delay = _igvn->delay_transform();
1363 _igvn->set_delay_transform(true);
1364 _igvn->hash_delete(ophi);
1365
1366 // Copying all users first because some will be removed and others won't.
1367 // Ophi also may acquire some new users as part of Cast reduction.
1368 // CastPPs also need to be processed before CmpPs.
1369 Unique_Node_List castpps;
1370 Unique_Node_List others;
1371 for (DUIterator_Fast imax, i = ophi->fast_outs(imax); i < imax; i++) {
1372 Node* use = ophi->fast_out(i);
1373
1374 if (use->is_CastPP()) {
1375 castpps.push(use);
1376 } else if (use->is_AddP() || use->is_Cmp()) {
1377 others.push(use);
1378 } else {
1379 // Safepoints to be processed later; other users aren't expected here
1380 assert(use->is_SafePoint(), "Unexpected user of reducible Phi %d -> %d:%s:%d", ophi->_idx, use->_idx, use->Name(), use->outcnt());
1381 }
1382 }
1383
1384 _compile->print_method(PHASE_EA_BEFORE_PHI_REDUCTION, 5, ophi);
1385
1386 // CastPPs need to be processed before Cmps because during the process of
1387 // splitting CastPPs we make reference to the inputs of the Cmp that is used
1388 // by the If controlling the CastPP.
1389 for (uint i = 0; i < castpps.size(); i++) {
1390 reduce_phi_on_castpp_field_load(castpps.at(i)->as_CastPP(), alloc_worklist);
1391 _compile->print_method(PHASE_EA_AFTER_PHI_CASTPP_REDUCTION, 6, castpps.at(i));
1392 }
1393
1394 for (uint i = 0; i < others.size(); i++) {
1395 Node* use = others.at(i);
1396
1397 if (use->is_AddP()) {
1398 reduce_phi_on_field_access(use, alloc_worklist);
1399 _compile->print_method(PHASE_EA_AFTER_PHI_ADDP_REDUCTION, 6, use);
1400 } else if(use->is_Cmp()) {
1401 reduce_phi_on_cmp(use);
1402 _compile->print_method(PHASE_EA_AFTER_PHI_CMP_REDUCTION, 6, use);
1403 }
1404 }
1405
1406 _igvn->set_delay_transform(delay);
1407 }
1408
1409 void ConnectionGraph::reset_scalar_replaceable_entries(PhiNode* ophi) {
1410 Node* null_ptr = _igvn->makecon(TypePtr::NULL_PTR);
1411 const TypeOopPtr* merge_t = _igvn->type(ophi)->make_oopptr();
1412 const Type* new_t = merge_t->meet(TypePtr::NULL_PTR);
1413 Node* new_phi = _igvn->register_new_node_with_optimizer(PhiNode::make(ophi->region(), null_ptr, new_t));
1414
1415 for (uint i = 1; i < ophi->req(); i++) {
1416 Node* base = ophi->in(i);
1417 JavaObjectNode* ptn = unique_java_object(base);
1418
1419 if (ptn != nullptr && ptn->scalar_replaceable()) {
1420 new_phi->set_req(i, null_ptr);
1421 } else {
1422 new_phi->set_req(i, ophi->in(i));
1423 }
1424 }
1425
1426 for (int i = ophi->outcnt()-1; i >= 0;) {
1427 Node* out = ophi->raw_out(i);
1428
1429 if (out->is_ConstraintCast()) {
1430 const Type* out_t = _igvn->type(out)->make_ptr();
1431 const Type* out_new_t = out_t->meet(TypePtr::NULL_PTR);
1432 bool change = out_new_t != out_t;
1433
1434 for (int j = out->outcnt()-1; change && j >= 0; --j) {
1435 Node* out2 = out->raw_out(j);
1436 if (!out2->is_SafePoint()) {
1437 change = false;
1438 break;
1439 }
1440 }
1441
1442 if (change) {
1443 Node* new_cast = ConstraintCastNode::make_cast_for_type(out->in(0), out->in(1), out_new_t, ConstraintCastNode::DependencyType::NonFloatingNarrowing, nullptr);
1444 _igvn->replace_node(out, new_cast);
1445 _igvn->register_new_node_with_optimizer(new_cast);
1446 }
1447 }
1448
1449 --i;
1450 i = MIN2(i, (int)ophi->outcnt()-1);
1451 }
1452
1453 _igvn->replace_node(ophi, new_phi);
1454 }
1455
1456 void ConnectionGraph::verify_ram_nodes(Compile* C, Node* root) {
1457 if (!C->do_reduce_allocation_merges()) return;
1458
1459 Unique_Node_List ideal_nodes;
1460 ideal_nodes.map(C->live_nodes(), nullptr); // preallocate space
1461 ideal_nodes.push(root);
1462
1463 for (uint next = 0; next < ideal_nodes.size(); ++next) {
1464 Node* n = ideal_nodes.at(next);
1465
1466 if (n->is_SafePointScalarMerge()) {
1467 SafePointScalarMergeNode* merge = n->as_SafePointScalarMerge();
1468
1469 // Validate inputs of merge
1470 for (uint i = 1; i < merge->req(); i++) {
1471 if (merge->in(i) != nullptr && !merge->in(i)->is_top() && !merge->in(i)->is_SafePointScalarObject()) {
1472 assert(false, "SafePointScalarMerge inputs should be null/top or SafePointScalarObject.");
1473 C->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
1474 }
1475 }
1476
1477 // Validate users of merge
1478 for (DUIterator_Fast imax, i = merge->fast_outs(imax); i < imax; i++) {
1479 Node* sfpt = merge->fast_out(i);
1480 if (sfpt->is_SafePoint()) {
1481 int merge_idx = merge->merge_pointer_idx(sfpt->as_SafePoint()->jvms());
1482
1483 if (sfpt->in(merge_idx) != nullptr && sfpt->in(merge_idx)->is_SafePointScalarMerge()) {
1484 assert(false, "SafePointScalarMerge nodes can't be nested.");
1485 C->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
1486 }
1487 } else {
1488 assert(false, "Only safepoints can use SafePointScalarMerge nodes.");
1489 C->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
1490 }
1491 }
1492 }
1493
1494 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1495 Node* m = n->fast_out(i);
1496 ideal_nodes.push(m);
1497 }
1498 }
1499 }
1500
1501 // Returns true if there is an object in the scope of sfn that does not escape globally.
1502 bool ConnectionGraph::has_ea_local_in_scope(SafePointNode* sfn) {
1503 Compile* C = _compile;
1504 for (JVMState* jvms = sfn->jvms(); jvms != nullptr; jvms = jvms->caller()) {
1505 if (C->env()->should_retain_local_variables() || C->env()->jvmti_can_walk_any_space() ||
1506 DeoptimizeObjectsALot) {
1507 // Jvmti agents can access locals. Must provide info about local objects at runtime.
1508 int num_locs = jvms->loc_size();
1509 for (int idx = 0; idx < num_locs; idx++) {
1510 Node* l = sfn->local(jvms, idx);
1511 if (not_global_escape(l)) {
1512 return true;
1513 }
1514 }
1515 }
1516 if (C->env()->jvmti_can_get_owned_monitor_info() ||
1517 C->env()->jvmti_can_walk_any_space() || DeoptimizeObjectsALot) {
1518 // Jvmti agents can read monitors. Must provide info about locked objects at runtime.
1519 int num_mon = jvms->nof_monitors();
1520 for (int idx = 0; idx < num_mon; idx++) {
1521 Node* m = sfn->monitor_obj(jvms, idx);
1522 if (m != nullptr && not_global_escape(m)) {
1523 return true;
1524 }
1525 }
1526 }
1527 }
1528 return false;
1529 }
1530
1531 // Returns true if at least one of the arguments to the call is an object
1532 // that does not escape globally.
1533 bool ConnectionGraph::has_arg_escape(CallJavaNode* call) {
1534 if (call->method() != nullptr) {
1535 uint max_idx = TypeFunc::Parms + call->method()->arg_size();
1536 for (uint idx = TypeFunc::Parms; idx < max_idx; idx++) {
1537 Node* p = call->in(idx);
1538 if (not_global_escape(p)) {
1539 return true;
1540 }
1541 }
1542 } else {
1543 const char* name = call->as_CallStaticJava()->_name;
1544 assert(name != nullptr, "no name");
1545 // no arg escapes through uncommon traps
1546 if (strcmp(name, "uncommon_trap") != 0) {
1547 // process_call_arguments() assumes that all arguments escape globally
1548 const TypeTuple* d = call->tf()->domain();
1549 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1550 const Type* at = d->field_at(i);
1551 if (at->isa_oopptr() != nullptr) {
1552 return true;
1553 }
1554 }
1555 }
1556 }
1557 return false;
1558 }
1559
1560
1561
1562 // Utility function for nodes that load an object
1563 void ConnectionGraph::add_objload_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
1564 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1565 // ThreadLocal has RawPtr type.
1566 const Type* t = _igvn->type(n);
1567 if (t->make_ptr() != nullptr) {
1568 Node* adr = n->in(MemNode::Address);
1569 #ifdef ASSERT
1570 if (!adr->is_AddP()) {
1571 assert(_igvn->type(adr)->isa_rawptr(), "sanity");
1572 } else {
1573 assert((ptnode_adr(adr->_idx) == nullptr ||
1574 ptnode_adr(adr->_idx)->as_Field()->is_oop()), "sanity");
1575 }
1576 #endif
1577 add_local_var_and_edge(n, PointsToNode::NoEscape,
1578 adr, delayed_worklist);
1579 }
1580 }
1581
1582 // Populate Connection Graph with PointsTo nodes and create simple
1583 // connection graph edges.
1584 void ConnectionGraph::add_node_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
1585 assert(!_verify, "this method should not be called for verification");
1586 PhaseGVN* igvn = _igvn;
1587 uint n_idx = n->_idx;
1588 PointsToNode* n_ptn = ptnode_adr(n_idx);
1589 if (n_ptn != nullptr) {
1590 return; // No need to redefine PointsTo node during first iteration.
1591 }
1592 int opcode = n->Opcode();
1593 bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->escape_add_to_con_graph(this, igvn, delayed_worklist, n, opcode);
1594 if (gc_handled) {
1595 return; // Ignore node if already handled by GC.
1596 }
1597
1598 if (n->is_Call()) {
1599 // Arguments to allocation and locking don't escape.
1600 if (n->is_AbstractLock()) {
1601 // Put Lock and Unlock nodes on IGVN worklist to process them during
1602 // first IGVN optimization when escape information is still available.
1603 record_for_optimizer(n);
1604 } else if (n->is_Allocate()) {
1605 add_call_node(n->as_Call());
1606 record_for_optimizer(n);
1607 } else {
1608 if (n->is_CallStaticJava()) {
1609 const char* name = n->as_CallStaticJava()->_name;
1610 if (name != nullptr && strcmp(name, "uncommon_trap") == 0) {
1611 return; // Skip uncommon traps
1612 }
1613 }
1614 // Don't mark as processed since call's arguments have to be processed.
1615 delayed_worklist->push(n);
1616 // Check if a call returns an object.
1617 if ((n->as_Call()->returns_pointer() &&
1618 n->as_Call()->proj_out_or_null(TypeFunc::Parms) != nullptr) ||
1619 (n->is_CallStaticJava() &&
1620 n->as_CallStaticJava()->is_boxing_method())) {
1621 add_call_node(n->as_Call());
1622 }
1623 }
1624 return;
1625 }
1626 // Put this check here to process call arguments since some call nodes
1627 // point to phantom_obj.
1628 if (n_ptn == phantom_obj || n_ptn == null_obj) {
1629 return; // Skip predefined nodes.
1630 }
1631 switch (opcode) {
1632 case Op_AddP: {
1633 Node* base = get_addp_base(n);
1634 PointsToNode* ptn_base = ptnode_adr(base->_idx);
1635 // Field nodes are created for all field types. They are used in
1636 // adjust_scalar_replaceable_state() and split_unique_types().
1637 // Note, non-oop fields will have only base edges in Connection
1638 // Graph because such fields are not used for oop loads and stores.
1639 int offset = address_offset(n, igvn);
1640 add_field(n, PointsToNode::NoEscape, offset);
1641 if (ptn_base == nullptr) {
1642 delayed_worklist->push(n); // Process it later.
1643 } else {
1644 n_ptn = ptnode_adr(n_idx);
1645 add_base(n_ptn->as_Field(), ptn_base);
1646 }
1647 break;
1648 }
1649 case Op_CastX2P: {
1650 map_ideal_node(n, phantom_obj);
1651 break;
1652 }
1653 case Op_CastPP:
1654 case Op_CheckCastPP:
1655 case Op_EncodeP:
1656 case Op_DecodeN:
1657 case Op_EncodePKlass:
1658 case Op_DecodeNKlass: {
1659 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), delayed_worklist);
1660 break;
1661 }
1662 case Op_CMoveP: {
1663 add_local_var(n, PointsToNode::NoEscape);
1664 // Do not add edges during first iteration because some could be
1665 // not defined yet.
1666 delayed_worklist->push(n);
1667 break;
1668 }
1669 case Op_ConP:
1670 case Op_ConN:
1671 case Op_ConNKlass: {
1672 // assume all oop constants globally escape except for null
1673 PointsToNode::EscapeState es;
1674 const Type* t = igvn->type(n);
1675 if (t == TypePtr::NULL_PTR || t == TypeNarrowOop::NULL_PTR) {
1676 es = PointsToNode::NoEscape;
1677 } else {
1678 es = PointsToNode::GlobalEscape;
1679 }
1680 PointsToNode* ptn_con = add_java_object(n, es);
1681 set_not_scalar_replaceable(ptn_con NOT_PRODUCT(COMMA "Constant pointer"));
1682 break;
1683 }
1684 case Op_CreateEx: {
1685 // assume that all exception objects globally escape
1686 map_ideal_node(n, phantom_obj);
1687 break;
1688 }
1689 case Op_LoadKlass:
1690 case Op_LoadNKlass: {
1691 // Unknown class is loaded
1692 map_ideal_node(n, phantom_obj);
1693 break;
1694 }
1695 case Op_LoadP:
1696 case Op_LoadN: {
1697 add_objload_to_connection_graph(n, delayed_worklist);
1698 break;
1699 }
1700 case Op_Parm: {
1701 map_ideal_node(n, phantom_obj);
1702 break;
1703 }
1704 case Op_PartialSubtypeCheck: {
1705 // Produces Null or notNull and is used in only in CmpP so
1706 // phantom_obj could be used.
1707 map_ideal_node(n, phantom_obj); // Result is unknown
1708 break;
1709 }
1710 case Op_Phi: {
1711 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1712 // ThreadLocal has RawPtr type.
1713 const Type* t = n->as_Phi()->type();
1714 if (t->make_ptr() != nullptr) {
1715 add_local_var(n, PointsToNode::NoEscape);
1716 // Do not add edges during first iteration because some could be
1717 // not defined yet.
1718 delayed_worklist->push(n);
1719 }
1720 break;
1721 }
1722 case Op_Proj: {
1723 // we are only interested in the oop result projection from a call
1724 if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&1725 n->in(0)->as_Call()->returns_pointer()) {1726 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist);1727 }
1728 break;
1729 }
1730 case Op_Rethrow: // Exception object escapes
1731 case Op_Return: {
1732 if (n->req() > TypeFunc::Parms &&
1733 igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
1734 // Treat Return value as LocalVar with GlobalEscape escape state.
1735 add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), delayed_worklist);
1736 }
1737 break;
1738 }
1739 case Op_CompareAndExchangeP:
1740 case Op_CompareAndExchangeN:
1741 case Op_GetAndSetP:
1742 case Op_GetAndSetN: {
1743 add_objload_to_connection_graph(n, delayed_worklist);
1744 // fall-through
1745 }
1746 case Op_StoreP:
1747 case Op_StoreN:
1748 case Op_StoreNKlass:
1749 case Op_WeakCompareAndSwapP:
1750 case Op_WeakCompareAndSwapN:
1751 case Op_CompareAndSwapP:
1752 case Op_CompareAndSwapN: {
1753 add_to_congraph_unsafe_access(n, opcode, delayed_worklist);
1754 break;
1755 }
1756 case Op_AryEq:
1757 case Op_CountPositives:
1758 case Op_StrComp:
1759 case Op_StrEquals:
1760 case Op_StrIndexOf:
1761 case Op_StrIndexOfChar:
1762 case Op_StrInflatedCopy:
1763 case Op_StrCompressedCopy:
1764 case Op_VectorizedHashCode:
1765 case Op_EncodeISOArray: {
1766 add_local_var(n, PointsToNode::ArgEscape);
1767 delayed_worklist->push(n); // Process it later.
1768 break;
1769 }
1770 case Op_ThreadLocal: {
1771 PointsToNode* ptn_thr = add_java_object(n, PointsToNode::ArgEscape);
1772 set_not_scalar_replaceable(ptn_thr NOT_PRODUCT(COMMA "Constant pointer"));
1773 break;
1774 }
1775 case Op_Blackhole: {
1776 // All blackhole pointer arguments are globally escaping.
1777 // Only do this if there is at least one pointer argument.
1778 // Do not add edges during first iteration because some could be
1779 // not defined yet, defer to final step.
1780 for (uint i = 0; i < n->req(); i++) {
1781 Node* in = n->in(i);
1782 if (in != nullptr) {
1783 const Type* at = _igvn->type(in);
1784 if (!at->isa_ptr()) continue;
1785
1786 add_local_var(n, PointsToNode::GlobalEscape);
1787 delayed_worklist->push(n);
1788 break;
1789 }
1790 }
1791 break;
1792 }
1793 default:
1794 ; // Do nothing for nodes not related to EA.
1795 }
1796 return;
1797 }
1798
1799 // Add final simple edges to graph.
1800 void ConnectionGraph::add_final_edges(Node *n) {
1801 PointsToNode* n_ptn = ptnode_adr(n->_idx);
1802 #ifdef ASSERT
1803 if (_verify && n_ptn->is_JavaObject())
1804 return; // This method does not change graph for JavaObject.
1805 #endif
1806
1807 if (n->is_Call()) {
1808 process_call_arguments(n->as_Call());
1809 return;
1810 }
1811 assert(n->is_Store() || n->is_LoadStore() ||
1812 ((n_ptn != nullptr) && (n_ptn->ideal_node() != nullptr)),
1813 "node should be registered already");
1814 int opcode = n->Opcode();
1815 bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->escape_add_final_edges(this, _igvn, n, opcode);
1816 if (gc_handled) {
1817 return; // Ignore node if already handled by GC.
1818 }
1819 switch (opcode) {
1820 case Op_AddP: {
1821 Node* base = get_addp_base(n);
1822 PointsToNode* ptn_base = ptnode_adr(base->_idx);
1823 assert(ptn_base != nullptr, "field's base should be registered");
1824 add_base(n_ptn->as_Field(), ptn_base);
1825 break;
1826 }
1827 case Op_CastPP:
1828 case Op_CheckCastPP:
1829 case Op_EncodeP:
1830 case Op_DecodeN:
1831 case Op_EncodePKlass:
1832 case Op_DecodeNKlass: {
1833 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), nullptr);
1834 break;
1835 }
1836 case Op_CMoveP: {
1837 for (uint i = CMoveNode::IfFalse; i < n->req(); i++) {
1838 Node* in = n->in(i);
1839 if (in == nullptr) {
1840 continue; // ignore null
1841 }
1842 Node* uncast_in = in->uncast();
1843 if (uncast_in->is_top() || uncast_in == n) {
1844 continue; // ignore top or inputs which go back this node
1845 }
1846 PointsToNode* ptn = ptnode_adr(in->_idx);
1847 assert(ptn != nullptr, "node should be registered");
1848 add_edge(n_ptn, ptn);
1849 }
1850 break;
1851 }
1852 case Op_LoadP:
1853 case Op_LoadN: {
1854 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1855 // ThreadLocal has RawPtr type.
1856 assert(_igvn->type(n)->make_ptr() != nullptr, "Unexpected node type");
1857 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(MemNode::Address), nullptr);
1858 break;
1859 }
1860 case Op_Phi: {
1861 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1862 // ThreadLocal has RawPtr type.
1863 assert(n->as_Phi()->type()->make_ptr() != nullptr, "Unexpected node type");
1864 for (uint i = 1; i < n->req(); i++) {
1865 Node* in = n->in(i);
1866 if (in == nullptr) {
1867 continue; // ignore null
1868 }
1869 Node* uncast_in = in->uncast();
1870 if (uncast_in->is_top() || uncast_in == n) {
1871 continue; // ignore top or inputs which go back this node
1872 }
1873 PointsToNode* ptn = ptnode_adr(in->_idx);
1874 assert(ptn != nullptr, "node should be registered");
1875 add_edge(n_ptn, ptn);
1876 }
1877 break;
1878 }
1879 case Op_Proj: {
1880 // we are only interested in the oop result projection from a call1881 assert(n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&1882 n->in(0)->as_Call()->returns_pointer(), "Unexpected node type");1883 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), nullptr);
1884 break;
1885 }
1886 case Op_Rethrow: // Exception object escapes
1887 case Op_Return: {
1888 assert(n->req() > TypeFunc::Parms && _igvn->type(n->in(TypeFunc::Parms))->isa_oopptr(),
1889 "Unexpected node type");
1890 // Treat Return value as LocalVar with GlobalEscape escape state.
1891 add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), nullptr);
1892 break;
1893 }
1894 case Op_CompareAndExchangeP:
1895 case Op_CompareAndExchangeN:
1896 case Op_GetAndSetP:
1897 case Op_GetAndSetN:{
1898 assert(_igvn->type(n)->make_ptr() != nullptr, "Unexpected node type");
1899 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(MemNode::Address), nullptr);
1900 // fall-through
1901 }
1902 case Op_CompareAndSwapP:
1903 case Op_CompareAndSwapN:
1904 case Op_WeakCompareAndSwapP:
1905 case Op_WeakCompareAndSwapN:
1906 case Op_StoreP:
1907 case Op_StoreN:
1908 case Op_StoreNKlass:{
1909 add_final_edges_unsafe_access(n, opcode);
1910 break;
1911 }
1912 case Op_VectorizedHashCode:
1913 case Op_AryEq:
1914 case Op_CountPositives:
1915 case Op_StrComp:
1916 case Op_StrEquals:
1917 case Op_StrIndexOf:
1918 case Op_StrIndexOfChar:
1919 case Op_StrInflatedCopy:
1920 case Op_StrCompressedCopy:
1921 case Op_EncodeISOArray: {
1922 // char[]/byte[] arrays passed to string intrinsic do not escape but
1923 // they are not scalar replaceable. Adjust escape state for them.
1924 // Start from in(2) edge since in(1) is memory edge.
1925 for (uint i = 2; i < n->req(); i++) {
1926 Node* adr = n->in(i);
1927 const Type* at = _igvn->type(adr);
1928 if (!adr->is_top() && at->isa_ptr()) {
1929 assert(at == Type::TOP || at == TypePtr::NULL_PTR ||
1930 at->isa_ptr() != nullptr, "expecting a pointer");
1931 if (adr->is_AddP()) {
1932 adr = get_addp_base(adr);
1933 }
1934 PointsToNode* ptn = ptnode_adr(adr->_idx);
1935 assert(ptn != nullptr, "node should be registered");
1936 add_edge(n_ptn, ptn);
1937 }
1938 }
1939 break;
1940 }
1941 case Op_Blackhole: {
1942 // All blackhole pointer arguments are globally escaping.
1943 for (uint i = 0; i < n->req(); i++) {
1944 Node* in = n->in(i);
1945 if (in != nullptr) {
1946 const Type* at = _igvn->type(in);
1947 if (!at->isa_ptr()) continue;
1948
1949 if (in->is_AddP()) {
1950 in = get_addp_base(in);
1951 }
1952
1953 PointsToNode* ptn = ptnode_adr(in->_idx);
1954 assert(ptn != nullptr, "should be defined already");
1955 set_escape_state(ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "blackhole"));
1956 add_edge(n_ptn, ptn);
1957 }
1958 }
1959 break;
1960 }
1961 default: {
1962 // This method should be called only for EA specific nodes which may
1963 // miss some edges when they were created.
1964 #ifdef ASSERT
1965 n->dump(1);
1966 #endif
1967 guarantee(false, "unknown node");
1968 }
1969 }
1970 return;
1971 }
1972
1973 void ConnectionGraph::add_to_congraph_unsafe_access(Node* n, uint opcode, Unique_Node_List* delayed_worklist) {
1974 Node* adr = n->in(MemNode::Address);
1975 const Type* adr_type = _igvn->type(adr);
1976 adr_type = adr_type->make_ptr();
1977 if (adr_type == nullptr) {
1978 return; // skip dead nodes
1979 }
1980 if (adr_type->isa_oopptr()
1981 || ((opcode == Op_StoreP || opcode == Op_StoreN || opcode == Op_StoreNKlass)
1982 && adr_type == TypeRawPtr::NOTNULL
1983 && is_captured_store_address(adr))) {
1984 delayed_worklist->push(n); // Process it later.
1985 #ifdef ASSERT
1986 assert (adr->is_AddP(), "expecting an AddP");
1987 if (adr_type == TypeRawPtr::NOTNULL) {
1988 // Verify a raw address for a store captured by Initialize node.
1989 int offs = (int) _igvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
1990 assert(offs != Type::OffsetBot, "offset must be a constant");
1991 }
1992 #endif
1993 } else {
1994 // Ignore copy the displaced header to the BoxNode (OSR compilation).
1995 if (adr->is_BoxLock()) {
1996 return;
1997 }
1998 // Stored value escapes in unsafe access.
1999 if ((opcode == Op_StoreP) && adr_type->isa_rawptr()) {
2000 delayed_worklist->push(n); // Process unsafe access later.
2001 return;
2002 }
2003 #ifdef ASSERT
2004 n->dump(1);
2005 assert(false, "not unsafe");
2006 #endif
2007 }
2008 }
2009
2010 bool ConnectionGraph::add_final_edges_unsafe_access(Node* n, uint opcode) {
2011 Node* adr = n->in(MemNode::Address);
2012 const Type *adr_type = _igvn->type(adr);
2013 adr_type = adr_type->make_ptr();
2014 #ifdef ASSERT
2015 if (adr_type == nullptr) {
2016 n->dump(1);
2017 assert(adr_type != nullptr, "dead node should not be on list");
2018 return true;
2019 }
2020 #endif
2021
2022 if (adr_type->isa_oopptr()
2023 || ((opcode == Op_StoreP || opcode == Op_StoreN || opcode == Op_StoreNKlass)
2024 && adr_type == TypeRawPtr::NOTNULL
2025 && is_captured_store_address(adr))) {
2026 // Point Address to Value
2027 PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
2028 assert(adr_ptn != nullptr &&
2029 adr_ptn->as_Field()->is_oop(), "node should be registered");
2030 Node* val = n->in(MemNode::ValueIn);
2031 PointsToNode* ptn = ptnode_adr(val->_idx);
2032 assert(ptn != nullptr, "node should be registered");
2033 add_edge(adr_ptn, ptn);
2034 return true;
2035 } else if ((opcode == Op_StoreP) && adr_type->isa_rawptr()) {
2036 // Stored value escapes in unsafe access.
2037 Node* val = n->in(MemNode::ValueIn);
2038 PointsToNode* ptn = ptnode_adr(val->_idx);
2039 assert(ptn != nullptr, "node should be registered");
2040 set_escape_state(ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "stored at raw address"));
2041 // Add edge to object for unsafe access with offset.
2042 PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
2043 assert(adr_ptn != nullptr, "node should be registered");
2044 if (adr_ptn->is_Field()) {
2045 assert(adr_ptn->as_Field()->is_oop(), "should be oop field");
2046 add_edge(adr_ptn, ptn);
2047 }
2048 return true;
2049 }
2050 #ifdef ASSERT
2051 n->dump(1);
2052 assert(false, "not unsafe");
2053 #endif
2054 return false;
2055 }
2056
2057 void ConnectionGraph::add_call_node(CallNode* call) {
2058 assert(call->returns_pointer(), "only for call which returns pointer");
2059 uint call_idx = call->_idx;
2060 if (call->is_Allocate()) {
2061 Node* k = call->in(AllocateNode::KlassNode);
2062 const TypeKlassPtr* kt = k->bottom_type()->isa_klassptr();
2063 assert(kt != nullptr, "TypeKlassPtr required.");
2064 PointsToNode::EscapeState es = PointsToNode::NoEscape;
2065 bool scalar_replaceable = true;
2066 NOT_PRODUCT(const char* nsr_reason = "");
2067 if (call->is_AllocateArray()) {
2068 if (!kt->isa_aryklassptr()) { // StressReflectiveCode
2069 es = PointsToNode::GlobalEscape;
2070 } else {
2071 int length = call->in(AllocateNode::ALength)->find_int_con(-1);
2072 if (length < 0) {
2073 // Not scalar replaceable if the length is not constant.
2074 scalar_replaceable = false;
2075 NOT_PRODUCT(nsr_reason = "has a non-constant length");
2076 } else if (length > EliminateAllocationArraySizeLimit) {
2077 // Not scalar replaceable if the length is too big.
2078 scalar_replaceable = false;
2079 NOT_PRODUCT(nsr_reason = "has a length that is too big");
2080 }
2081 }
2082 } else { // Allocate instance
2083 if (!kt->isa_instklassptr()) { // StressReflectiveCode
2084 es = PointsToNode::GlobalEscape;
2085 } else {
2086 const TypeInstKlassPtr* ikt = kt->is_instklassptr();
2087 ciInstanceKlass* ik = ikt->klass_is_exact() ? ikt->exact_klass()->as_instance_klass() : ikt->instance_klass();
2088 if (ik->is_subclass_of(_compile->env()->Thread_klass()) ||
2089 ik->is_subclass_of(_compile->env()->Reference_klass()) ||
2090 !ik->can_be_instantiated() ||
2091 ik->has_finalizer()) {
2092 es = PointsToNode::GlobalEscape;
2093 } else {
2094 int nfields = ik->as_instance_klass()->nof_nonstatic_fields();
2095 if (nfields > EliminateAllocationFieldsLimit) {
2096 // Not scalar replaceable if there are too many fields.
2097 scalar_replaceable = false;
2098 NOT_PRODUCT(nsr_reason = "has too many fields");
2099 }
2100 }
2101 }
2102 }
2103 add_java_object(call, es);
2104 PointsToNode* ptn = ptnode_adr(call_idx);
2105 if (!scalar_replaceable && ptn->scalar_replaceable()) {
2106 set_not_scalar_replaceable(ptn NOT_PRODUCT(COMMA nsr_reason));
2107 }
2108 } else if (call->is_CallStaticJava()) {
2109 // Call nodes could be different types:
2110 //
2111 // 1. CallDynamicJavaNode (what happened during call is unknown):
2112 //
2113 // - mapped to GlobalEscape JavaObject node if oop is returned;
2114 //
2115 // - all oop arguments are escaping globally;
2116 //
2117 // 2. CallStaticJavaNode (execute bytecode analysis if possible):
2118 //
2119 // - the same as CallDynamicJavaNode if can't do bytecode analysis;
2120 //
2121 // - mapped to GlobalEscape JavaObject node if unknown oop is returned;
2122 // - mapped to NoEscape JavaObject node if non-escaping object allocated
2123 // during call is returned;
2124 // - mapped to ArgEscape LocalVar node pointed to object arguments
2125 // which are returned and does not escape during call;
2126 //
2127 // - oop arguments escaping status is defined by bytecode analysis;
2128 //
2129 // For a static call, we know exactly what method is being called.
2130 // Use bytecode estimator to record whether the call's return value escapes.
2131 ciMethod* meth = call->as_CallJava()->method();
2132 if (meth == nullptr) {
2133 assert(call->as_CallStaticJava()->is_call_to_multianewarray_stub(), "TODO: add failed case check");
2134 // Returns a newly allocated non-escaped object.
2135 add_java_object(call, PointsToNode::NoEscape);
2136 set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of multinewarray"));
2137 } else if (meth->is_boxing_method()) {
2138 // Returns boxing object
2139 PointsToNode::EscapeState es;
2140 vmIntrinsics::ID intr = meth->intrinsic_id();
2141 if (intr == vmIntrinsics::_floatValue || intr == vmIntrinsics::_doubleValue) {
2142 // It does not escape if object is always allocated.
2143 es = PointsToNode::NoEscape;
2144 } else {
2145 // It escapes globally if object could be loaded from cache.
2146 es = PointsToNode::GlobalEscape;
2147 }
2148 add_java_object(call, es);
2149 if (es == PointsToNode::GlobalEscape) {
2150 set_not_scalar_replaceable(ptnode_adr(call->_idx) NOT_PRODUCT(COMMA "object can be loaded from boxing cache"));
2151 }
2152 } else {
2153 BCEscapeAnalyzer* call_analyzer = meth->get_bcea();
2154 call_analyzer->copy_dependencies(_compile->dependencies());
2155 if (call_analyzer->is_return_allocated()) {
2156 // Returns a newly allocated non-escaped object, simply
2157 // update dependency information.
2158 // Mark it as NoEscape so that objects referenced by
2159 // it's fields will be marked as NoEscape at least.
2160 add_java_object(call, PointsToNode::NoEscape);
2161 set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of call"));
2162 } else {
2163 // Determine whether any arguments are returned.2164 const TypeTuple* d = call->tf()->domain();2165 bool ret_arg = false;2166 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {2167 if (d->field_at(i)->isa_ptr() != nullptr &&2168 call_analyzer->is_arg_returned(i - TypeFunc::Parms)) {2169 ret_arg = true;2170 break;2171 }2172 }2173 if (ret_arg) {
2174 add_local_var(call, PointsToNode::ArgEscape);
2175 } else {
2176 // Returns unknown object.
2177 map_ideal_node(call, phantom_obj);
2178 }
2179 }
2180 }
2181 } else {
2182 // An other type of call, assume the worst case:
2183 // returned value is unknown and globally escapes.
2184 assert(call->Opcode() == Op_CallDynamicJava, "add failed case check");
2185 map_ideal_node(call, phantom_obj);
2186 }
2187 }
2188
2189 void ConnectionGraph::process_call_arguments(CallNode *call) {
2190 bool is_arraycopy = false;
2191 switch (call->Opcode()) {
2192 #ifdef ASSERT
2193 case Op_Allocate:
2194 case Op_AllocateArray:
2195 case Op_Lock:
2196 case Op_Unlock:
2197 assert(false, "should be done already");
2198 break;
2199 #endif
2200 case Op_ArrayCopy:
2201 case Op_CallLeafNoFP:
2202 // Most array copies are ArrayCopy nodes at this point but there
2203 // are still a few direct calls to the copy subroutines (See
2204 // PhaseStringOpts::copy_string())
2205 is_arraycopy = (call->Opcode() == Op_ArrayCopy) ||
2206 call->as_CallLeaf()->is_call_to_arraycopystub();
2207 // fall through
2208 case Op_CallLeafVector:
2209 case Op_CallLeaf: {
2210 // Stub calls, objects do not escape but they are not scale replaceable.
2211 // Adjust escape state for outgoing arguments.
2212 const TypeTuple * d = call->tf()->domain();
2213 bool src_has_oops = false;
2214 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2215 const Type* at = d->field_at(i);
2216 Node *arg = call->in(i);
2217 if (arg == nullptr) {
2218 continue;
2219 }
2220 const Type *aat = _igvn->type(arg);
2221 if (arg->is_top() || !at->isa_ptr() || !aat->isa_ptr()) {
2222 continue;
2223 }
2224 if (arg->is_AddP()) {
2225 //
2226 // The inline_native_clone() case when the arraycopy stub is called
2227 // after the allocation before Initialize and CheckCastPP nodes.
2228 // Or normal arraycopy for object arrays case.
2229 //
2230 // Set AddP's base (Allocate) as not scalar replaceable since
2231 // pointer to the base (with offset) is passed as argument.
2232 //
2233 arg = get_addp_base(arg);
2234 }
2235 PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2236 assert(arg_ptn != nullptr, "should be registered");
2237 PointsToNode::EscapeState arg_esc = arg_ptn->escape_state();
2238 if (is_arraycopy || arg_esc < PointsToNode::ArgEscape) {
2239 assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
2240 aat->isa_ptr() != nullptr, "expecting an Ptr");
2241 bool arg_has_oops = aat->isa_oopptr() &&
2242 (aat->isa_instptr() ||
2243 (aat->isa_aryptr() && (aat->isa_aryptr()->elem() == Type::BOTTOM || aat->isa_aryptr()->elem()->make_oopptr() != nullptr)));
2244 if (i == TypeFunc::Parms) {
2245 src_has_oops = arg_has_oops;
2246 }
2247 //
2248 // src or dst could be j.l.Object when other is basic type array:
2249 //
2250 // arraycopy(char[],0,Object*,0,size);
2251 // arraycopy(Object*,0,char[],0,size);
2252 //
2253 // Don't add edges in such cases.
2254 //
2255 bool arg_is_arraycopy_dest = src_has_oops && is_arraycopy &&
2256 arg_has_oops && (i > TypeFunc::Parms);
2257 #ifdef ASSERT
2258 if (!(is_arraycopy ||
2259 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(call) ||
2260 (call->as_CallLeaf()->_name != nullptr &&
2261 (strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32") == 0 ||
2262 strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32C") == 0 ||
2263 strcmp(call->as_CallLeaf()->_name, "updateBytesAdler32") == 0 ||
2264 strcmp(call->as_CallLeaf()->_name, "aescrypt_encryptBlock") == 0 ||
2265 strcmp(call->as_CallLeaf()->_name, "aescrypt_decryptBlock") == 0 ||
2266 strcmp(call->as_CallLeaf()->_name, "cipherBlockChaining_encryptAESCrypt") == 0 ||
2267 strcmp(call->as_CallLeaf()->_name, "cipherBlockChaining_decryptAESCrypt") == 0 ||
2268 strcmp(call->as_CallLeaf()->_name, "electronicCodeBook_encryptAESCrypt") == 0 ||
2269 strcmp(call->as_CallLeaf()->_name, "electronicCodeBook_decryptAESCrypt") == 0 ||
2270 strcmp(call->as_CallLeaf()->_name, "counterMode_AESCrypt") == 0 ||
2271 strcmp(call->as_CallLeaf()->_name, "galoisCounterMode_AESCrypt") == 0 ||
2272 strcmp(call->as_CallLeaf()->_name, "poly1305_processBlocks") == 0 ||
2273 strcmp(call->as_CallLeaf()->_name, "intpoly_montgomeryMult_P256") == 0 ||
2274 strcmp(call->as_CallLeaf()->_name, "intpoly_assign") == 0 ||
2275 strcmp(call->as_CallLeaf()->_name, "intpoly_mult_25519") == 0 ||
2276 strcmp(call->as_CallLeaf()->_name, "intpoly_square_25519") == 0 ||
2277 strcmp(call->as_CallLeaf()->_name, "ghash_processBlocks") == 0 ||
2278 strcmp(call->as_CallLeaf()->_name, "chacha20Block") == 0 ||
2279 strcmp(call->as_CallLeaf()->_name, "kyberNtt") == 0 ||
2280 strcmp(call->as_CallLeaf()->_name, "kyberInverseNtt") == 0 ||
2281 strcmp(call->as_CallLeaf()->_name, "kyberNttMult") == 0 ||
2282 strcmp(call->as_CallLeaf()->_name, "kyberAddPoly_2") == 0 ||
2283 strcmp(call->as_CallLeaf()->_name, "kyberAddPoly_3") == 0 ||
2284 strcmp(call->as_CallLeaf()->_name, "kyber12To16") == 0 ||
2285 strcmp(call->as_CallLeaf()->_name, "kyberBarrettReduce") == 0 ||
2286 strcmp(call->as_CallLeaf()->_name, "dilithiumAlmostNtt") == 0 ||
2287 strcmp(call->as_CallLeaf()->_name, "dilithiumAlmostInverseNtt") == 0 ||
2288 strcmp(call->as_CallLeaf()->_name, "dilithiumNttMult") == 0 ||
2289 strcmp(call->as_CallLeaf()->_name, "dilithiumMontMulByConstant") == 0 ||
2290 strcmp(call->as_CallLeaf()->_name, "dilithiumDecomposePoly") == 0 ||
2291 strcmp(call->as_CallLeaf()->_name, "encodeBlock") == 0 ||
2292 strcmp(call->as_CallLeaf()->_name, "decodeBlock") == 0 ||
2293 strcmp(call->as_CallLeaf()->_name, "md5_implCompress") == 0 ||
2294 strcmp(call->as_CallLeaf()->_name, "md5_implCompressMB") == 0 ||
2295 strcmp(call->as_CallLeaf()->_name, "sha1_implCompress") == 0 ||
2296 strcmp(call->as_CallLeaf()->_name, "sha1_implCompressMB") == 0 ||
2297 strcmp(call->as_CallLeaf()->_name, "sha256_implCompress") == 0 ||
2298 strcmp(call->as_CallLeaf()->_name, "sha256_implCompressMB") == 0 ||
2299 strcmp(call->as_CallLeaf()->_name, "sha512_implCompress") == 0 ||
2300 strcmp(call->as_CallLeaf()->_name, "sha512_implCompressMB") == 0 ||
2301 strcmp(call->as_CallLeaf()->_name, "sha3_implCompress") == 0 ||
2302 strcmp(call->as_CallLeaf()->_name, "double_keccak") == 0 ||
2303 strcmp(call->as_CallLeaf()->_name, "quad_keccak") == 0 ||
2304 strcmp(call->as_CallLeaf()->_name, "sha3_implCompressMB") == 0 ||
2305 strcmp(call->as_CallLeaf()->_name, "multiplyToLen") == 0 ||
2306 strcmp(call->as_CallLeaf()->_name, "squareToLen") == 0 ||
2307 strcmp(call->as_CallLeaf()->_name, "mulAdd") == 0 ||
2308 strcmp(call->as_CallLeaf()->_name, "montgomery_multiply") == 0 ||
2309 strcmp(call->as_CallLeaf()->_name, "montgomery_square") == 0 ||
2310 strcmp(call->as_CallLeaf()->_name, "bigIntegerRightShiftWorker") == 0 ||
2311 strcmp(call->as_CallLeaf()->_name, "bigIntegerLeftShiftWorker") == 0 ||
2312 strcmp(call->as_CallLeaf()->_name, "vectorizedMismatch") == 0 ||
2313 strcmp(call->as_CallLeaf()->_name, "stringIndexOf") == 0 ||
2314 strcmp(call->as_CallLeaf()->_name, "arraysort_stub") == 0 ||
2315 strcmp(call->as_CallLeaf()->_name, "array_partition_stub") == 0 ||
2316 strcmp(call->as_CallLeaf()->_name, "get_class_id_intrinsic") == 0 ||
2317 strcmp(call->as_CallLeaf()->_name, "unsafe_setmemory") == 0)
2318 ))) {
2319 call->dump();
2320 fatal("EA unexpected CallLeaf %s", call->as_CallLeaf()->_name);
2321 }
2322 #endif
2323 // Always process arraycopy's destination object since
2324 // we need to add all possible edges to references in
2325 // source object.
2326 if (arg_esc >= PointsToNode::ArgEscape &&
2327 !arg_is_arraycopy_dest) {
2328 continue;
2329 }
2330 PointsToNode::EscapeState es = PointsToNode::ArgEscape;
2331 if (call->is_ArrayCopy()) {
2332 ArrayCopyNode* ac = call->as_ArrayCopy();
2333 if (ac->is_clonebasic() ||
2334 ac->is_arraycopy_validated() ||
2335 ac->is_copyof_validated() ||
2336 ac->is_copyofrange_validated()) {
2337 es = PointsToNode::NoEscape;
2338 }
2339 }
2340 set_escape_state(arg_ptn, es NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2341 if (arg_is_arraycopy_dest) {
2342 Node* src = call->in(TypeFunc::Parms);
2343 if (src->is_AddP()) {
2344 src = get_addp_base(src);
2345 }
2346 PointsToNode* src_ptn = ptnode_adr(src->_idx);
2347 assert(src_ptn != nullptr, "should be registered");
2348 // Special arraycopy edge:
2349 // Only escape state of destination object's fields affects
2350 // escape state of fields in source object.
2351 add_arraycopy(call, es, src_ptn, arg_ptn);
2352 }
2353 }
2354 }
2355 break;
2356 }
2357 case Op_CallStaticJava: {
2358 // For a static call, we know exactly what method is being called.
2359 // Use bytecode estimator to record the call's escape affects
2360 #ifdef ASSERT
2361 const char* name = call->as_CallStaticJava()->_name;
2362 assert((name == nullptr || strcmp(name, "uncommon_trap") != 0), "normal calls only");
2363 #endif
2364 ciMethod* meth = call->as_CallJava()->method();
2365 if ((meth != nullptr) && meth->is_boxing_method()) {
2366 break; // Boxing methods do not modify any oops.
2367 }
2368 BCEscapeAnalyzer* call_analyzer = (meth !=nullptr) ? meth->get_bcea() : nullptr;
2369 // fall-through if not a Java method or no analyzer information
2370 if (call_analyzer != nullptr) {
2371 PointsToNode* call_ptn = ptnode_adr(call->_idx);
2372 const TypeTuple* d = call->tf()->domain();2373 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {2374 const Type* at = d->field_at(i);2375 int k = i - TypeFunc::Parms;2376 Node* arg = call->in(i);
2377 PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2378 if (at->isa_ptr() != nullptr &&2379 call_analyzer->is_arg_returned(k)) {
2380 // The call returns arguments.
2381 if (call_ptn != nullptr) { // Is call's result used?
2382 assert(call_ptn->is_LocalVar(), "node should be registered");
2383 assert(arg_ptn != nullptr, "node should be registered");
2384 add_edge(call_ptn, arg_ptn);
2385 }
2386 }
2387 if (at->isa_oopptr() != nullptr &&
2388 arg_ptn->escape_state() < PointsToNode::GlobalEscape) {
2389 if (!call_analyzer->is_arg_stack(k)) {
2390 // The argument global escapes
2391 set_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2392 } else {
2393 set_escape_state(arg_ptn, PointsToNode::ArgEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2394 if (!call_analyzer->is_arg_local(k)) {
2395 // The argument itself doesn't escape, but any fields might
2396 set_fields_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2397 }
2398 }
2399 }
2400 }
2401 if (call_ptn != nullptr && call_ptn->is_LocalVar()) {
2402 // The call returns arguments.
2403 assert(call_ptn->edge_count() > 0, "sanity");
2404 if (!call_analyzer->is_return_local()) {
2405 // Returns also unknown object.
2406 add_edge(call_ptn, phantom_obj);
2407 }
2408 }
2409 break;
2410 }
2411 }
2412 default: {
2413 // Fall-through here if not a Java method or no analyzer information
2414 // or some other type of call, assume the worst case: all arguments
2415 // globally escape.
2416 const TypeTuple* d = call->tf()->domain();
2417 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2418 const Type* at = d->field_at(i);
2419 if (at->isa_oopptr() != nullptr) {
2420 Node* arg = call->in(i);
2421 if (arg->is_AddP()) {
2422 arg = get_addp_base(arg);
2423 }
2424 assert(ptnode_adr(arg->_idx) != nullptr, "should be defined already");
2425 set_escape_state(ptnode_adr(arg->_idx), PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2426 }
2427 }
2428 }
2429 }
2430 }
2431
2432
2433 // Finish Graph construction.
2434 bool ConnectionGraph::complete_connection_graph(
2435 GrowableArray<PointsToNode*>& ptnodes_worklist,
2436 GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist,
2437 GrowableArray<JavaObjectNode*>& java_objects_worklist,
2438 GrowableArray<FieldNode*>& oop_fields_worklist) {
2439 // Normally only 1-3 passes needed to build Connection Graph depending
2440 // on graph complexity. Observed 8 passes in jvm2008 compiler.compiler.
2441 // Set limit to 20 to catch situation when something did go wrong and
2442 // bailout Escape Analysis.
2443 // Also limit build time to 20 sec (60 in debug VM), EscapeAnalysisTimeout flag.
2444 #define GRAPH_BUILD_ITER_LIMIT 20
2445
2446 // Propagate GlobalEscape and ArgEscape escape states and check that
2447 // we still have non-escaping objects. The method pushs on _worklist
2448 // Field nodes which reference phantom_object.
2449 if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_allocs_worklist)) {
2450 return false; // Nothing to do.
2451 }
2452 // Now propagate references to all JavaObject nodes.
2453 int java_objects_length = java_objects_worklist.length();
2454 elapsedTimer build_time;
2455 build_time.start();
2456 elapsedTimer time;
2457 bool timeout = false;
2458 int new_edges = 1;
2459 int iterations = 0;
2460 do {
2461 while ((new_edges > 0) &&
2462 (iterations++ < GRAPH_BUILD_ITER_LIMIT)) {
2463 double start_time = time.seconds();
2464 time.start();
2465 new_edges = 0;
2466 // Propagate references to phantom_object for nodes pushed on _worklist
2467 // by find_non_escaped_objects() and find_field_value().
2468 new_edges += add_java_object_edges(phantom_obj, false);
2469 for (int next = 0; next < java_objects_length; ++next) {
2470 JavaObjectNode* ptn = java_objects_worklist.at(next);
2471 new_edges += add_java_object_edges(ptn, true);
2472
2473 #define SAMPLE_SIZE 4
2474 if ((next % SAMPLE_SIZE) == 0) {
2475 // Each 4 iterations calculate how much time it will take
2476 // to complete graph construction.
2477 time.stop();
2478 // Poll for requests from shutdown mechanism to quiesce compiler
2479 // because Connection graph construction may take long time.
2480 CompileBroker::maybe_block();
2481 double stop_time = time.seconds();
2482 double time_per_iter = (stop_time - start_time) / (double)SAMPLE_SIZE;
2483 double time_until_end = time_per_iter * (double)(java_objects_length - next);
2484 if ((start_time + time_until_end) >= EscapeAnalysisTimeout) {
2485 timeout = true;
2486 break; // Timeout
2487 }
2488 start_time = stop_time;
2489 time.start();
2490 }
2491 #undef SAMPLE_SIZE
2492
2493 }
2494 if (timeout) break;
2495 if (new_edges > 0) {
2496 // Update escape states on each iteration if graph was updated.
2497 if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_allocs_worklist)) {
2498 return false; // Nothing to do.
2499 }
2500 }
2501 time.stop();
2502 if (time.seconds() >= EscapeAnalysisTimeout) {
2503 timeout = true;
2504 break;
2505 }
2506 _compile->print_method(PHASE_EA_COMPLETE_CONNECTION_GRAPH_ITER, 5);
2507 }
2508 if ((iterations < GRAPH_BUILD_ITER_LIMIT) && !timeout) {
2509 time.start();
2510 // Find fields which have unknown value.
2511 int fields_length = oop_fields_worklist.length();
2512 for (int next = 0; next < fields_length; next++) {
2513 FieldNode* field = oop_fields_worklist.at(next);
2514 if (field->edge_count() == 0) {
2515 new_edges += find_field_value(field);
2516 // This code may added new edges to phantom_object.
2517 // Need an other cycle to propagate references to phantom_object.
2518 }
2519 }
2520 time.stop();
2521 if (time.seconds() >= EscapeAnalysisTimeout) {
2522 timeout = true;
2523 break;
2524 }
2525 } else {
2526 new_edges = 0; // Bailout
2527 }
2528 } while (new_edges > 0);
2529
2530 build_time.stop();
2531 _build_time = build_time.seconds();
2532 _build_iterations = iterations;
2533
2534 // Bailout if passed limits.
2535 if ((iterations >= GRAPH_BUILD_ITER_LIMIT) || timeout) {
2536 Compile* C = _compile;
2537 if (C->log() != nullptr) {
2538 C->log()->begin_elem("connectionGraph_bailout reason='reached ");
2539 C->log()->text("%s", timeout ? "time" : "iterations");
2540 C->log()->end_elem(" limit'");
2541 }
2542 assert(ExitEscapeAnalysisOnTimeout, "infinite EA connection graph build during invocation %d (%f sec, %d iterations) with %d nodes and worklist size %d",
2543 _invocation, _build_time, _build_iterations, nodes_size(), ptnodes_worklist.length());
2544 // Possible infinite build_connection_graph loop,
2545 // bailout (no changes to ideal graph were made).
2546 return false;
2547 }
2548
2549 #undef GRAPH_BUILD_ITER_LIMIT
2550
2551 // Find fields initialized by null for non-escaping Allocations.
2552 int non_escaped_length = non_escaped_allocs_worklist.length();
2553 for (int next = 0; next < non_escaped_length; next++) {
2554 JavaObjectNode* ptn = non_escaped_allocs_worklist.at(next);
2555 PointsToNode::EscapeState es = ptn->escape_state();
2556 assert(es <= PointsToNode::ArgEscape, "sanity");
2557 if (es == PointsToNode::NoEscape) {
2558 if (find_init_values_null(ptn, _igvn) > 0) {
2559 // Adding references to null object does not change escape states
2560 // since it does not escape. Also no fields are added to null object.
2561 add_java_object_edges(null_obj, false);
2562 }
2563 }
2564 Node* n = ptn->ideal_node();
2565 if (n->is_Allocate()) {
2566 // The object allocated by this Allocate node will never be
2567 // seen by an other thread. Mark it so that when it is
2568 // expanded no MemBarStoreStore is added.
2569 InitializeNode* ini = n->as_Allocate()->initialization();
2570 if (ini != nullptr)
2571 ini->set_does_not_escape();
2572 }
2573 }
2574 return true; // Finished graph construction.
2575 }
2576
2577 // Propagate GlobalEscape and ArgEscape escape states to all nodes
2578 // and check that we still have non-escaping java objects.
2579 bool ConnectionGraph::find_non_escaped_objects(GrowableArray<PointsToNode*>& ptnodes_worklist,
2580 GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist,
2581 bool print_method) {
2582 GrowableArray<PointsToNode*> escape_worklist;
2583 // First, put all nodes with GlobalEscape and ArgEscape states on worklist.
2584 int ptnodes_length = ptnodes_worklist.length();
2585 for (int next = 0; next < ptnodes_length; ++next) {
2586 PointsToNode* ptn = ptnodes_worklist.at(next);
2587 if (ptn->escape_state() >= PointsToNode::ArgEscape ||
2588 ptn->fields_escape_state() >= PointsToNode::ArgEscape) {
2589 escape_worklist.push(ptn);
2590 }
2591 }
2592 // Set escape states to referenced nodes (edges list).
2593 while (escape_worklist.length() > 0) {
2594 PointsToNode* ptn = escape_worklist.pop();
2595 PointsToNode::EscapeState es = ptn->escape_state();
2596 PointsToNode::EscapeState field_es = ptn->fields_escape_state();
2597 if (ptn->is_Field() && ptn->as_Field()->is_oop() &&
2598 es >= PointsToNode::ArgEscape) {
2599 // GlobalEscape or ArgEscape state of field means it has unknown value.
2600 if (add_edge(ptn, phantom_obj)) {
2601 // New edge was added
2602 add_field_uses_to_worklist(ptn->as_Field());
2603 }
2604 }
2605 for (EdgeIterator i(ptn); i.has_next(); i.next()) {
2606 PointsToNode* e = i.get();
2607 if (e->is_Arraycopy()) {
2608 assert(ptn->arraycopy_dst(), "sanity");
2609 // Propagate only fields escape state through arraycopy edge.
2610 if (e->fields_escape_state() < field_es) {
2611 set_fields_escape_state(e, field_es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
2612 escape_worklist.push(e);
2613 }
2614 } else if (es >= field_es) {
2615 // fields_escape_state is also set to 'es' if it is less than 'es'.
2616 if (e->escape_state() < es) {
2617 set_escape_state(e, es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
2618 escape_worklist.push(e);
2619 }
2620 } else {
2621 // Propagate field escape state.
2622 bool es_changed = false;
2623 if (e->fields_escape_state() < field_es) {
2624 set_fields_escape_state(e, field_es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
2625 es_changed = true;
2626 }
2627 if ((e->escape_state() < field_es) &&
2628 e->is_Field() && ptn->is_JavaObject() &&
2629 e->as_Field()->is_oop()) {
2630 // Change escape state of referenced fields.
2631 set_escape_state(e, field_es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
2632 es_changed = true;
2633 } else if (e->escape_state() < es) {
2634 set_escape_state(e, es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
2635 es_changed = true;
2636 }
2637 if (es_changed) {
2638 escape_worklist.push(e);
2639 }
2640 }
2641 if (print_method) {
2642 _compile->print_method(PHASE_EA_CONNECTION_GRAPH_PROPAGATE_ITER, 6, e->ideal_node());
2643 }
2644 }
2645 }
2646 // Remove escaped objects from non_escaped list.
2647 for (int next = non_escaped_allocs_worklist.length()-1; next >= 0 ; --next) {
2648 JavaObjectNode* ptn = non_escaped_allocs_worklist.at(next);
2649 if (ptn->escape_state() >= PointsToNode::GlobalEscape) {
2650 non_escaped_allocs_worklist.delete_at(next);
2651 }
2652 if (ptn->escape_state() == PointsToNode::NoEscape) {
2653 // Find fields in non-escaped allocations which have unknown value.
2654 find_init_values_phantom(ptn);
2655 }
2656 }
2657 return (non_escaped_allocs_worklist.length() > 0);
2658 }
2659
2660 // Add all references to JavaObject node by walking over all uses.
2661 int ConnectionGraph::add_java_object_edges(JavaObjectNode* jobj, bool populate_worklist) {
2662 int new_edges = 0;
2663 if (populate_worklist) {
2664 // Populate _worklist by uses of jobj's uses.
2665 for (UseIterator i(jobj); i.has_next(); i.next()) {
2666 PointsToNode* use = i.get();
2667 if (use->is_Arraycopy()) {
2668 continue;
2669 }
2670 add_uses_to_worklist(use);
2671 if (use->is_Field() && use->as_Field()->is_oop()) {
2672 // Put on worklist all field's uses (loads) and
2673 // related field nodes (same base and offset).
2674 add_field_uses_to_worklist(use->as_Field());
2675 }
2676 }
2677 }
2678 for (int l = 0; l < _worklist.length(); l++) {
2679 PointsToNode* use = _worklist.at(l);
2680 if (PointsToNode::is_base_use(use)) {
2681 // Add reference from jobj to field and from field to jobj (field's base).
2682 use = PointsToNode::get_use_node(use)->as_Field();
2683 if (add_base(use->as_Field(), jobj)) {
2684 new_edges++;
2685 }
2686 continue;
2687 }
2688 assert(!use->is_JavaObject(), "sanity");
2689 if (use->is_Arraycopy()) {
2690 if (jobj == null_obj) { // null object does not have field edges
2691 continue;
2692 }
2693 // Added edge from Arraycopy node to arraycopy's source java object
2694 if (add_edge(use, jobj)) {
2695 jobj->set_arraycopy_src();
2696 new_edges++;
2697 }
2698 // and stop here.
2699 continue;
2700 }
2701 if (!add_edge(use, jobj)) {
2702 continue; // No new edge added, there was such edge already.
2703 }
2704 new_edges++;
2705 if (use->is_LocalVar()) {
2706 add_uses_to_worklist(use);
2707 if (use->arraycopy_dst()) {
2708 for (EdgeIterator i(use); i.has_next(); i.next()) {
2709 PointsToNode* e = i.get();
2710 if (e->is_Arraycopy()) {
2711 if (jobj == null_obj) { // null object does not have field edges
2712 continue;
2713 }
2714 // Add edge from arraycopy's destination java object to Arraycopy node.
2715 if (add_edge(jobj, e)) {
2716 new_edges++;
2717 jobj->set_arraycopy_dst();
2718 }
2719 }
2720 }
2721 }
2722 } else {
2723 // Added new edge to stored in field values.
2724 // Put on worklist all field's uses (loads) and
2725 // related field nodes (same base and offset).
2726 add_field_uses_to_worklist(use->as_Field());
2727 }
2728 }
2729 _worklist.clear();
2730 _in_worklist.reset();
2731 return new_edges;
2732 }
2733
2734 // Put on worklist all related field nodes.
2735 void ConnectionGraph::add_field_uses_to_worklist(FieldNode* field) {
2736 assert(field->is_oop(), "sanity");
2737 int offset = field->offset();
2738 add_uses_to_worklist(field);
2739 // Loop over all bases of this field and push on worklist Field nodes
2740 // with the same offset and base (since they may reference the same field).
2741 for (BaseIterator i(field); i.has_next(); i.next()) {
2742 PointsToNode* base = i.get();
2743 add_fields_to_worklist(field, base);
2744 // Check if the base was source object of arraycopy and go over arraycopy's
2745 // destination objects since values stored to a field of source object are
2746 // accessible by uses (loads) of fields of destination objects.
2747 if (base->arraycopy_src()) {
2748 for (UseIterator j(base); j.has_next(); j.next()) {
2749 PointsToNode* arycp = j.get();
2750 if (arycp->is_Arraycopy()) {
2751 for (UseIterator k(arycp); k.has_next(); k.next()) {
2752 PointsToNode* abase = k.get();
2753 if (abase->arraycopy_dst() && abase != base) {
2754 // Look for the same arraycopy reference.
2755 add_fields_to_worklist(field, abase);
2756 }
2757 }
2758 }
2759 }
2760 }
2761 }
2762 }
2763
2764 // Put on worklist all related field nodes.
2765 void ConnectionGraph::add_fields_to_worklist(FieldNode* field, PointsToNode* base) {
2766 int offset = field->offset();
2767 if (base->is_LocalVar()) {
2768 for (UseIterator j(base); j.has_next(); j.next()) {
2769 PointsToNode* f = j.get();
2770 if (PointsToNode::is_base_use(f)) { // Field
2771 f = PointsToNode::get_use_node(f);
2772 if (f == field || !f->as_Field()->is_oop()) {
2773 continue;
2774 }
2775 int offs = f->as_Field()->offset();
2776 if (offs == offset || offset == Type::OffsetBot || offs == Type::OffsetBot) {
2777 add_to_worklist(f);
2778 }
2779 }
2780 }
2781 } else {
2782 assert(base->is_JavaObject(), "sanity");
2783 if (// Skip phantom_object since it is only used to indicate that
2784 // this field's content globally escapes.
2785 (base != phantom_obj) &&
2786 // null object node does not have fields.
2787 (base != null_obj)) {
2788 for (EdgeIterator i(base); i.has_next(); i.next()) {
2789 PointsToNode* f = i.get();
2790 // Skip arraycopy edge since store to destination object field
2791 // does not update value in source object field.
2792 if (f->is_Arraycopy()) {
2793 assert(base->arraycopy_dst(), "sanity");
2794 continue;
2795 }
2796 if (f == field || !f->as_Field()->is_oop()) {
2797 continue;
2798 }
2799 int offs = f->as_Field()->offset();
2800 if (offs == offset || offset == Type::OffsetBot || offs == Type::OffsetBot) {
2801 add_to_worklist(f);
2802 }
2803 }
2804 }
2805 }
2806 }
2807
2808 // Find fields which have unknown value.
2809 int ConnectionGraph::find_field_value(FieldNode* field) {
2810 // Escaped fields should have init value already.
2811 assert(field->escape_state() == PointsToNode::NoEscape, "sanity");
2812 int new_edges = 0;
2813 for (BaseIterator i(field); i.has_next(); i.next()) {
2814 PointsToNode* base = i.get();
2815 if (base->is_JavaObject()) {
2816 // Skip Allocate's fields which will be processed later.
2817 if (base->ideal_node()->is_Allocate()) {
2818 return 0;
2819 }
2820 assert(base == null_obj, "only null ptr base expected here");
2821 }
2822 }
2823 if (add_edge(field, phantom_obj)) {
2824 // New edge was added
2825 new_edges++;
2826 add_field_uses_to_worklist(field);
2827 }
2828 return new_edges;
2829 }
2830
2831 // Find fields initializing values for allocations.
2832 int ConnectionGraph::find_init_values_phantom(JavaObjectNode* pta) {
2833 assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
2834 Node* alloc = pta->ideal_node();
2835
2836 // Do nothing for Allocate nodes since its fields values are
2837 // "known" unless they are initialized by arraycopy/clone.
2838 if (alloc->is_Allocate() && !pta->arraycopy_dst()) {
2839 return 0;
2840 }
2841 assert(pta->arraycopy_dst() || alloc->as_CallStaticJava(), "sanity");
2842 #ifdef ASSERT
2843 if (!pta->arraycopy_dst() && alloc->as_CallStaticJava()->method() == nullptr) {2844 assert(alloc->as_CallStaticJava()->is_call_to_multianewarray_stub(), "sanity");
2845 }
2846 #endif
2847 // Non-escaped allocation returned from Java or runtime call have unknown values in fields.
2848 int new_edges = 0;
2849 for (EdgeIterator i(pta); i.has_next(); i.next()) {
2850 PointsToNode* field = i.get();
2851 if (field->is_Field() && field->as_Field()->is_oop()) {
2852 if (add_edge(field, phantom_obj)) {
2853 // New edge was added
2854 new_edges++;
2855 add_field_uses_to_worklist(field->as_Field());
2856 }
2857 }
2858 }
2859 return new_edges;
2860 }
2861
2862 // Find fields initializing values for allocations.
2863 int ConnectionGraph::find_init_values_null(JavaObjectNode* pta, PhaseValues* phase) {
2864 assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
2865 Node* alloc = pta->ideal_node();
2866 // Do nothing for Call nodes since its fields values are unknown.
2867 if (!alloc->is_Allocate()) {
2868 return 0;
2869 }
2870 InitializeNode* ini = alloc->as_Allocate()->initialization();
2871 bool visited_bottom_offset = false;
2872 GrowableArray<int> offsets_worklist;
2873 int new_edges = 0;
2874
2875 // Check if an oop field's initializing value is recorded and add
2876 // a corresponding null if field's value if it is not recorded.
2877 // Connection Graph does not record a default initialization by null
2878 // captured by Initialize node.
2879 //
2880 for (EdgeIterator i(pta); i.has_next(); i.next()) {
2881 PointsToNode* field = i.get(); // Field (AddP)
2882 if (!field->is_Field() || !field->as_Field()->is_oop()) {
2883 continue; // Not oop field
2884 }
2885 int offset = field->as_Field()->offset();
2886 if (offset == Type::OffsetBot) {
2887 if (!visited_bottom_offset) {
2888 // OffsetBot is used to reference array's element,
2889 // always add reference to null to all Field nodes since we don't
2890 // known which element is referenced.
2891 if (add_edge(field, null_obj)) {
2892 // New edge was added
2893 new_edges++;
2894 add_field_uses_to_worklist(field->as_Field());
2895 visited_bottom_offset = true;
2896 }
2897 }
2898 } else {
2899 // Check only oop fields.
2900 const Type* adr_type = field->ideal_node()->as_AddP()->bottom_type();
2901 if (adr_type->isa_rawptr()) {
2902 #ifdef ASSERT
2903 // Raw pointers are used for initializing stores so skip it
2904 // since it should be recorded already
2905 Node* base = get_addp_base(field->ideal_node());
2906 assert(adr_type->isa_rawptr() && is_captured_store_address(field->ideal_node()), "unexpected pointer type");
2907 #endif
2908 continue;
2909 }
2910 if (!offsets_worklist.contains(offset)) {
2911 offsets_worklist.append(offset);
2912 Node* value = nullptr;
2913 if (ini != nullptr) {
2914 // StoreP::value_basic_type() == T_ADDRESS
2915 BasicType ft = UseCompressedOops ? T_NARROWOOP : T_ADDRESS;
2916 Node* store = ini->find_captured_store(offset, type2aelembytes(ft, true), phase);
2917 // Make sure initializing store has the same type as this AddP.
2918 // This AddP may reference non existing field because it is on a
2919 // dead branch of bimorphic call which is not eliminated yet.
2920 if (store != nullptr && store->is_Store() &&
2921 store->as_Store()->value_basic_type() == ft) {
2922 value = store->in(MemNode::ValueIn);
2923 #ifdef ASSERT
2924 if (VerifyConnectionGraph) {
2925 // Verify that AddP already points to all objects the value points to.
2926 PointsToNode* val = ptnode_adr(value->_idx);
2927 assert((val != nullptr), "should be processed already");
2928 PointsToNode* missed_obj = nullptr;
2929 if (val->is_JavaObject()) {
2930 if (!field->points_to(val->as_JavaObject())) {
2931 missed_obj = val;
2932 }
2933 } else {
2934 if (!val->is_LocalVar() || (val->edge_count() == 0)) {
2935 tty->print_cr("----------init store has invalid value -----");
2936 store->dump();
2937 val->dump();
2938 assert(val->is_LocalVar() && (val->edge_count() > 0), "should be processed already");
2939 }
2940 for (EdgeIterator j(val); j.has_next(); j.next()) {
2941 PointsToNode* obj = j.get();
2942 if (obj->is_JavaObject()) {
2943 if (!field->points_to(obj->as_JavaObject())) {
2944 missed_obj = obj;
2945 break;
2946 }
2947 }
2948 }
2949 }
2950 if (missed_obj != nullptr) {
2951 tty->print_cr("----------field---------------------------------");
2952 field->dump();
2953 tty->print_cr("----------missed referernce to object-----------");
2954 missed_obj->dump();
2955 tty->print_cr("----------object referernced by init store -----");
2956 store->dump();
2957 val->dump();
2958 assert(!field->points_to(missed_obj->as_JavaObject()), "missed JavaObject reference");
2959 }
2960 }
2961 #endif
2962 } else {
2963 // There could be initializing stores which follow allocation.
2964 // For example, a volatile field store is not collected
2965 // by Initialize node.
2966 //
2967 // Need to check for dependent loads to separate such stores from
2968 // stores which follow loads. For now, add initial value null so
2969 // that compare pointers optimization works correctly.
2970 }
2971 }
2972 if (value == nullptr) {
2973 // A field's initializing value was not recorded. Add null.
2974 if (add_edge(field, null_obj)) {
2975 // New edge was added
2976 new_edges++;
2977 add_field_uses_to_worklist(field->as_Field());
2978 }
2979 }
2980 }
2981 }
2982 }
2983 return new_edges;
2984 }
2985
2986 // Adjust scalar_replaceable state after Connection Graph is built.
2987 void ConnectionGraph::adjust_scalar_replaceable_state(JavaObjectNode* jobj, Unique_Node_List &reducible_merges) {
2988 // A Phi 'x' is a _candidate_ to be reducible if 'can_reduce_phi(x)'
2989 // returns true. If one of the constraints in this method set 'jobj' to NSR
2990 // then the candidate Phi is discarded. If the Phi has another SR 'jobj' as
2991 // input, 'adjust_scalar_replaceable_state' will eventually be called with
2992 // that other object and the Phi will become a reducible Phi.
2993 // There could be multiple merges involving the same jobj.
2994 Unique_Node_List candidates;
2995
2996 // Search for non-escaping objects which are not scalar replaceable
2997 // and mark them to propagate the state to referenced objects.
2998
2999 for (UseIterator i(jobj); i.has_next(); i.next()) {
3000 PointsToNode* use = i.get();
3001 if (use->is_Arraycopy()) {
3002 continue;
3003 }
3004 if (use->is_Field()) {
3005 FieldNode* field = use->as_Field();
3006 assert(field->is_oop() && field->scalar_replaceable(), "sanity");
3007 // 1. An object is not scalar replaceable if the field into which it is
3008 // stored has unknown offset (stored into unknown element of an array).
3009 if (field->offset() == Type::OffsetBot) {
3010 set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is stored at unknown offset"));
3011 return;
3012 }
3013 for (BaseIterator i(field); i.has_next(); i.next()) {
3014 PointsToNode* base = i.get();
3015 // 2. An object is not scalar replaceable if the field into which it is
3016 // stored has multiple bases one of which is null.
3017 if ((base == null_obj) && (field->base_count() > 1)) {
3018 set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is stored into field with potentially null base"));
3019 return;
3020 }
3021 // 2.5. An object is not scalar replaceable if the field into which it is
3022 // stored has NSR base.
3023 if (!base->scalar_replaceable()) {
3024 set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is stored into field with NSR base"));
3025 return;
3026 }
3027 }
3028 }
3029 assert(use->is_Field() || use->is_LocalVar(), "sanity");
3030 // 3. An object is not scalar replaceable if it is merged with other objects
3031 // and we can't remove the merge
3032 for (EdgeIterator j(use); j.has_next(); j.next()) {
3033 PointsToNode* ptn = j.get();
3034 if (ptn->is_JavaObject() && ptn != jobj) {
3035 Node* use_n = use->ideal_node();
3036
3037 // These other local vars may point to multiple objects through a Phi
3038 // In this case we skip them and see if we can reduce the Phi.
3039 if (use_n->is_CastPP() || use_n->is_CheckCastPP()) {
3040 use_n = use_n->in(1);
3041 }
3042
3043 // If it's already a candidate or confirmed reducible merge we can skip verification
3044 if (candidates.member(use_n) || reducible_merges.member(use_n)) {
3045 continue;
3046 }
3047
3048 if (use_n->is_Phi() && can_reduce_phi(use_n->as_Phi())) {
3049 candidates.push(use_n);
3050 } else {
3051 // Mark all objects as NSR if we can't remove the merge
3052 set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA trace_merged_message(ptn)));
3053 set_not_scalar_replaceable(ptn NOT_PRODUCT(COMMA trace_merged_message(jobj)));
3054 }
3055 }
3056 }
3057 if (!jobj->scalar_replaceable()) {
3058 return;
3059 }
3060 }
3061
3062 for (EdgeIterator j(jobj); j.has_next(); j.next()) {
3063 if (j.get()->is_Arraycopy()) {
3064 continue;
3065 }
3066
3067 // Non-escaping object node should point only to field nodes.
3068 FieldNode* field = j.get()->as_Field();
3069 int offset = field->as_Field()->offset();
3070
3071 // 4. An object is not scalar replaceable if it has a field with unknown
3072 // offset (array's element is accessed in loop).
3073 if (offset == Type::OffsetBot) {
3074 set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "has field with unknown offset"));
3075 return;
3076 }
3077 // 5. Currently an object is not scalar replaceable if a LoadStore node
3078 // access its field since the field value is unknown after it.
3079 //
3080 Node* n = field->ideal_node();
3081
3082 // Test for an unsafe access that was parsed as maybe off heap
3083 // (with a CheckCastPP to raw memory).
3084 assert(n->is_AddP(), "expect an address computation");
3085 if (n->in(AddPNode::Base)->is_top() &&
3086 n->in(AddPNode::Address)->Opcode() == Op_CheckCastPP) {
3087 assert(n->in(AddPNode::Address)->bottom_type()->isa_rawptr(), "raw address so raw cast expected");
3088 assert(_igvn->type(n->in(AddPNode::Address)->in(1))->isa_oopptr(), "cast pattern at unsafe access expected");
3089 set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is used as base of mixed unsafe access"));
3090 return;
3091 }
3092
3093 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3094 Node* u = n->fast_out(i);
3095 if (u->is_LoadStore() || (u->is_Mem() && u->as_Mem()->is_mismatched_access())) {
3096 set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is used in LoadStore or mismatched access"));
3097 return;
3098 }
3099 }
3100
3101 // 6. Or the address may point to more then one object. This may produce
3102 // the false positive result (set not scalar replaceable)
3103 // since the flow-insensitive escape analysis can't separate
3104 // the case when stores overwrite the field's value from the case
3105 // when stores happened on different control branches.
3106 //
3107 // Note: it will disable scalar replacement in some cases:
3108 //
3109 // Point p[] = new Point[1];
3110 // p[0] = new Point(); // Will be not scalar replaced
3111 //
3112 // but it will save us from incorrect optimizations in next cases:
3113 //
3114 // Point p[] = new Point[1];
3115 // if ( x ) p[0] = new Point(); // Will be not scalar replaced
3116 //
3117 if (field->base_count() > 1 && candidates.size() == 0) {
3118 if (has_non_reducible_merge(field, reducible_merges)) {
3119 for (BaseIterator i(field); i.has_next(); i.next()) {
3120 PointsToNode* base = i.get();
3121 // Don't take into account LocalVar nodes which
3122 // may point to only one object which should be also
3123 // this field's base by now.
3124 if (base->is_JavaObject() && base != jobj) {
3125 // Mark all bases.
3126 set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "may point to more than one object"));
3127 set_not_scalar_replaceable(base NOT_PRODUCT(COMMA "may point to more than one object"));
3128 }
3129 }
3130
3131 if (!jobj->scalar_replaceable()) {
3132 return;
3133 }
3134 }
3135 }
3136 }
3137
3138 // The candidate is truly a reducible merge only if none of the other
3139 // constraints ruled it as NSR. There could be multiple merges involving the
3140 // same jobj.
3141 assert(jobj->scalar_replaceable(), "sanity");
3142 for (uint i = 0; i < candidates.size(); i++ ) {
3143 Node* candidate = candidates.at(i);
3144 reducible_merges.push(candidate);
3145 }
3146 }
3147
3148 bool ConnectionGraph::has_non_reducible_merge(FieldNode* field, Unique_Node_List& reducible_merges) {
3149 for (BaseIterator i(field); i.has_next(); i.next()) {
3150 Node* base = i.get()->ideal_node();
3151 if (base->is_Phi() && !reducible_merges.member(base)) {
3152 return true;
3153 }
3154 }
3155 return false;
3156 }
3157
3158 void ConnectionGraph::revisit_reducible_phi_status(JavaObjectNode* jobj, Unique_Node_List& reducible_merges) {
3159 assert(jobj != nullptr && !jobj->scalar_replaceable(), "jobj should be set as NSR before calling this function.");
3160
3161 // Look for 'phis' that refer to 'jobj' as the last
3162 // remaining scalar replaceable input.
3163 uint reducible_merges_cnt = reducible_merges.size();
3164 for (uint i = 0; i < reducible_merges_cnt; i++) {
3165 Node* phi = reducible_merges.at(i);
3166
3167 // This 'Phi' will be a 'good' if it still points to
3168 // at least one scalar replaceable object. Note that 'obj'
3169 // was/should be marked as NSR before calling this function.
3170 bool good_phi = false;
3171
3172 for (uint j = 1; j < phi->req(); j++) {
3173 JavaObjectNode* phi_in_obj = unique_java_object(phi->in(j));
3174 if (phi_in_obj != nullptr && phi_in_obj->scalar_replaceable()) {
3175 good_phi = true;
3176 break;
3177 }
3178 }
3179
3180 if (!good_phi) {
3181 NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Phi %d became non-reducible after node %d became NSR.", phi->_idx, jobj->ideal_node()->_idx);)
3182 reducible_merges.remove(i);
3183
3184 // Decrement the index because the 'remove' call above actually
3185 // moves the last entry of the list to position 'i'.
3186 i--;
3187
3188 reducible_merges_cnt--;
3189 }
3190 }
3191 }
3192
3193 // Propagate NSR (Not scalar replaceable) state.
3194 void ConnectionGraph::find_scalar_replaceable_allocs(GrowableArray<JavaObjectNode*>& jobj_worklist, Unique_Node_List &reducible_merges) {
3195 int jobj_length = jobj_worklist.length();
3196 bool found_nsr_alloc = true;
3197 while (found_nsr_alloc) {
3198 found_nsr_alloc = false;
3199 for (int next = 0; next < jobj_length; ++next) {
3200 JavaObjectNode* jobj = jobj_worklist.at(next);
3201 for (UseIterator i(jobj); (jobj->scalar_replaceable() && i.has_next()); i.next()) {
3202 PointsToNode* use = i.get();
3203 if (use->is_Field()) {
3204 FieldNode* field = use->as_Field();
3205 assert(field->is_oop() && field->scalar_replaceable(), "sanity");
3206 assert(field->offset() != Type::OffsetBot, "sanity");
3207 for (BaseIterator i(field); i.has_next(); i.next()) {
3208 PointsToNode* base = i.get();
3209 // An object is not scalar replaceable if the field into which
3210 // it is stored has NSR base.
3211 if ((base != null_obj) && !base->scalar_replaceable()) {
3212 set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is stored into field with NSR base"));
3213 // Any merge that had only 'jobj' as scalar-replaceable will now be non-reducible,
3214 // because there is no point in reducing a Phi that won't improve the number of SR
3215 // objects.
3216 revisit_reducible_phi_status(jobj, reducible_merges);
3217 found_nsr_alloc = true;
3218 break;
3219 }
3220 }
3221 } else if (use->is_LocalVar()) {
3222 Node* phi = use->ideal_node();
3223 if (phi->Opcode() == Op_Phi && reducible_merges.member(phi) && !can_reduce_phi(phi->as_Phi())) {
3224 set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is merged in a non-reducible phi"));
3225 reducible_merges.yank(phi);
3226 found_nsr_alloc = true;
3227 break;
3228 }
3229 }
3230 _compile->print_method(PHASE_EA_PROPAGATE_NSR_ITER, 5, jobj->ideal_node());
3231 }
3232 }
3233 }
3234 }
3235
3236 #ifdef ASSERT
3237 void ConnectionGraph::verify_connection_graph(
3238 GrowableArray<PointsToNode*>& ptnodes_worklist,
3239 GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist,
3240 GrowableArray<JavaObjectNode*>& java_objects_worklist,
3241 GrowableArray<Node*>& addp_worklist) {
3242 // Verify that graph is complete - no new edges could be added.
3243 int java_objects_length = java_objects_worklist.length();
3244 int non_escaped_length = non_escaped_allocs_worklist.length();
3245 int new_edges = 0;
3246 for (int next = 0; next < java_objects_length; ++next) {
3247 JavaObjectNode* ptn = java_objects_worklist.at(next);
3248 new_edges += add_java_object_edges(ptn, true);
3249 }
3250 assert(new_edges == 0, "graph was not complete");
3251 // Verify that escape state is final.
3252 int length = non_escaped_allocs_worklist.length();
3253 find_non_escaped_objects(ptnodes_worklist, non_escaped_allocs_worklist, /*print_method=*/ false);
3254 assert((non_escaped_length == non_escaped_allocs_worklist.length()) &&
3255 (non_escaped_length == length) &&
3256 (_worklist.length() == 0), "escape state was not final");
3257
3258 // Verify fields information.
3259 int addp_length = addp_worklist.length();
3260 for (int next = 0; next < addp_length; ++next ) {
3261 Node* n = addp_worklist.at(next);
3262 FieldNode* field = ptnode_adr(n->_idx)->as_Field();
3263 if (field->is_oop()) {
3264 // Verify that field has all bases
3265 Node* base = get_addp_base(n);
3266 PointsToNode* ptn = ptnode_adr(base->_idx);
3267 if (ptn->is_JavaObject()) {
3268 assert(field->has_base(ptn->as_JavaObject()), "sanity");
3269 } else {
3270 assert(ptn->is_LocalVar(), "sanity");
3271 for (EdgeIterator i(ptn); i.has_next(); i.next()) {
3272 PointsToNode* e = i.get();
3273 if (e->is_JavaObject()) {
3274 assert(field->has_base(e->as_JavaObject()), "sanity");
3275 }
3276 }
3277 }
3278 // Verify that all fields have initializing values.
3279 if (field->edge_count() == 0) {
3280 tty->print_cr("----------field does not have references----------");
3281 field->dump();
3282 for (BaseIterator i(field); i.has_next(); i.next()) {
3283 PointsToNode* base = i.get();
3284 tty->print_cr("----------field has next base---------------------");
3285 base->dump();
3286 if (base->is_JavaObject() && (base != phantom_obj) && (base != null_obj)) {
3287 tty->print_cr("----------base has fields-------------------------");
3288 for (EdgeIterator j(base); j.has_next(); j.next()) {
3289 j.get()->dump();
3290 }
3291 tty->print_cr("----------base has references---------------------");
3292 for (UseIterator j(base); j.has_next(); j.next()) {
3293 j.get()->dump();
3294 }
3295 }
3296 }
3297 for (UseIterator i(field); i.has_next(); i.next()) {
3298 i.get()->dump();
3299 }
3300 assert(field->edge_count() > 0, "sanity");
3301 }
3302 }
3303 }
3304 }
3305 #endif
3306
3307 // Optimize ideal graph.
3308 void ConnectionGraph::optimize_ideal_graph(GrowableArray<Node*>& ptr_cmp_worklist,
3309 GrowableArray<MemBarStoreStoreNode*>& storestore_worklist) {
3310 Compile* C = _compile;
3311 PhaseIterGVN* igvn = _igvn;
3312 if (EliminateLocks) {
3313 // Mark locks before changing ideal graph.
3314 int cnt = C->macro_count();
3315 for (int i = 0; i < cnt; i++) {
3316 Node *n = C->macro_node(i);
3317 if (n->is_AbstractLock()) { // Lock and Unlock nodes
3318 AbstractLockNode* alock = n->as_AbstractLock();
3319 if (!alock->is_non_esc_obj()) {
3320 if (can_eliminate_lock(alock)) {
3321 assert(!alock->is_eliminated() || alock->is_coarsened(), "sanity");
3322 // The lock could be marked eliminated by lock coarsening
3323 // code during first IGVN before EA. Replace coarsened flag
3324 // to eliminate all associated locks/unlocks.
3325 #ifdef ASSERT
3326 alock->log_lock_optimization(C, "eliminate_lock_set_non_esc3");
3327 #endif
3328 alock->set_non_esc_obj();
3329 }
3330 }
3331 }
3332 }
3333 }
3334
3335 if (OptimizePtrCompare) {
3336 for (int i = 0; i < ptr_cmp_worklist.length(); i++) {
3337 Node *n = ptr_cmp_worklist.at(i);
3338 assert(n->Opcode() == Op_CmpN || n->Opcode() == Op_CmpP, "must be");
3339 const TypeInt* tcmp = optimize_ptr_compare(n->in(1), n->in(2));
3340 if (tcmp->singleton()) {
3341 Node* cmp = igvn->makecon(tcmp);
3342 #ifndef PRODUCT
3343 if (PrintOptimizePtrCompare) {
3344 tty->print_cr("++++ Replaced: %d %s(%d,%d) --> %s", n->_idx, (n->Opcode() == Op_CmpP ? "CmpP" : "CmpN"), n->in(1)->_idx, n->in(2)->_idx, (tcmp == TypeInt::CC_EQ ? "EQ" : "NotEQ"));
3345 if (Verbose) {
3346 n->dump(1);
3347 }
3348 }
3349 #endif
3350 igvn->replace_node(n, cmp);
3351 }
3352 }
3353 }
3354
3355 // For MemBarStoreStore nodes added in library_call.cpp, check
3356 // escape status of associated AllocateNode and optimize out
3357 // MemBarStoreStore node if the allocated object never escapes.
3358 for (int i = 0; i < storestore_worklist.length(); i++) {
3359 Node* storestore = storestore_worklist.at(i);
3360 Node* alloc = storestore->in(MemBarNode::Precedent)->in(0);
3361 if (alloc->is_Allocate() && not_global_escape(alloc)) {
3362 MemBarNode* mb = MemBarNode::make(C, Op_MemBarCPUOrder, Compile::AliasIdxBot);3363 mb->init_req(TypeFunc::Memory, storestore->in(TypeFunc::Memory));3364 mb->init_req(TypeFunc::Control, storestore->in(TypeFunc::Control));3365 igvn->register_new_node_with_optimizer(mb);3366 igvn->replace_node(storestore, mb);
3367 }
3368 }
3369 }
3370
3371 // Optimize objects compare.
3372 const TypeInt* ConnectionGraph::optimize_ptr_compare(Node* left, Node* right) {
3373 const TypeInt* UNKNOWN = TypeInt::CC; // [-1, 0,1]
3374 if (!OptimizePtrCompare) {
3375 return UNKNOWN;
3376 }
3377 const TypeInt* EQ = TypeInt::CC_EQ; // [0] == ZERO
3378 const TypeInt* NE = TypeInt::CC_GT; // [1] == ONE
3379
3380 PointsToNode* ptn1 = ptnode_adr(left->_idx);
3381 PointsToNode* ptn2 = ptnode_adr(right->_idx);
3382 JavaObjectNode* jobj1 = unique_java_object(left);
3383 JavaObjectNode* jobj2 = unique_java_object(right);
3384
3385 // The use of this method during allocation merge reduction may cause 'left'
3386 // or 'right' be something (e.g., a Phi) that isn't in the connection graph or
3387 // that doesn't reference an unique java object.
3388 if (ptn1 == nullptr || ptn2 == nullptr ||
3389 jobj1 == nullptr || jobj2 == nullptr) {
3390 return UNKNOWN;
3391 }
3392
3393 assert(ptn1->is_JavaObject() || ptn1->is_LocalVar(), "sanity");
3394 assert(ptn2->is_JavaObject() || ptn2->is_LocalVar(), "sanity");
3395
3396 // Check simple cases first.
3397 if (jobj1 != nullptr) {
3398 if (jobj1->escape_state() == PointsToNode::NoEscape) {
3399 if (jobj1 == jobj2) {
3400 // Comparing the same not escaping object.
3401 return EQ;
3402 }
3403 Node* obj = jobj1->ideal_node();
3404 // Comparing not escaping allocation.
3405 if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
3406 !ptn2->points_to(jobj1)) {
3407 return NE; // This includes nullness check.
3408 }
3409 }
3410 }
3411 if (jobj2 != nullptr) {
3412 if (jobj2->escape_state() == PointsToNode::NoEscape) {
3413 Node* obj = jobj2->ideal_node();
3414 // Comparing not escaping allocation.
3415 if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
3416 !ptn1->points_to(jobj2)) {
3417 return NE; // This includes nullness check.
3418 }
3419 }
3420 }
3421 if (jobj1 != nullptr && jobj1 != phantom_obj &&
3422 jobj2 != nullptr && jobj2 != phantom_obj &&
3423 jobj1->ideal_node()->is_Con() &&
3424 jobj2->ideal_node()->is_Con()) {
3425 // Klass or String constants compare. Need to be careful with
3426 // compressed pointers - compare types of ConN and ConP instead of nodes.
3427 const Type* t1 = jobj1->ideal_node()->get_ptr_type();
3428 const Type* t2 = jobj2->ideal_node()->get_ptr_type();
3429 if (t1->make_ptr() == t2->make_ptr()) {
3430 return EQ;
3431 } else {
3432 return NE;
3433 }
3434 }
3435 if (ptn1->meet(ptn2)) {
3436 return UNKNOWN; // Sets are not disjoint
3437 }
3438
3439 // Sets are disjoint.
3440 bool set1_has_unknown_ptr = ptn1->points_to(phantom_obj);
3441 bool set2_has_unknown_ptr = ptn2->points_to(phantom_obj);
3442 bool set1_has_null_ptr = ptn1->points_to(null_obj);
3443 bool set2_has_null_ptr = ptn2->points_to(null_obj);
3444 if ((set1_has_unknown_ptr && set2_has_null_ptr) ||
3445 (set2_has_unknown_ptr && set1_has_null_ptr)) {
3446 // Check nullness of unknown object.
3447 return UNKNOWN;
3448 }
3449
3450 // Disjointness by itself is not sufficient since
3451 // alias analysis is not complete for escaped objects.
3452 // Disjoint sets are definitely unrelated only when
3453 // at least one set has only not escaping allocations.
3454 if (!set1_has_unknown_ptr && !set1_has_null_ptr) {
3455 if (ptn1->non_escaping_allocation()) {
3456 return NE;
3457 }
3458 }
3459 if (!set2_has_unknown_ptr && !set2_has_null_ptr) {
3460 if (ptn2->non_escaping_allocation()) {
3461 return NE;
3462 }
3463 }
3464 return UNKNOWN;
3465 }
3466
3467 // Connection Graph construction functions.
3468
3469 void ConnectionGraph::add_local_var(Node *n, PointsToNode::EscapeState es) {
3470 PointsToNode* ptadr = _nodes.at(n->_idx);
3471 if (ptadr != nullptr) {
3472 assert(ptadr->is_LocalVar() && ptadr->ideal_node() == n, "sanity");
3473 return;
3474 }
3475 Compile* C = _compile;
3476 ptadr = new (C->comp_arena()) LocalVarNode(this, n, es);
3477 map_ideal_node(n, ptadr);
3478 }
3479
3480 PointsToNode* ConnectionGraph::add_java_object(Node *n, PointsToNode::EscapeState es) {
3481 PointsToNode* ptadr = _nodes.at(n->_idx);
3482 if (ptadr != nullptr) {
3483 assert(ptadr->is_JavaObject() && ptadr->ideal_node() == n, "sanity");
3484 return ptadr;
3485 }
3486 Compile* C = _compile;
3487 ptadr = new (C->comp_arena()) JavaObjectNode(this, n, es);
3488 map_ideal_node(n, ptadr);
3489 return ptadr;
3490 }
3491
3492 void ConnectionGraph::add_field(Node *n, PointsToNode::EscapeState es, int offset) {
3493 PointsToNode* ptadr = _nodes.at(n->_idx);
3494 if (ptadr != nullptr) {
3495 assert(ptadr->is_Field() && ptadr->ideal_node() == n, "sanity");
3496 return;
3497 }
3498 bool unsafe = false;
3499 bool is_oop = is_oop_field(n, offset, &unsafe);
3500 if (unsafe) {
3501 es = PointsToNode::GlobalEscape;
3502 }
3503 Compile* C = _compile;
3504 FieldNode* field = new (C->comp_arena()) FieldNode(this, n, es, offset, is_oop);
3505 map_ideal_node(n, field);
3506 }
3507
3508 void ConnectionGraph::add_arraycopy(Node *n, PointsToNode::EscapeState es,
3509 PointsToNode* src, PointsToNode* dst) {
3510 assert(!src->is_Field() && !dst->is_Field(), "only for JavaObject and LocalVar");
3511 assert((src != null_obj) && (dst != null_obj), "not for ConP null");
3512 PointsToNode* ptadr = _nodes.at(n->_idx);
3513 if (ptadr != nullptr) {
3514 assert(ptadr->is_Arraycopy() && ptadr->ideal_node() == n, "sanity");
3515 return;
3516 }
3517 Compile* C = _compile;
3518 ptadr = new (C->comp_arena()) ArraycopyNode(this, n, es);
3519 map_ideal_node(n, ptadr);
3520 // Add edge from arraycopy node to source object.
3521 (void)add_edge(ptadr, src);
3522 src->set_arraycopy_src();
3523 // Add edge from destination object to arraycopy node.
3524 (void)add_edge(dst, ptadr);
3525 dst->set_arraycopy_dst();
3526 }
3527
3528 bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) {
3529 const Type* adr_type = n->as_AddP()->bottom_type();
3530 BasicType bt = T_INT;
3531 if (offset == Type::OffsetBot) {
3532 // Check only oop fields.
3533 if (!adr_type->isa_aryptr() ||
3534 adr_type->isa_aryptr()->elem() == Type::BOTTOM ||
3535 adr_type->isa_aryptr()->elem()->make_oopptr() != nullptr) {
3536 // OffsetBot is used to reference array's element. Ignore first AddP.
3537 if (find_second_addp(n, n->in(AddPNode::Base)) == nullptr) {
3538 bt = T_OBJECT;
3539 }
3540 }
3541 } else if (offset != oopDesc::klass_offset_in_bytes()) {
3542 if (adr_type->isa_instptr()) {
3543 ciField* field = _compile->alias_type(adr_type->isa_instptr())->field();
3544 if (field != nullptr) {
3545 bt = field->layout_type();
3546 } else {
3547 // Check for unsafe oop field access
3548 if (has_oop_node_outs(n)) {
3549 bt = T_OBJECT;
3550 (*unsafe) = true;
3551 }
3552 }
3553 } else if (adr_type->isa_aryptr()) {
3554 if (offset == arrayOopDesc::length_offset_in_bytes()) {
3555 // Ignore array length load.
3556 } else if (find_second_addp(n, n->in(AddPNode::Base)) != nullptr) {
3557 // Ignore first AddP.
3558 } else {
3559 const Type* elemtype = adr_type->isa_aryptr()->elem();3560 bt = elemtype->array_element_basic_type();
3561 }
3562 } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
3563 // Allocation initialization, ThreadLocal field access, unsafe access
3564 if (has_oop_node_outs(n)) {
3565 bt = T_OBJECT;
3566 }
3567 }
3568 }
3569 // Note: T_NARROWOOP is not classed as a real reference type
3570 bool res = (is_reference_type(bt) || bt == T_NARROWOOP);
3571 assert(!has_oop_node_outs(n) || res, "sanity: AddP has oop outs, needs to be treated as oop field");
3572 return res;
3573 }
3574
3575 bool ConnectionGraph::has_oop_node_outs(Node* n) {
3576 return n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN) ||
3577 n->has_out_with(Op_GetAndSetP, Op_GetAndSetN, Op_CompareAndExchangeP, Op_CompareAndExchangeN) ||
3578 n->has_out_with(Op_CompareAndSwapP, Op_CompareAndSwapN, Op_WeakCompareAndSwapP, Op_WeakCompareAndSwapN) ||
3579 BarrierSet::barrier_set()->barrier_set_c2()->escape_has_out_with_unsafe_object(n);
3580 }
3581
3582 // Returns unique pointed java object or null.
3583 JavaObjectNode* ConnectionGraph::unique_java_object(Node *n) const {
3584 // If the node was created after the escape computation we can't answer.
3585 uint idx = n->_idx;
3586 if (idx >= nodes_size()) {
3587 return nullptr;
3588 }
3589 PointsToNode* ptn = ptnode_adr(idx);
3590 if (ptn == nullptr) {
3591 return nullptr;
3592 }
3593 if (ptn->is_JavaObject()) {
3594 return ptn->as_JavaObject();
3595 }
3596 assert(ptn->is_LocalVar(), "sanity");
3597 // Check all java objects it points to.
3598 JavaObjectNode* jobj = nullptr;
3599 for (EdgeIterator i(ptn); i.has_next(); i.next()) {
3600 PointsToNode* e = i.get();
3601 if (e->is_JavaObject()) {
3602 if (jobj == nullptr) {
3603 jobj = e->as_JavaObject();
3604 } else if (jobj != e) {
3605 return nullptr;
3606 }
3607 }
3608 }
3609 return jobj;
3610 }
3611
3612 // Return true if this node points only to non-escaping allocations.
3613 bool PointsToNode::non_escaping_allocation() {
3614 if (is_JavaObject()) {
3615 Node* n = ideal_node();
3616 if (n->is_Allocate() || n->is_CallStaticJava()) {
3617 return (escape_state() == PointsToNode::NoEscape);
3618 } else {
3619 return false;
3620 }
3621 }
3622 assert(is_LocalVar(), "sanity");
3623 // Check all java objects it points to.
3624 for (EdgeIterator i(this); i.has_next(); i.next()) {
3625 PointsToNode* e = i.get();
3626 if (e->is_JavaObject()) {
3627 Node* n = e->ideal_node();
3628 if ((e->escape_state() != PointsToNode::NoEscape) ||
3629 !(n->is_Allocate() || n->is_CallStaticJava())) {
3630 return false;
3631 }
3632 }
3633 }
3634 return true;
3635 }
3636
3637 // Return true if we know the node does not escape globally.
3638 bool ConnectionGraph::not_global_escape(Node *n) {
3639 assert(!_collecting, "should not call during graph construction");
3640 // If the node was created after the escape computation we can't answer.
3641 uint idx = n->_idx;
3642 if (idx >= nodes_size()) {
3643 return false;
3644 }
3645 PointsToNode* ptn = ptnode_adr(idx);
3646 if (ptn == nullptr) {
3647 return false; // not in congraph (e.g. ConI)
3648 }
3649 PointsToNode::EscapeState es = ptn->escape_state();
3650 // If we have already computed a value, return it.
3651 if (es >= PointsToNode::GlobalEscape) {
3652 return false;
3653 }
3654 if (ptn->is_JavaObject()) {
3655 return true; // (es < PointsToNode::GlobalEscape);
3656 }
3657 assert(ptn->is_LocalVar(), "sanity");
3658 // Check all java objects it points to.
3659 for (EdgeIterator i(ptn); i.has_next(); i.next()) {
3660 if (i.get()->escape_state() >= PointsToNode::GlobalEscape) {
3661 return false;
3662 }
3663 }
3664 return true;
3665 }
3666
3667 // Return true if locked object does not escape globally
3668 // and locked code region (identified by BoxLockNode) is balanced:
3669 // all compiled code paths have corresponding Lock/Unlock pairs.
3670 bool ConnectionGraph::can_eliminate_lock(AbstractLockNode* alock) {
3671 if (alock->is_balanced() && not_global_escape(alock->obj_node())) {
3672 if (EliminateNestedLocks) {
3673 // We can mark whole locking region as Local only when only
3674 // one object is used for locking.
3675 alock->box_node()->as_BoxLock()->set_local();
3676 }
3677 return true;
3678 }
3679 return false;
3680 }
3681
3682 // Helper functions
3683
3684 // Return true if this node points to specified node or nodes it points to.
3685 bool PointsToNode::points_to(JavaObjectNode* ptn) const {
3686 if (is_JavaObject()) {
3687 return (this == ptn);
3688 }
3689 assert(is_LocalVar() || is_Field(), "sanity");
3690 for (EdgeIterator i(this); i.has_next(); i.next()) {
3691 if (i.get() == ptn) {
3692 return true;
3693 }
3694 }
3695 return false;
3696 }
3697
3698 // Return true if one node points to an other.
3699 bool PointsToNode::meet(PointsToNode* ptn) {
3700 if (this == ptn) {
3701 return true;
3702 } else if (ptn->is_JavaObject()) {
3703 return this->points_to(ptn->as_JavaObject());
3704 } else if (this->is_JavaObject()) {
3705 return ptn->points_to(this->as_JavaObject());
3706 }
3707 assert(this->is_LocalVar() && ptn->is_LocalVar(), "sanity");
3708 int ptn_count = ptn->edge_count();
3709 for (EdgeIterator i(this); i.has_next(); i.next()) {
3710 PointsToNode* this_e = i.get();
3711 for (int j = 0; j < ptn_count; j++) {
3712 if (this_e == ptn->edge(j)) {
3713 return true;
3714 }
3715 }
3716 }
3717 return false;
3718 }
3719
3720 #ifdef ASSERT
3721 // Return true if bases point to this java object.
3722 bool FieldNode::has_base(JavaObjectNode* jobj) const {
3723 for (BaseIterator i(this); i.has_next(); i.next()) {
3724 if (i.get() == jobj) {
3725 return true;
3726 }
3727 }
3728 return false;
3729 }
3730 #endif
3731
3732 bool ConnectionGraph::is_captured_store_address(Node* addp) {
3733 // Handle simple case first.
3734 assert(_igvn->type(addp)->isa_oopptr() == nullptr, "should be raw access");
3735 if (addp->in(AddPNode::Address)->is_Proj() && addp->in(AddPNode::Address)->in(0)->is_Allocate()) {
3736 return true;
3737 } else if (addp->in(AddPNode::Address)->is_Phi()) {
3738 for (DUIterator_Fast imax, i = addp->fast_outs(imax); i < imax; i++) {
3739 Node* addp_use = addp->fast_out(i);
3740 if (addp_use->is_Store()) {
3741 for (DUIterator_Fast jmax, j = addp_use->fast_outs(jmax); j < jmax; j++) {
3742 if (addp_use->fast_out(j)->is_Initialize()) {
3743 return true;
3744 }
3745 }
3746 }
3747 }
3748 }
3749 return false;
3750 }
3751
3752 int ConnectionGraph::address_offset(Node* adr, PhaseValues* phase) {
3753 const Type *adr_type = phase->type(adr);
3754 if (adr->is_AddP() && adr_type->isa_oopptr() == nullptr && is_captured_store_address(adr)) {
3755 // We are computing a raw address for a store captured by an Initialize
3756 // compute an appropriate address type. AddP cases #3 and #5 (see below).
3757 int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
3758 assert(offs != Type::OffsetBot ||
3759 adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
3760 "offset must be a constant or it is initialization of array");
3761 return offs;
3762 }
3763 const TypePtr *t_ptr = adr_type->isa_ptr();3764 assert(t_ptr != nullptr, "must be a pointer type");3765 return t_ptr->offset();
3766 }
3767
3768 Node* ConnectionGraph::get_addp_base(Node *addp) {
3769 assert(addp->is_AddP(), "must be AddP");
3770 //
3771 // AddP cases for Base and Address inputs:
3772 // case #1. Direct object's field reference:
3773 // Allocate
3774 // |
3775 // Proj #5 ( oop result )
3776 // |
3777 // CheckCastPP (cast to instance type)
3778 // | |
3779 // AddP ( base == address )
3780 //
3781 // case #2. Indirect object's field reference:
3782 // Phi
3783 // |
3784 // CastPP (cast to instance type)
3785 // | |
3786 // AddP ( base == address )
3787 //
3788 // case #3. Raw object's field reference for Initialize node:
3789 // Allocate
3790 // |
3791 // Proj #5 ( oop result )
3792 // top |
3793 // \ |
3794 // AddP ( base == top )
3795 //
3796 // case #4. Array's element reference:
3797 // {CheckCastPP | CastPP}
3798 // | | |
3799 // | AddP ( array's element offset )
3800 // | |
3801 // AddP ( array's offset )
3802 //
3803 // case #5. Raw object's field reference for arraycopy stub call:
3804 // The inline_native_clone() case when the arraycopy stub is called
3805 // after the allocation before Initialize and CheckCastPP nodes.
3806 // Allocate
3807 // |
3808 // Proj #5 ( oop result )
3809 // | |
3810 // AddP ( base == address )
3811 //
3812 // case #6. Constant Pool, ThreadLocal, CastX2P, Klass, OSR buffer buf or
3813 // Raw object's field reference:
3814 // {ConP, ThreadLocal, CastX2P, raw Load, Parm0}
3815 // top |
3816 // \ |
3817 // AddP ( base == top )
3818 //
3819 // case #7. Klass's field reference.
3820 // LoadKlass
3821 // | |
3822 // AddP ( base == address )
3823 //
3824 // case #8. narrow Klass's field reference.
3825 // LoadNKlass
3826 // |
3827 // DecodeN
3828 // | |
3829 // AddP ( base == address )
3830 //
3831 // case #9. Mixed unsafe access
3832 // {instance}
3833 // |
3834 // CheckCastPP (raw)
3835 // top |
3836 // \ |
3837 // AddP ( base == top )
3838 //
3839 Node *base = addp->in(AddPNode::Base);
3840 if (base->uncast()->is_top()) { // The AddP case #3 and #6 and #9.
3841 base = addp->in(AddPNode::Address);
3842 while (base->is_AddP()) {
3843 // Case #6 (unsafe access) may have several chained AddP nodes.
3844 assert(base->in(AddPNode::Base)->uncast()->is_top(), "expected unsafe access address only");
3845 base = base->in(AddPNode::Address);
3846 }
3847 if (base->Opcode() == Op_CheckCastPP &&
3848 base->bottom_type()->isa_rawptr() &&
3849 _igvn->type(base->in(1))->isa_oopptr()) {
3850 base = base->in(1); // Case #9
3851 } else {
3852 Node* uncast_base = base->uncast();
3853 int opcode = uncast_base->Opcode();
3854 assert(opcode == Op_ConP || opcode == Op_ThreadLocal ||
3855 opcode == Op_CastX2P || uncast_base->is_DecodeNarrowPtr() ||
3856 (_igvn->C->is_osr_compilation() && uncast_base->is_Parm() && uncast_base->as_Parm()->_con == TypeFunc::Parms)||
3857 (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_rawptr() != nullptr)) ||
3858 (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_klassptr() != nullptr)) ||
3859 is_captured_store_address(addp), "sanity");
3860 }
3861 }
3862 return base;
3863 }
3864
3865 Node* ConnectionGraph::find_second_addp(Node* addp, Node* n) {
3866 assert(addp->is_AddP() && addp->outcnt() > 0, "Don't process dead nodes");
3867 Node* addp2 = addp->raw_out(0);
3868 if (addp->outcnt() == 1 && addp2->is_AddP() &&
3869 addp2->in(AddPNode::Base) == n &&
3870 addp2->in(AddPNode::Address) == addp) {
3871 assert(addp->in(AddPNode::Base) == n, "expecting the same base");
3872 //
3873 // Find array's offset to push it on worklist first and
3874 // as result process an array's element offset first (pushed second)
3875 // to avoid CastPP for the array's offset.
3876 // Otherwise the inserted CastPP (LocalVar) will point to what
3877 // the AddP (Field) points to. Which would be wrong since
3878 // the algorithm expects the CastPP has the same point as
3879 // as AddP's base CheckCastPP (LocalVar).
3880 //
3881 // ArrayAllocation
3882 // |
3883 // CheckCastPP
3884 // |
3885 // memProj (from ArrayAllocation CheckCastPP)
3886 // | ||
3887 // | || Int (element index)
3888 // | || | ConI (log(element size))
3889 // | || | /
3890 // | || LShift
3891 // | || /
3892 // | AddP (array's element offset)
3893 // | |
3894 // | | ConI (array's offset: #12(32-bits) or #24(64-bits))
3895 // | / /
3896 // AddP (array's offset)
3897 // |
3898 // Load/Store (memory operation on array's element)
3899 //
3900 return addp2;
3901 }
3902 return nullptr;
3903 }
3904
3905 //
3906 // Adjust the type and inputs of an AddP which computes the
3907 // address of a field of an instance
3908 //
3909 bool ConnectionGraph::split_AddP(Node *addp, Node *base) {
3910 PhaseGVN* igvn = _igvn;
3911 const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
3912 assert(base_t != nullptr && base_t->is_known_instance(), "expecting instance oopptr");
3913 const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
3914 if (t == nullptr) {
3915 // We are computing a raw address for a store captured by an Initialize
3916 // compute an appropriate address type (cases #3 and #5).
3917 assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
3918 assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
3919 intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
3920 assert(offs != Type::OffsetBot, "offset must be a constant");
3921 t = base_t->add_offset(offs)->is_oopptr();
3922 }
3923 int inst_id = base_t->instance_id();
3924 assert(!t->is_known_instance() || t->instance_id() == inst_id,
3925 "old type must be non-instance or match new type");
3926
3927 // The type 't' could be subclass of 'base_t'.
3928 // As result t->offset() could be large then base_t's size and it will
3929 // cause the failure in add_offset() with narrow oops since TypeOopPtr()
3930 // constructor verifies correctness of the offset.
3931 //
3932 // It could happened on subclass's branch (from the type profiling
3933 // inlining) which was not eliminated during parsing since the exactness
3934 // of the allocation type was not propagated to the subclass type check.
3935 //
3936 // Or the type 't' could be not related to 'base_t' at all.
3937 // It could happened when CHA type is different from MDO type on a dead path
3938 // (for example, from instanceof check) which is not collapsed during parsing.
3939 //
3940 // Do nothing for such AddP node and don't process its users since
3941 // this code branch will go away.
3942 //
3943 if (!t->is_known_instance() &&
3944 !base_t->maybe_java_subtype_of(t)) {
3945 return false; // bail out
3946 }
3947 const TypeOopPtr *tinst = base_t->add_offset(t->offset())->is_oopptr();
3948 // Do NOT remove the next line: ensure a new alias index is allocated
3949 // for the instance type. Note: C++ will not remove it since the call
3950 // has side effect.
3951 int alias_idx = _compile->get_alias_index(tinst);
3952 igvn->set_type(addp, tinst);
3953 // record the allocation in the node map
3954 set_map(addp, get_map(base->_idx));
3955 // Set addp's Base and Address to 'base'.
3956 Node *abase = addp->in(AddPNode::Base);
3957 Node *adr = addp->in(AddPNode::Address);
3958 if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
3959 adr->in(0)->_idx == (uint)inst_id) {
3960 // Skip AddP cases #3 and #5.
3961 } else {
3962 assert(!abase->is_top(), "sanity"); // AddP case #3
3963 if (abase != base) {
3964 igvn->hash_delete(addp);
3965 addp->set_req(AddPNode::Base, base);
3966 if (abase == adr) {
3967 addp->set_req(AddPNode::Address, base);
3968 } else {
3969 // AddP case #4 (adr is array's element offset AddP node)
3970 #ifdef ASSERT
3971 const TypeOopPtr *atype = igvn->type(adr)->isa_oopptr();
3972 assert(adr->is_AddP() && atype != nullptr &&
3973 atype->instance_id() == inst_id, "array's element offset should be processed first");
3974 #endif
3975 }
3976 igvn->hash_insert(addp);
3977 }
3978 }
3979 // Put on IGVN worklist since at least addp's type was changed above.
3980 record_for_optimizer(addp);
3981 return true;
3982 }
3983
3984 //
3985 // Create a new version of orig_phi if necessary. Returns either the newly
3986 // created phi or an existing phi. Sets create_new to indicate whether a new
3987 // phi was created. Cache the last newly created phi in the node map.
3988 //
3989 PhiNode* ConnectionGraph::create_split_phi(PhiNode* orig_phi, int alias_idx, Unique_Node_List& orig_phi_worklist, bool& new_created) {
3990 Compile *C = _compile;
3991 PhaseGVN* igvn = _igvn;
3992 new_created = false;
3993 int phi_alias_idx = C->get_alias_index(orig_phi->adr_type());
3994 // nothing to do if orig_phi is bottom memory or matches alias_idx
3995 if (phi_alias_idx == alias_idx) {
3996 return orig_phi;
3997 }
3998 // Have we recently created a Phi for this alias index?
3999 PhiNode *result = get_map_phi(orig_phi->_idx);
4000 if (result != nullptr && C->get_alias_index(result->adr_type()) == alias_idx) {
4001 return result;
4002 }
4003 // Previous check may fail when the same wide memory Phi was split into Phis
4004 // for different memory slices. Search all Phis for this region.
4005 if (result != nullptr) {
4006 Node* region = orig_phi->in(0);
4007 for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
4008 Node* phi = region->fast_out(i);
4009 if (phi->is_Phi() &&
4010 C->get_alias_index(phi->as_Phi()->adr_type()) == alias_idx) {
4011 assert(phi->_idx >= nodes_size(), "only new Phi per instance memory slice");
4012 return phi->as_Phi();
4013 }
4014 }
4015 }
4016 if (C->live_nodes() + 2*NodeLimitFudgeFactor > C->max_node_limit()) {
4017 if (C->do_escape_analysis() == true && !C->failing()) {
4018 // Retry compilation without escape analysis.
4019 // If this is the first failure, the sentinel string will "stick"
4020 // to the Compile object, and the C2Compiler will see it and retry.
4021 C->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
4022 }
4023 return nullptr;
4024 }
4025 orig_phi_worklist.push(orig_phi);
4026 const TypePtr *atype = C->get_adr_type(alias_idx);
4027 result = PhiNode::make(orig_phi->in(0), nullptr, Type::MEMORY, atype);
4028 C->copy_node_notes_to(result, orig_phi);
4029 igvn->set_type(result, result->bottom_type());
4030 record_for_optimizer(result);
4031 set_map(orig_phi, result);
4032 new_created = true;
4033 return result;
4034 }
4035
4036 //
4037 // Return a new version of Memory Phi "orig_phi" with the inputs having the
4038 // specified alias index.
4039 //
4040 PhiNode* ConnectionGraph::split_memory_phi(PhiNode* orig_phi, int alias_idx, Unique_Node_List& orig_phi_worklist, uint rec_depth) {
4041 assert(alias_idx != Compile::AliasIdxBot, "can't split out bottom memory");
4042 Compile *C = _compile;
4043 PhaseGVN* igvn = _igvn;
4044 bool new_phi_created;
4045 PhiNode *result = create_split_phi(orig_phi, alias_idx, orig_phi_worklist, new_phi_created);
4046 if (!new_phi_created) {
4047 return result;
4048 }
4049 Unique_Node_List phi_list;
4050 GrowableArray<uint> cur_input;
4051 PhiNode *phi = orig_phi;
4052 uint idx = 1;
4053 bool finished = false;
4054 while(!finished) {
4055 while (idx < phi->req()) {
4056 Node *mem = find_inst_mem(phi->in(idx), alias_idx, orig_phi_worklist, rec_depth + 1);
4057 if (mem != nullptr && mem->is_Phi()) {
4058 PhiNode *newphi = create_split_phi(mem->as_Phi(), alias_idx, orig_phi_worklist, new_phi_created);
4059 if (new_phi_created) {
4060 // found an phi for which we created a new split, push current one on worklist and begin
4061 // processing new one
4062 phi_list.push(phi);
4063 cur_input.push(idx);
4064 phi = mem->as_Phi();
4065 result = newphi;
4066 idx = 1;
4067 continue;
4068 } else {
4069 mem = newphi;
4070 }
4071 }
4072 if (C->failing()) {
4073 return nullptr;
4074 }
4075 result->set_req(idx++, mem);
4076 }
4077 #ifdef ASSERT
4078 // verify that the new Phi has an input for each input of the original
4079 assert( phi->req() == result->req(), "must have same number of inputs.");
4080 assert( result->in(0) != nullptr && result->in(0) == phi->in(0), "regions must match");
4081 #endif
4082 // Check if all new phi's inputs have specified alias index.
4083 // Otherwise use old phi.
4084 for (uint i = 1; i < phi->req(); i++) {
4085 Node* in = result->in(i);
4086 assert((phi->in(i) == nullptr) == (in == nullptr), "inputs must correspond.");
4087 }
4088 // we have finished processing a Phi, see if there are any more to do
4089 finished = (phi_list.size() == 0);
4090 if (!finished) {
4091 phi = phi_list.pop()->as_Phi();
4092 idx = cur_input.pop();
4093 PhiNode *prev_result = get_map_phi(phi->_idx);
4094 prev_result->set_req(idx++, result);
4095 result = prev_result;
4096 }
4097 }
4098 return result;
4099 }
4100
4101 //
4102 // The next methods are derived from methods in MemNode.
4103 //
4104 Node* ConnectionGraph::step_through_mergemem(MergeMemNode *mmem, int alias_idx, const TypeOopPtr *toop) {
4105 Node *mem = mmem;
4106 // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
4107 // means an array I have not precisely typed yet. Do not do any
4108 // alias stuff with it any time soon.
4109 if (toop->base() != Type::AnyPtr &&
4110 !(toop->isa_instptr() &&
4111 toop->is_instptr()->instance_klass()->is_java_lang_Object() &&
4112 toop->offset() == Type::OffsetBot)) {
4113 mem = mmem->memory_at(alias_idx);
4114 // Update input if it is progress over what we have now
4115 }
4116 return mem;
4117 }
4118
4119 //
4120 // Move memory users to their memory slices.
4121 //
4122 void ConnectionGraph::move_inst_mem(Node* n, Unique_Node_List& orig_phis) {
4123 Compile* C = _compile;
4124 PhaseGVN* igvn = _igvn;
4125 const TypePtr* tp = igvn->type(n->in(MemNode::Address))->isa_ptr();
4126 assert(tp != nullptr, "ptr type");
4127 int alias_idx = C->get_alias_index(tp);
4128 int general_idx = C->get_general_index(alias_idx);
4129
4130 // Move users first
4131 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4132 Node* use = n->fast_out(i);
4133 if (use->is_MergeMem()) {
4134 MergeMemNode* mmem = use->as_MergeMem();
4135 assert(n == mmem->memory_at(alias_idx), "should be on instance memory slice");
4136 if (n != mmem->memory_at(general_idx) || alias_idx == general_idx) {
4137 continue; // Nothing to do
4138 }
4139 // Replace previous general reference to mem node.
4140 uint orig_uniq = C->unique();
4141 Node* m = find_inst_mem(n, general_idx, orig_phis);
4142 assert(orig_uniq == C->unique(), "no new nodes");
4143 mmem->set_memory_at(general_idx, m);
4144 --imax;
4145 --i;
4146 } else if (use->is_MemBar()) {
4147 assert(!use->is_Initialize(), "initializing stores should not be moved");
4148 if (use->req() > MemBarNode::Precedent &&
4149 use->in(MemBarNode::Precedent) == n) {
4150 // Don't move related membars.
4151 record_for_optimizer(use);
4152 continue;
4153 }
4154 tp = use->as_MemBar()->adr_type()->isa_ptr();
4155 if ((tp != nullptr && C->get_alias_index(tp) == alias_idx) ||
4156 alias_idx == general_idx) {
4157 continue; // Nothing to do
4158 }
4159 // Move to general memory slice.
4160 uint orig_uniq = C->unique();
4161 Node* m = find_inst_mem(n, general_idx, orig_phis);
4162 assert(orig_uniq == C->unique(), "no new nodes");
4163 igvn->hash_delete(use);
4164 imax -= use->replace_edge(n, m, igvn);
4165 igvn->hash_insert(use);
4166 record_for_optimizer(use);
4167 --i;
4168 #ifdef ASSERT
4169 } else if (use->is_Mem()) {
4170 // Memory nodes should have new memory input.
4171 tp = igvn->type(use->in(MemNode::Address))->isa_ptr();
4172 assert(tp != nullptr, "ptr type");
4173 int idx = C->get_alias_index(tp);
4174 assert(get_map(use->_idx) != nullptr || idx == alias_idx,
4175 "Following memory nodes should have new memory input or be on the same memory slice");
4176 } else if (use->is_Phi()) {
4177 // Phi nodes should be split and moved already.
4178 tp = use->as_Phi()->adr_type()->isa_ptr();
4179 assert(tp != nullptr, "ptr type");
4180 int idx = C->get_alias_index(tp);
4181 assert(idx == alias_idx, "Following Phi nodes should be on the same memory slice");
4182 } else {
4183 use->dump();
4184 assert(false, "should not be here");
4185 #endif
4186 }
4187 }
4188 }
4189
4190 //
4191 // Search memory chain of "mem" to find a MemNode whose address
4192 // is the specified alias index.
4193 //
4194 #define FIND_INST_MEM_RECURSION_DEPTH_LIMIT 1000
4195 Node* ConnectionGraph::find_inst_mem(Node* orig_mem, int alias_idx, Unique_Node_List& orig_phis, uint rec_depth) {
4196 if (rec_depth > FIND_INST_MEM_RECURSION_DEPTH_LIMIT) {
4197 _compile->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
4198 return nullptr;
4199 }
4200 if (orig_mem == nullptr) {
4201 return orig_mem;
4202 }
4203 Compile* C = _compile;
4204 PhaseGVN* igvn = _igvn;
4205 const TypeOopPtr *toop = C->get_adr_type(alias_idx)->isa_oopptr();
4206 bool is_instance = (toop != nullptr) && toop->is_known_instance();
4207 Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
4208 Node *prev = nullptr;
4209 Node *result = orig_mem;
4210 while (prev != result) {
4211 prev = result;
4212 if (result == start_mem) {
4213 break; // hit one of our sentinels
4214 }
4215 if (result->is_Mem()) {
4216 const Type *at = igvn->type(result->in(MemNode::Address));
4217 if (at == Type::TOP) {
4218 break; // Dead
4219 }
4220 assert (at->isa_ptr() != nullptr, "pointer type required.");
4221 int idx = C->get_alias_index(at->is_ptr());
4222 if (idx == alias_idx) {
4223 break; // Found
4224 }
4225 if (!is_instance && (at->isa_oopptr() == nullptr ||
4226 !at->is_oopptr()->is_known_instance())) {
4227 break; // Do not skip store to general memory slice.
4228 }
4229 result = result->in(MemNode::Memory);
4230 }
4231 if (!is_instance) {
4232 continue; // don't search further for non-instance types
4233 }
4234 // skip over a call which does not affect this memory slice
4235 if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
4236 Node *proj_in = result->in(0);
4237 if (proj_in->is_Allocate() && proj_in->_idx == (uint)toop->instance_id()) {
4238 break; // hit one of our sentinels
4239 } else if (proj_in->is_Call()) {
4240 // ArrayCopy node processed here as well
4241 CallNode *call = proj_in->as_Call();
4242 if (!call->may_modify(toop, igvn)) {
4243 result = call->in(TypeFunc::Memory);
4244 }
4245 } else if (proj_in->is_Initialize()) {
4246 AllocateNode* alloc = proj_in->as_Initialize()->allocation();
4247 // Stop if this is the initialization for the object instance which
4248 // which contains this memory slice, otherwise skip over it.
4249 if (alloc == nullptr || alloc->_idx != (uint)toop->instance_id()) {
4250 result = proj_in->in(TypeFunc::Memory);
4251 } else if (C->get_alias_index(result->adr_type()) != alias_idx) {
4252 assert(C->get_general_index(alias_idx) == C->get_alias_index(result->adr_type()), "should be projection for the same field/array element");
4253 result = get_map(result->_idx);
4254 assert(result != nullptr, "new projection should have been allocated");
4255 break;
4256 }
4257 } else if (proj_in->is_MemBar()) {
4258 // Check if there is an array copy for a clone
4259 // Step over GC barrier when ReduceInitialCardMarks is disabled
4260 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4261 Node* control_proj_ac = bs->step_over_gc_barrier(proj_in->in(0));
4262
4263 if (control_proj_ac->is_Proj() && control_proj_ac->in(0)->is_ArrayCopy()) {
4264 // Stop if it is a clone
4265 ArrayCopyNode* ac = control_proj_ac->in(0)->as_ArrayCopy();
4266 if (ac->may_modify(toop, igvn)) {
4267 break;
4268 }
4269 }
4270 result = proj_in->in(TypeFunc::Memory);
4271 }
4272 } else if (result->is_MergeMem()) {
4273 MergeMemNode *mmem = result->as_MergeMem();
4274 result = step_through_mergemem(mmem, alias_idx, toop);
4275 if (result == mmem->base_memory()) {
4276 // Didn't find instance memory, search through general slice recursively.
4277 result = mmem->memory_at(C->get_general_index(alias_idx));
4278 result = find_inst_mem(result, alias_idx, orig_phis, rec_depth + 1);
4279 if (C->failing()) {
4280 return nullptr;
4281 }
4282 mmem->set_memory_at(alias_idx, result);
4283 }
4284 } else if (result->is_Phi() &&
4285 C->get_alias_index(result->as_Phi()->adr_type()) != alias_idx) {
4286 Node *un = result->as_Phi()->unique_input(igvn);
4287 if (un != nullptr) {
4288 orig_phis.push(result);
4289 result = un;
4290 } else {
4291 break;
4292 }
4293 } else if (result->is_ClearArray()) {
4294 if (!ClearArrayNode::step_through(&result, (uint)toop->instance_id(), igvn)) {
4295 // Can not bypass initialization of the instance
4296 // we are looking for.
4297 break;
4298 }
4299 // Otherwise skip it (the call updated 'result' value).
4300 } else if (result->Opcode() == Op_SCMemProj) {
4301 Node* mem = result->in(0);
4302 Node* adr = nullptr;
4303 if (mem->is_LoadStore()) {
4304 adr = mem->in(MemNode::Address);
4305 } else {
4306 assert(mem->Opcode() == Op_EncodeISOArray ||
4307 mem->Opcode() == Op_StrCompressedCopy, "sanity");
4308 adr = mem->in(3); // Memory edge corresponds to destination array
4309 }
4310 const Type *at = igvn->type(adr);
4311 if (at != Type::TOP) {
4312 assert(at->isa_ptr() != nullptr, "pointer type required.");
4313 int idx = C->get_alias_index(at->is_ptr());
4314 if (idx == alias_idx) {
4315 // Assert in debug mode
4316 assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
4317 break; // In product mode return SCMemProj node
4318 }
4319 }
4320 result = mem->in(MemNode::Memory);
4321 } else if (result->Opcode() == Op_StrInflatedCopy) {
4322 Node* adr = result->in(3); // Memory edge corresponds to destination array
4323 const Type *at = igvn->type(adr);
4324 if (at != Type::TOP) {
4325 assert(at->isa_ptr() != nullptr, "pointer type required.");
4326 int idx = C->get_alias_index(at->is_ptr());
4327 if (idx == alias_idx) {
4328 // Assert in debug mode
4329 assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
4330 break; // In product mode return SCMemProj node
4331 }
4332 }
4333 result = result->in(MemNode::Memory);
4334 }
4335 }
4336 if (result->is_Phi()) {
4337 PhiNode *mphi = result->as_Phi();
4338 assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
4339 const TypePtr *t = mphi->adr_type();
4340 if (!is_instance) {
4341 // Push all non-instance Phis on the orig_phis worklist to update inputs
4342 // during Phase 4 if needed.
4343 orig_phis.push(mphi);
4344 } else if (C->get_alias_index(t) != alias_idx) {
4345 // Create a new Phi with the specified alias index type.
4346 result = split_memory_phi(mphi, alias_idx, orig_phis, rec_depth + 1);
4347 }
4348 }
4349 // the result is either MemNode, PhiNode, InitializeNode.
4350 return result;
4351 }
4352
4353 //
4354 // Convert the types of non-escaped object to instance types where possible,
4355 // propagate the new type information through the graph, and update memory
4356 // edges and MergeMem inputs to reflect the new type.
4357 //
4358 // We start with allocations (and calls which may be allocations) on alloc_worklist.
4359 // The processing is done in 4 phases:
4360 //
4361 // Phase 1: Process possible allocations from alloc_worklist. Create instance
4362 // types for the CheckCastPP for allocations where possible.
4363 // Propagate the new types through users as follows:
4364 // casts and Phi: push users on alloc_worklist
4365 // AddP: cast Base and Address inputs to the instance type
4366 // push any AddP users on alloc_worklist and push any memnode
4367 // users onto memnode_worklist.
4368 // Phase 2: Process MemNode's from memnode_worklist. compute new address type and
4369 // search the Memory chain for a store with the appropriate type
4370 // address type. If a Phi is found, create a new version with
4371 // the appropriate memory slices from each of the Phi inputs.
4372 // For stores, process the users as follows:
4373 // MemNode: push on memnode_worklist
4374 // MergeMem: push on mergemem_worklist
4375 // Phase 3: Process MergeMem nodes from mergemem_worklist. Walk each memory slice
4376 // moving the first node encountered of each instance type to the
4377 // the input corresponding to its alias index.
4378 // appropriate memory slice.
4379 // Phase 4: Update the inputs of non-instance memory Phis and the Memory input of memnodes.
4380 //
4381 // In the following example, the CheckCastPP nodes are the cast of allocation
4382 // results and the allocation of node 29 is non-escaped and eligible to be an
4383 // instance type.
4384 //
4385 // We start with:
4386 //
4387 // 7 Parm #memory
4388 // 10 ConI "12"
4389 // 19 CheckCastPP "Foo"
4390 // 20 AddP _ 19 19 10 Foo+12 alias_index=4
4391 // 29 CheckCastPP "Foo"
4392 // 30 AddP _ 29 29 10 Foo+12 alias_index=4
4393 //
4394 // 40 StoreP 25 7 20 ... alias_index=4
4395 // 50 StoreP 35 40 30 ... alias_index=4
4396 // 60 StoreP 45 50 20 ... alias_index=4
4397 // 70 LoadP _ 60 30 ... alias_index=4
4398 // 80 Phi 75 50 60 Memory alias_index=4
4399 // 90 LoadP _ 80 30 ... alias_index=4
4400 // 100 LoadP _ 80 20 ... alias_index=4
4401 //
4402 //
4403 // Phase 1 creates an instance type for node 29 assigning it an instance id of 24
4404 // and creating a new alias index for node 30. This gives:
4405 //
4406 // 7 Parm #memory
4407 // 10 ConI "12"
4408 // 19 CheckCastPP "Foo"
4409 // 20 AddP _ 19 19 10 Foo+12 alias_index=4
4410 // 29 CheckCastPP "Foo" iid=24
4411 // 30 AddP _ 29 29 10 Foo+12 alias_index=6 iid=24
4412 //
4413 // 40 StoreP 25 7 20 ... alias_index=4
4414 // 50 StoreP 35 40 30 ... alias_index=6
4415 // 60 StoreP 45 50 20 ... alias_index=4
4416 // 70 LoadP _ 60 30 ... alias_index=6
4417 // 80 Phi 75 50 60 Memory alias_index=4
4418 // 90 LoadP _ 80 30 ... alias_index=6
4419 // 100 LoadP _ 80 20 ... alias_index=4
4420 //
4421 // In phase 2, new memory inputs are computed for the loads and stores,
4422 // And a new version of the phi is created. In phase 4, the inputs to
4423 // node 80 are updated and then the memory nodes are updated with the
4424 // values computed in phase 2. This results in:
4425 //
4426 // 7 Parm #memory
4427 // 10 ConI "12"
4428 // 19 CheckCastPP "Foo"
4429 // 20 AddP _ 19 19 10 Foo+12 alias_index=4
4430 // 29 CheckCastPP "Foo" iid=24
4431 // 30 AddP _ 29 29 10 Foo+12 alias_index=6 iid=24
4432 //
4433 // 40 StoreP 25 7 20 ... alias_index=4
4434 // 50 StoreP 35 7 30 ... alias_index=6
4435 // 60 StoreP 45 40 20 ... alias_index=4
4436 // 70 LoadP _ 50 30 ... alias_index=6
4437 // 80 Phi 75 40 60 Memory alias_index=4
4438 // 120 Phi 75 50 50 Memory alias_index=6
4439 // 90 LoadP _ 120 30 ... alias_index=6
4440 // 100 LoadP _ 80 20 ... alias_index=4
4441 //
4442 void ConnectionGraph::split_unique_types(GrowableArray<Node *> &alloc_worklist,
4443 GrowableArray<ArrayCopyNode*> &arraycopy_worklist,
4444 GrowableArray<MergeMemNode*> &mergemem_worklist,
4445 Unique_Node_List &reducible_merges) {
4446 DEBUG_ONLY(Unique_Node_List reduced_merges;)
4447 Unique_Node_List memnode_worklist;
4448 Unique_Node_List orig_phis;
4449 PhaseIterGVN *igvn = _igvn;
4450 uint new_index_start = (uint) _compile->num_alias_types();
4451 VectorSet visited;
4452 ideal_nodes.clear(); // Reset for use with set_map/get_map.
4453
4454 // Phase 1: Process possible allocations from alloc_worklist.
4455 // Create instance types for the CheckCastPP for allocations where possible.
4456 //
4457 // (Note: don't forget to change the order of the second AddP node on
4458 // the alloc_worklist if the order of the worklist processing is changed,
4459 // see the comment in find_second_addp().)
4460 //
4461 while (alloc_worklist.length() != 0) {
4462 Node *n = alloc_worklist.pop();
4463 uint ni = n->_idx;
4464 if (n->is_Call()) {
4465 CallNode *alloc = n->as_Call();
4466 // copy escape information to call node
4467 PointsToNode* ptn = ptnode_adr(alloc->_idx);
4468 PointsToNode::EscapeState es = ptn->escape_state();
4469 // We have an allocation or call which returns a Java object,
4470 // see if it is non-escaped.
4471 if (es != PointsToNode::NoEscape || !ptn->scalar_replaceable()) {
4472 continue;
4473 }
4474 // Find CheckCastPP for the allocate or for the return value of a call
4475 n = alloc->result_cast();
4476 if (n == nullptr) { // No uses except Initialize node
4477 if (alloc->is_Allocate()) {
4478 // Set the scalar_replaceable flag for allocation
4479 // so it could be eliminated if it has no uses.
4480 alloc->as_Allocate()->_is_scalar_replaceable = true;
4481 }
4482 continue;
4483 }
4484 if (!n->is_CheckCastPP()) { // not unique CheckCastPP.
4485 // we could reach here for allocate case if one init is associated with many allocs.
4486 if (alloc->is_Allocate()) {
4487 alloc->as_Allocate()->_is_scalar_replaceable = false;
4488 }
4489 continue;
4490 }
4491
4492 // The inline code for Object.clone() casts the allocation result to
4493 // java.lang.Object and then to the actual type of the allocated
4494 // object. Detect this case and use the second cast.
4495 // Also detect j.l.reflect.Array.newInstance(jobject, jint) case when
4496 // the allocation result is cast to java.lang.Object and then
4497 // to the actual Array type.
4498 if (alloc->is_Allocate() && n->as_Type()->type() == TypeInstPtr::NOTNULL
4499 && (alloc->is_AllocateArray() ||
4500 igvn->type(alloc->in(AllocateNode::KlassNode)) != TypeInstKlassPtr::OBJECT)) {
4501 Node *cast2 = nullptr;
4502 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4503 Node *use = n->fast_out(i);
4504 if (use->is_CheckCastPP()) {
4505 cast2 = use;
4506 break;
4507 }
4508 }
4509 if (cast2 != nullptr) {
4510 n = cast2;
4511 } else {
4512 // Non-scalar replaceable if the allocation type is unknown statically
4513 // (reflection allocation), the object can't be restored during
4514 // deoptimization without precise type.
4515 continue;
4516 }
4517 }
4518
4519 const TypeOopPtr *t = igvn->type(n)->isa_oopptr();
4520 if (t == nullptr) {
4521 continue; // not a TypeOopPtr
4522 }
4523 if (!t->klass_is_exact()) {
4524 continue; // not an unique type
4525 }
4526 if (alloc->is_Allocate()) {
4527 // Set the scalar_replaceable flag for allocation
4528 // so it could be eliminated.
4529 alloc->as_Allocate()->_is_scalar_replaceable = true;
4530 }
4531 set_escape_state(ptnode_adr(n->_idx), es NOT_PRODUCT(COMMA trace_propagate_message(ptn))); // CheckCastPP escape state
4532 // in order for an object to be scalar-replaceable, it must be:
4533 // - a direct allocation (not a call returning an object)
4534 // - non-escaping
4535 // - eligible to be a unique type
4536 // - not determined to be ineligible by escape analysis
4537 set_map(alloc, n);
4538 set_map(n, alloc);
4539 const TypeOopPtr* tinst = t->cast_to_instance_id(ni);
4540 igvn->hash_delete(n);
4541 igvn->set_type(n, tinst);
4542 n->raise_bottom_type(tinst);
4543 igvn->hash_insert(n);
4544 record_for_optimizer(n);
4545 // Allocate an alias index for the header fields. Accesses to
4546 // the header emitted during macro expansion wouldn't have
4547 // correct memory state otherwise.
4548 _compile->get_alias_index(tinst->add_offset(oopDesc::mark_offset_in_bytes()));
4549 _compile->get_alias_index(tinst->add_offset(oopDesc::klass_offset_in_bytes()));
4550 if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
4551 // Add a new NarrowMem projection for each existing NarrowMem projection with new adr type
4552 InitializeNode* init = alloc->as_Allocate()->initialization();
4553 assert(init != nullptr, "can't find Initialization node for this Allocate node");
4554 auto process_narrow_proj = [&](NarrowMemProjNode* proj) {
4555 const TypePtr* adr_type = proj->adr_type();
4556 const TypePtr* new_adr_type = tinst->add_offset(adr_type->offset());
4557 if (adr_type != new_adr_type && !init->already_has_narrow_mem_proj_with_adr_type(new_adr_type)) {
4558 // Do NOT remove the next line: ensure a new alias index is allocated for the instance type.
4559 uint alias_idx = _compile->get_alias_index(new_adr_type);
4560 assert(_compile->get_general_index(alias_idx) == _compile->get_alias_index(adr_type), "new adr type should be narrowed down from existing adr type");
4561 NarrowMemProjNode* new_proj = new NarrowMemProjNode(init, new_adr_type);
4562 igvn->set_type(new_proj, new_proj->bottom_type());
4563 record_for_optimizer(new_proj);
4564 set_map(proj, new_proj); // record it so ConnectionGraph::find_inst_mem() can find it
4565 }
4566 };
4567 init->for_each_narrow_mem_proj_with_new_uses(process_narrow_proj);
4568
4569 // First, put on the worklist all Field edges from Connection Graph
4570 // which is more accurate than putting immediate users from Ideal Graph.
4571 for (EdgeIterator e(ptn); e.has_next(); e.next()) {
4572 PointsToNode* tgt = e.get();
4573 if (tgt->is_Arraycopy()) {
4574 continue;
4575 }
4576 Node* use = tgt->ideal_node();
4577 assert(tgt->is_Field() && use->is_AddP(),
4578 "only AddP nodes are Field edges in CG");
4579 if (use->outcnt() > 0) { // Don't process dead nodes
4580 Node* addp2 = find_second_addp(use, use->in(AddPNode::Base));
4581 if (addp2 != nullptr) {
4582 assert(alloc->is_AllocateArray(),"array allocation was expected");
4583 alloc_worklist.append_if_missing(addp2);
4584 }
4585 alloc_worklist.append_if_missing(use);
4586 }
4587 }
4588
4589 // An allocation may have an Initialize which has raw stores. Scan
4590 // the users of the raw allocation result and push AddP users
4591 // on alloc_worklist.
4592 Node *raw_result = alloc->proj_out_or_null(TypeFunc::Parms);
4593 assert (raw_result != nullptr, "must have an allocation result");
4594 for (DUIterator_Fast imax, i = raw_result->fast_outs(imax); i < imax; i++) {
4595 Node *use = raw_result->fast_out(i);
4596 if (use->is_AddP() && use->outcnt() > 0) { // Don't process dead nodes
4597 Node* addp2 = find_second_addp(use, raw_result);
4598 if (addp2 != nullptr) {
4599 assert(alloc->is_AllocateArray(),"array allocation was expected");
4600 alloc_worklist.append_if_missing(addp2);
4601 }
4602 alloc_worklist.append_if_missing(use);
4603 } else if (use->is_MemBar()) {
4604 memnode_worklist.push(use);
4605 }
4606 }
4607 }
4608 } else if (n->is_AddP()) {
4609 if (has_reducible_merge_base(n->as_AddP(), reducible_merges)) {
4610 // This AddP will go away when we reduce the Phi
4611 continue;
4612 }
4613 Node* addp_base = get_addp_base(n);
4614 JavaObjectNode* jobj = unique_java_object(addp_base);
4615 if (jobj == nullptr || jobj == phantom_obj) {
4616 #ifdef ASSERT
4617 ptnode_adr(get_addp_base(n)->_idx)->dump();
4618 ptnode_adr(n->_idx)->dump();
4619 assert(jobj != nullptr && jobj != phantom_obj, "escaped allocation");
4620 #endif
4621 _compile->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
4622 return;
4623 }
4624 Node *base = get_map(jobj->idx()); // CheckCastPP node
4625 if (!split_AddP(n, base)) continue; // wrong type from dead path
4626 } else if (n->is_Phi() ||
4627 n->is_CheckCastPP() ||
4628 n->is_EncodeP() ||
4629 n->is_DecodeN() ||
4630 (n->is_ConstraintCast() && n->Opcode() == Op_CastPP)) {
4631 if (visited.test_set(n->_idx)) {
4632 assert(n->is_Phi(), "loops only through Phi's");
4633 continue; // already processed
4634 }
4635 // Reducible Phi's will be removed from the graph after split_unique_types
4636 // finishes. For now we just try to split out the SR inputs of the merge.
4637 Node* parent = n->in(1);
4638 if (reducible_merges.member(n)) {
4639 reduce_phi(n->as_Phi(), alloc_worklist);
4640 #ifdef ASSERT
4641 if (VerifyReduceAllocationMerges) {
4642 reduced_merges.push(n);
4643 }
4644 #endif
4645 continue;
4646 } else if (reducible_merges.member(parent)) {
4647 // 'n' is an user of a reducible merge (a Phi). It will be simplified as
4648 // part of reduce_merge.
4649 continue;
4650 }
4651 JavaObjectNode* jobj = unique_java_object(n);
4652 if (jobj == nullptr || jobj == phantom_obj) {
4653 #ifdef ASSERT
4654 ptnode_adr(n->_idx)->dump();
4655 assert(jobj != nullptr && jobj != phantom_obj, "escaped allocation");
4656 #endif
4657 _compile->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
4658 return;
4659 } else {
4660 Node *val = get_map(jobj->idx()); // CheckCastPP node
4661 TypeNode *tn = n->as_Type();
4662 const TypeOopPtr* tinst = igvn->type(val)->isa_oopptr();
4663 assert(tinst != nullptr && tinst->is_known_instance() &&
4664 tinst->instance_id() == jobj->idx() , "instance type expected.");
4665
4666 const Type *tn_type = igvn->type(tn);
4667 const TypeOopPtr *tn_t;
4668 if (tn_type->isa_narrowoop()) {
4669 tn_t = tn_type->make_ptr()->isa_oopptr();
4670 } else {
4671 tn_t = tn_type->isa_oopptr();
4672 }
4673 if (tn_t != nullptr && tinst->maybe_java_subtype_of(tn_t)) {
4674 if (tn_type->isa_narrowoop()) {
4675 tn_type = tinst->make_narrowoop();
4676 } else {
4677 tn_type = tinst;
4678 }
4679 igvn->hash_delete(tn);
4680 igvn->set_type(tn, tn_type);
4681 tn->set_type(tn_type);
4682 igvn->hash_insert(tn);
4683 record_for_optimizer(n);
4684 } else {
4685 assert(tn_type == TypePtr::NULL_PTR ||
4686 (tn_t != nullptr && !tinst->maybe_java_subtype_of(tn_t)),
4687 "unexpected type");
4688 continue; // Skip dead path with different type
4689 }
4690 }
4691 } else {
4692 DEBUG_ONLY(n->dump();)
4693 assert(false, "EA: unexpected node");
4694 continue;
4695 }
4696 // push allocation's users on appropriate worklist
4697 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4698 Node *use = n->fast_out(i);
4699 if(use->is_Mem() && use->in(MemNode::Address) == n) {
4700 // Load/store to instance's field
4701 memnode_worklist.push(use);
4702 } else if (use->is_MemBar()) {
4703 if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
4704 memnode_worklist.push(use);
4705 }
4706 } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
4707 Node* addp2 = find_second_addp(use, n);
4708 if (addp2 != nullptr) {
4709 alloc_worklist.append_if_missing(addp2);
4710 }
4711 alloc_worklist.append_if_missing(use);
4712 } else if (use->is_Phi() ||
4713 use->is_CheckCastPP() ||
4714 use->is_EncodeNarrowPtr() ||
4715 use->is_DecodeNarrowPtr() ||
4716 (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
4717 alloc_worklist.append_if_missing(use);
4718 #ifdef ASSERT
4719 } else if (use->is_Mem()) {
4720 assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
4721 } else if (use->is_MergeMem()) {
4722 assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4723 } else if (use->is_SafePoint()) {
4724 // Look for MergeMem nodes for calls which reference unique allocation
4725 // (through CheckCastPP nodes) even for debug info.
4726 Node* m = use->in(TypeFunc::Memory);
4727 if (m->is_MergeMem()) {
4728 assert(mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4729 }
4730 } else if (use->Opcode() == Op_EncodeISOArray) {
4731 if (use->in(MemNode::Memory) == n || use->in(3) == n) {
4732 // EncodeISOArray overwrites destination array
4733 memnode_worklist.push(use);
4734 }
4735 } else {
4736 uint op = use->Opcode();
4737 if ((op == Op_StrCompressedCopy || op == Op_StrInflatedCopy) &&
4738 (use->in(MemNode::Memory) == n)) {
4739 // They overwrite memory edge corresponding to destination array,
4740 memnode_worklist.push(use);
4741 } else if (!(op == Op_CmpP || op == Op_Conv2B ||
4742 op == Op_CastP2X ||
4743 op == Op_FastLock || op == Op_AryEq ||
4744 op == Op_StrComp || op == Op_CountPositives ||
4745 op == Op_StrCompressedCopy || op == Op_StrInflatedCopy ||
4746 op == Op_StrEquals || op == Op_VectorizedHashCode ||
4747 op == Op_StrIndexOf || op == Op_StrIndexOfChar ||
4748 op == Op_SubTypeCheck ||
4749 op == Op_ReinterpretS2HF ||
4750 op == Op_ReachabilityFence ||
4751 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use))) {
4752 n->dump();
4753 use->dump();
4754 assert(false, "EA: missing allocation reference path");
4755 }
4756 #endif
4757 }
4758 }
4759
4760 }
4761
4762 #ifdef ASSERT
4763 if (VerifyReduceAllocationMerges) {
4764 for (uint i = 0; i < reducible_merges.size(); i++) {
4765 Node* phi = reducible_merges.at(i);
4766
4767 if (!reduced_merges.member(phi)) {
4768 phi->dump(2);
4769 phi->dump(-2);
4770 assert(false, "This reducible merge wasn't reduced.");
4771 }
4772
4773 // At this point reducible Phis shouldn't have AddP users anymore; only SafePoints or Casts.
4774 for (DUIterator_Fast jmax, j = phi->fast_outs(jmax); j < jmax; j++) {
4775 Node* use = phi->fast_out(j);
4776 if (!use->is_SafePoint() && !use->is_CastPP()) {
4777 phi->dump(2);
4778 phi->dump(-2);
4779 assert(false, "Unexpected user of reducible Phi -> %d:%s:%d", use->_idx, use->Name(), use->outcnt());
4780 }
4781 }
4782 }
4783 }
4784 #endif
4785
4786 // Go over all ArrayCopy nodes and if one of the inputs has a unique
4787 // type, record it in the ArrayCopy node so we know what memory this
4788 // node uses/modified.
4789 for (int next = 0; next < arraycopy_worklist.length(); next++) {
4790 ArrayCopyNode* ac = arraycopy_worklist.at(next);
4791 Node* dest = ac->in(ArrayCopyNode::Dest);
4792 if (dest->is_AddP()) {
4793 dest = get_addp_base(dest);
4794 }
4795 JavaObjectNode* jobj = unique_java_object(dest);
4796 if (jobj != nullptr) {
4797 Node *base = get_map(jobj->idx());
4798 if (base != nullptr) {
4799 const TypeOopPtr *base_t = _igvn->type(base)->isa_oopptr();
4800 ac->_dest_type = base_t;
4801 }
4802 }
4803 Node* src = ac->in(ArrayCopyNode::Src);
4804 if (src->is_AddP()) {
4805 src = get_addp_base(src);
4806 }
4807 jobj = unique_java_object(src);
4808 if (jobj != nullptr) {
4809 Node* base = get_map(jobj->idx());
4810 if (base != nullptr) {
4811 const TypeOopPtr *base_t = _igvn->type(base)->isa_oopptr();
4812 ac->_src_type = base_t;
4813 }
4814 }
4815 }
4816
4817 // New alias types were created in split_AddP().
4818 uint new_index_end = (uint) _compile->num_alias_types();
4819
4820 _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES_1, 5);
4821
4822 // Phase 2: Process MemNode's from memnode_worklist. compute new address type and
4823 // compute new values for Memory inputs (the Memory inputs are not
4824 // actually updated until phase 4.)
4825 if (memnode_worklist.size() == 0) {
4826 return; // nothing to do
4827 }
4828 while (memnode_worklist.size() != 0) {
4829 Node *n = memnode_worklist.pop();
4830 if (visited.test_set(n->_idx)) {
4831 continue;
4832 }
4833 if (n->is_Phi()) {
4834 if ((uint) _compile->get_alias_index(n->adr_type()) < new_index_start) {
4835 // Push memory phis on the orig_phis worklist to update
4836 // during Phase 4 if needed.
4837 orig_phis.push(n);
4838 }
4839 } else if (n->is_ClearArray()) {
4840 // we don't need to do anything, but the users must be pushed
4841 } else if (n->is_MemBar()) { // MemBar nodes
4842 if (!n->is_Initialize()) { // memory projections for Initialize pushed below (so we get to all their uses)
4843 // we don't need to do anything, but the users must be pushed
4844 n = n->as_MemBar()->proj_out_or_null(TypeFunc::Memory);
4845 if (n == nullptr) {
4846 continue;
4847 }
4848 }
4849 } else if (n->is_CallLeaf()) {
4850 // Runtime calls with narrow memory input (no MergeMem node)
4851 // get the memory projection
4852 n = n->as_Call()->proj_out_or_null(TypeFunc::Memory);
4853 if (n == nullptr) {
4854 continue;
4855 }
4856 } else if (n->Opcode() == Op_StrInflatedCopy) {
4857 // Check direct uses of StrInflatedCopy.
4858 // It is memory type Node - no special SCMemProj node.
4859 } else if (n->Opcode() == Op_StrCompressedCopy ||
4860 n->Opcode() == Op_EncodeISOArray) {
4861 // get the memory projection
4862 n = n->find_out_with(Op_SCMemProj);
4863 assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
4864 } else if (n->is_Proj()) {
4865 assert(n->in(0)->is_Initialize(), "we only push memory projections for Initialize");
4866 } else {
4867 #ifdef ASSERT
4868 if (!n->is_Mem()) {
4869 n->dump();
4870 }
4871 assert(n->is_Mem(), "memory node required.");
4872 #endif
4873 Node *addr = n->in(MemNode::Address);
4874 const Type *addr_t = igvn->type(addr);
4875 if (addr_t == Type::TOP) {
4876 continue;
4877 }
4878 assert (addr_t->isa_ptr() != nullptr, "pointer type required.");
4879 int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
4880 assert ((uint)alias_idx < new_index_end, "wrong alias index");
4881 Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis);
4882 if (_compile->failing()) {
4883 return;
4884 }
4885 if (mem != n->in(MemNode::Memory)) {
4886 // We delay the memory edge update since we need old one in
4887 // MergeMem code below when instances memory slices are separated.
4888 set_map(n, mem);
4889 }
4890 if (n->is_Load()) {
4891 continue; // don't push users
4892 } else if (n->is_LoadStore()) {
4893 // get the memory projection
4894 n = n->find_out_with(Op_SCMemProj);
4895 assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
4896 }
4897 }
4898 // push user on appropriate worklist
4899 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4900 Node *use = n->fast_out(i);
4901 if (use->is_Phi() || use->is_ClearArray()) {
4902 memnode_worklist.push(use);
4903 } else if (use->is_Mem() && use->in(MemNode::Memory) == n) {
4904 memnode_worklist.push(use);
4905 } else if (use->is_MemBar() || use->is_CallLeaf()) {
4906 if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
4907 memnode_worklist.push(use);
4908 }
4909 } else if (use->is_Proj()) {
4910 assert(n->is_Initialize(), "We only push projections of Initialize");
4911 if (use->as_Proj()->_con == TypeFunc::Memory) { // Ignore precedent edge
4912 memnode_worklist.push(use);
4913 }
4914 #ifdef ASSERT
4915 } else if(use->is_Mem()) {
4916 assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
4917 } else if (use->is_MergeMem()) {
4918 assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4919 } else if (use->Opcode() == Op_EncodeISOArray) {
4920 if (use->in(MemNode::Memory) == n || use->in(3) == n) {
4921 // EncodeISOArray overwrites destination array
4922 memnode_worklist.push(use);
4923 }
4924 } else {
4925 uint op = use->Opcode();
4926 if ((use->in(MemNode::Memory) == n) &&
4927 (op == Op_StrCompressedCopy || op == Op_StrInflatedCopy)) {
4928 // They overwrite memory edge corresponding to destination array,
4929 memnode_worklist.push(use);
4930 } else if (!(BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use) ||
4931 op == Op_AryEq || op == Op_StrComp || op == Op_CountPositives ||
4932 op == Op_StrCompressedCopy || op == Op_StrInflatedCopy || op == Op_VectorizedHashCode ||
4933 op == Op_StrEquals || op == Op_StrIndexOf || op == Op_StrIndexOfChar)) {
4934 n->dump();
4935 use->dump();
4936 assert(false, "EA: missing memory path");
4937 }
4938 #endif
4939 }
4940 }
4941 }
4942
4943 // Phase 3: Process MergeMem nodes from mergemem_worklist.
4944 // Walk each memory slice moving the first node encountered of each
4945 // instance type to the input corresponding to its alias index.
4946 uint length = mergemem_worklist.length();
4947 for( uint next = 0; next < length; ++next ) {
4948 MergeMemNode* nmm = mergemem_worklist.at(next);
4949 assert(!visited.test_set(nmm->_idx), "should not be visited before");
4950 // Note: we don't want to use MergeMemStream here because we only want to
4951 // scan inputs which exist at the start, not ones we add during processing.
4952 // Note 2: MergeMem may already contains instance memory slices added
4953 // during find_inst_mem() call when memory nodes were processed above.
4954 igvn->hash_delete(nmm);
4955 uint nslices = MIN2(nmm->req(), new_index_start);
4956 for (uint i = Compile::AliasIdxRaw+1; i < nslices; i++) {
4957 Node* mem = nmm->in(i);
4958 Node* cur = nullptr;
4959 if (mem == nullptr || mem->is_top()) {
4960 continue;
4961 }
4962 // First, update mergemem by moving memory nodes to corresponding slices
4963 // if their type became more precise since this mergemem was created.
4964 while (mem->is_Mem()) {
4965 const Type* at = igvn->type(mem->in(MemNode::Address));
4966 if (at != Type::TOP) {
4967 assert (at->isa_ptr() != nullptr, "pointer type required.");
4968 uint idx = (uint)_compile->get_alias_index(at->is_ptr());
4969 if (idx == i) {
4970 if (cur == nullptr) {
4971 cur = mem;
4972 }
4973 } else {
4974 if (idx >= nmm->req() || nmm->is_empty_memory(nmm->in(idx))) {
4975 nmm->set_memory_at(idx, mem);
4976 }
4977 }
4978 }
4979 mem = mem->in(MemNode::Memory);
4980 }
4981 nmm->set_memory_at(i, (cur != nullptr) ? cur : mem);
4982 // Find any instance of the current type if we haven't encountered
4983 // already a memory slice of the instance along the memory chain.
4984 for (uint ni = new_index_start; ni < new_index_end; ni++) {
4985 if((uint)_compile->get_general_index(ni) == i) {
4986 Node *m = (ni >= nmm->req()) ? nmm->empty_memory() : nmm->in(ni);
4987 if (nmm->is_empty_memory(m)) {
4988 Node* result = find_inst_mem(mem, ni, orig_phis);
4989 if (_compile->failing()) {
4990 return;
4991 }
4992 nmm->set_memory_at(ni, result);
4993 }
4994 }
4995 }
4996 }
4997 // Find the rest of instances values
4998 for (uint ni = new_index_start; ni < new_index_end; ni++) {
4999 const TypeOopPtr *tinst = _compile->get_adr_type(ni)->isa_oopptr();
5000 Node* result = step_through_mergemem(nmm, ni, tinst);
5001 if (result == nmm->base_memory()) {
5002 // Didn't find instance memory, search through general slice recursively.
5003 result = nmm->memory_at(_compile->get_general_index(ni));
5004 result = find_inst_mem(result, ni, orig_phis);
5005 if (_compile->failing()) {
5006 return;
5007 }
5008 nmm->set_memory_at(ni, result);
5009 }
5010 }
5011
5012 // If we have crossed the 3/4 point of max node limit it's too risky
5013 // to continue with EA/SR because we might hit the max node limit.
5014 if (_compile->live_nodes() >= _compile->max_node_limit() * 0.75) {
5015 if (_compile->do_reduce_allocation_merges()) {
5016 _compile->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
5017 } else if (_invocation > 0) {
5018 _compile->record_failure(C2Compiler::retry_no_iterative_escape_analysis());
5019 } else {
5020 _compile->record_failure(C2Compiler::retry_no_escape_analysis());
5021 }
5022 return;
5023 }
5024
5025 igvn->hash_insert(nmm);
5026 record_for_optimizer(nmm);
5027 }
5028
5029 _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES_3, 5);
5030
5031 // Phase 4: Update the inputs of non-instance memory Phis and
5032 // the Memory input of memnodes
5033 // First update the inputs of any non-instance Phi's from
5034 // which we split out an instance Phi. Note we don't have
5035 // to recursively process Phi's encountered on the input memory
5036 // chains as is done in split_memory_phi() since they will
5037 // also be processed here.
5038 for (uint j = 0; j < orig_phis.size(); j++) {
5039 PhiNode* phi = orig_phis.at(j)->as_Phi();
5040 int alias_idx = _compile->get_alias_index(phi->adr_type());
5041 igvn->hash_delete(phi);
5042 for (uint i = 1; i < phi->req(); i++) {
5043 Node *mem = phi->in(i);
5044 Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis);
5045 if (_compile->failing()) {
5046 return;
5047 }
5048 if (mem != new_mem) {
5049 phi->set_req(i, new_mem);
5050 }
5051 }
5052 igvn->hash_insert(phi);
5053 record_for_optimizer(phi);
5054 }
5055
5056 // Update the memory inputs of MemNodes with the value we computed
5057 // in Phase 2 and move stores memory users to corresponding memory slices.
5058 // Disable memory split verification code until the fix for 6984348.
5059 // Currently it produces false negative results since it does not cover all cases.
5060 #if 0 // ifdef ASSERT
5061 visited.Reset();
5062 Node_Stack old_mems(arena, _compile->unique() >> 2);
5063 #endif
5064 for (uint i = 0; i < ideal_nodes.size(); i++) {
5065 Node* n = ideal_nodes.at(i);
5066 Node* nmem = get_map(n->_idx);
5067 assert(nmem != nullptr, "sanity");
5068 if (n->is_Mem()) {
5069 #if 0 // ifdef ASSERT
5070 Node* old_mem = n->in(MemNode::Memory);
5071 if (!visited.test_set(old_mem->_idx)) {
5072 old_mems.push(old_mem, old_mem->outcnt());
5073 }
5074 #endif
5075 assert(n->in(MemNode::Memory) != nmem, "sanity");
5076 if (!n->is_Load()) {
5077 // Move memory users of a store first.
5078 move_inst_mem(n, orig_phis);
5079 }
5080 // Now update memory input
5081 igvn->hash_delete(n);
5082 n->set_req(MemNode::Memory, nmem);
5083 igvn->hash_insert(n);
5084 record_for_optimizer(n);
5085 } else {
5086 assert(n->is_Allocate() || n->is_CheckCastPP() ||
5087 n->is_AddP() || n->is_Phi() || n->is_NarrowMemProj(), "unknown node used for set_map()");
5088 }
5089 }
5090 #if 0 // ifdef ASSERT
5091 // Verify that memory was split correctly
5092 while (old_mems.is_nonempty()) {
5093 Node* old_mem = old_mems.node();
5094 uint old_cnt = old_mems.index();
5095 old_mems.pop();
5096 assert(old_cnt == old_mem->outcnt(), "old mem could be lost");
5097 }
5098 #endif
5099 _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES_4, 5);
5100 }
5101
5102 #ifndef PRODUCT
5103 int ConnectionGraph::_no_escape_counter = 0;
5104 int ConnectionGraph::_arg_escape_counter = 0;
5105 int ConnectionGraph::_global_escape_counter = 0;
5106
5107 static const char *node_type_names[] = {
5108 "UnknownType",
5109 "JavaObject",
5110 "LocalVar",
5111 "Field",
5112 "Arraycopy"
5113 };
5114
5115 static const char *esc_names[] = {
5116 "UnknownEscape",
5117 "NoEscape",
5118 "ArgEscape",
5119 "GlobalEscape"
5120 };
5121
5122 const char* PointsToNode::esc_name() const {
5123 return esc_names[(int)escape_state()];
5124 }
5125
5126 void PointsToNode::dump_header(bool print_state, outputStream* out) const {
5127 NodeType nt = node_type();
5128 out->print("%s(%d) ", node_type_names[(int) nt], _pidx);
5129 if (print_state) {
5130 EscapeState es = escape_state();
5131 EscapeState fields_es = fields_escape_state();
5132 out->print("%s(%s) ", esc_names[(int)es], esc_names[(int)fields_es]);
5133 if (nt == PointsToNode::JavaObject && !this->scalar_replaceable()) {
5134 out->print("NSR ");
5135 }
5136 }
5137 }
5138
5139 void PointsToNode::dump(bool print_state, outputStream* out, bool newline) const {
5140 dump_header(print_state, out);
5141 if (is_Field()) {
5142 FieldNode* f = (FieldNode*)this;
5143 if (f->is_oop()) {
5144 out->print("oop ");
5145 }
5146 if (f->offset() > 0) {
5147 out->print("+%d ", f->offset());
5148 }
5149 out->print("(");
5150 for (BaseIterator i(f); i.has_next(); i.next()) {
5151 PointsToNode* b = i.get();
5152 out->print(" %d%s", b->idx(),(b->is_JavaObject() ? "P" : ""));
5153 }
5154 out->print(" )");
5155 }
5156 out->print("[");
5157 for (EdgeIterator i(this); i.has_next(); i.next()) {
5158 PointsToNode* e = i.get();
5159 out->print(" %d%s%s", e->idx(),(e->is_JavaObject() ? "P" : (e->is_Field() ? "F" : "")), e->is_Arraycopy() ? "cp" : "");
5160 }
5161 out->print(" [");
5162 for (UseIterator i(this); i.has_next(); i.next()) {
5163 PointsToNode* u = i.get();
5164 bool is_base = false;
5165 if (PointsToNode::is_base_use(u)) {
5166 is_base = true;
5167 u = PointsToNode::get_use_node(u)->as_Field();
5168 }
5169 out->print(" %d%s%s", u->idx(), is_base ? "b" : "", u->is_Arraycopy() ? "cp" : "");
5170 }
5171 out->print(" ]] ");
5172 if (_node == nullptr) {
5173 out->print("<null>%s", newline ? "\n" : "");
5174 } else {
5175 _node->dump(newline ? "\n" : "", false, out);
5176 }
5177 }
5178
5179 void ConnectionGraph::dump(GrowableArray<PointsToNode*>& ptnodes_worklist) {
5180 bool first = true;
5181 int ptnodes_length = ptnodes_worklist.length();
5182 for (int i = 0; i < ptnodes_length; i++) {
5183 PointsToNode *ptn = ptnodes_worklist.at(i);
5184 if (ptn == nullptr || !ptn->is_JavaObject()) {
5185 continue;
5186 }
5187 PointsToNode::EscapeState es = ptn->escape_state();
5188 if ((es != PointsToNode::NoEscape) && !Verbose) {
5189 continue;
5190 }
5191 Node* n = ptn->ideal_node();
5192 if (n->is_Allocate() || (n->is_CallStaticJava() &&
5193 n->as_CallStaticJava()->is_boxing_method())) {
5194 if (first) {
5195 tty->cr();
5196 tty->print("======== Connection graph for ");
5197 _compile->method()->print_short_name();
5198 tty->cr();
5199 tty->print_cr("invocation #%d: %d iterations and %f sec to build connection graph with %d nodes and worklist size %d",
5200 _invocation, _build_iterations, _build_time, nodes_size(), ptnodes_worklist.length());
5201 tty->cr();
5202 first = false;
5203 }
5204 ptn->dump();
5205 // Print all locals and fields which reference this allocation
5206 for (UseIterator j(ptn); j.has_next(); j.next()) {
5207 PointsToNode* use = j.get();
5208 if (use->is_LocalVar()) {
5209 use->dump(Verbose);
5210 } else if (Verbose) {
5211 use->dump();
5212 }
5213 }
5214 tty->cr();
5215 }
5216 }
5217 }
5218
5219 void ConnectionGraph::print_statistics() {
5220 tty->print_cr("No escape = %d, Arg escape = %d, Global escape = %d", AtomicAccess::load(&_no_escape_counter), AtomicAccess::load(&_arg_escape_counter), AtomicAccess::load(&_global_escape_counter));
5221 }
5222
5223 void ConnectionGraph::escape_state_statistics(GrowableArray<JavaObjectNode*>& java_objects_worklist) {
5224 if (!PrintOptoStatistics || (_invocation > 0)) { // Collect data only for the first invocation
5225 return;
5226 }
5227 for (int next = 0; next < java_objects_worklist.length(); ++next) {
5228 JavaObjectNode* ptn = java_objects_worklist.at(next);
5229 if (ptn->ideal_node()->is_Allocate()) {
5230 if (ptn->escape_state() == PointsToNode::NoEscape) {
5231 AtomicAccess::inc(&ConnectionGraph::_no_escape_counter);
5232 } else if (ptn->escape_state() == PointsToNode::ArgEscape) {
5233 AtomicAccess::inc(&ConnectionGraph::_arg_escape_counter);
5234 } else if (ptn->escape_state() == PointsToNode::GlobalEscape) {
5235 AtomicAccess::inc(&ConnectionGraph::_global_escape_counter);
5236 } else {
5237 assert(false, "Unexpected Escape State");
5238 }
5239 }
5240 }
5241 }
5242
5243 void ConnectionGraph::trace_es_update_helper(PointsToNode* ptn, PointsToNode::EscapeState es, bool fields, const char* reason) const {
5244 if (_compile->directive()->TraceEscapeAnalysisOption) {
5245 assert(ptn != nullptr, "should not be null");
5246 assert(reason != nullptr, "should not be null");
5247 ptn->dump_header(true);
5248 PointsToNode::EscapeState new_es = fields ? ptn->escape_state() : es;
5249 PointsToNode::EscapeState new_fields_es = fields ? es : ptn->fields_escape_state();
5250 tty->print_cr("-> %s(%s) %s", esc_names[(int)new_es], esc_names[(int)new_fields_es], reason);
5251 }
5252 }
5253
5254 const char* ConnectionGraph::trace_propagate_message(PointsToNode* from) const {
5255 if (_compile->directive()->TraceEscapeAnalysisOption) {
5256 stringStream ss;
5257 ss.print("propagated from: ");
5258 from->dump(true, &ss, false);
5259 return ss.as_string();
5260 } else {
5261 return nullptr;
5262 }
5263 }
5264
5265 const char* ConnectionGraph::trace_arg_escape_message(CallNode* call) const {
5266 if (_compile->directive()->TraceEscapeAnalysisOption) {
5267 stringStream ss;
5268 ss.print("escapes as arg to:");
5269 call->dump("", false, &ss);
5270 return ss.as_string();
5271 } else {
5272 return nullptr;
5273 }
5274 }
5275
5276 const char* ConnectionGraph::trace_merged_message(PointsToNode* other) const {
5277 if (_compile->directive()->TraceEscapeAnalysisOption) {
5278 stringStream ss;
5279 ss.print("is merged with other object: ");
5280 other->dump_header(true, &ss);
5281 return ss.as_string();
5282 } else {
5283 return nullptr;
5284 }
5285 }
5286
5287 #endif
5288
5289 void ConnectionGraph::record_for_optimizer(Node *n) {
5290 _igvn->_worklist.push(n);
5291 _igvn->add_users_to_worklist(n);
5292 }
--- EOF ---