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