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