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