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