1 /*
   2  * Copyright (c) 2005, 2022, 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 "precompiled.hpp"
  26 #include "ci/bcEscapeAnalyzer.hpp"
  27 #include "compiler/compileLog.hpp"
  28 #include "gc/shared/barrierSet.hpp"
  29 #include "gc/shared/c2/barrierSetC2.hpp"
  30 #include "libadt/vectset.hpp"
  31 #include "memory/allocation.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "opto/c2compiler.hpp"
  34 #include "opto/arraycopynode.hpp"
  35 #include "opto/callnode.hpp"
  36 #include "opto/cfgnode.hpp"
  37 #include "opto/compile.hpp"
  38 #include "opto/escape.hpp"
  39 #include "opto/phaseX.hpp"
  40 #include "opto/movenode.hpp"
  41 #include "opto/rootnode.hpp"
  42 #include "utilities/macros.hpp"
  43 
  44 ConnectionGraph::ConnectionGraph(Compile * C, PhaseIterGVN *igvn, int invocation) :
  45   _nodes(C->comp_arena(), C->unique(), C->unique(), NULL),
  46   _in_worklist(C->comp_arena()),
  47   _next_pidx(0),
  48   _collecting(true),
  49   _verify(false),
  50   _compile(C),
  51   _igvn(igvn),
  52   _invocation(invocation),
  53   _build_iterations(0),
  54   _build_time(0.),
  55   _node_map(C->comp_arena()) {
  56   // Add unknown java object.
  57   add_java_object(C->top(), PointsToNode::GlobalEscape);
  58   phantom_obj = ptnode_adr(C->top()->_idx)->as_JavaObject();
  59   // Add ConP(#NULL) and ConN(#NULL) nodes.
  60   Node* oop_null = igvn->zerocon(T_OBJECT);
  61   assert(oop_null->_idx < nodes_size(), "should be created already");
  62   add_java_object(oop_null, PointsToNode::NoEscape);
  63   null_obj = ptnode_adr(oop_null->_idx)->as_JavaObject();
  64   if (UseCompressedOops) {
  65     Node* noop_null = igvn->zerocon(T_NARROWOOP);
  66     assert(noop_null->_idx < nodes_size(), "should be created already");
  67     map_ideal_node(noop_null, null_obj);
  68   }
  69 }
  70 
  71 bool ConnectionGraph::has_candidates(Compile *C) {
  72   // EA brings benefits only when the code has allocations and/or locks which
  73   // are represented by ideal Macro nodes.
  74   int cnt = C->macro_count();
  75   for (int i = 0; i < cnt; i++) {
  76     Node *n = C->macro_node(i);
  77     if (n->is_Allocate()) {
  78       return true;
  79     }
  80     if (n->is_Lock()) {
  81       Node* obj = n->as_Lock()->obj_node()->uncast();
  82       if (!(obj->is_Parm() || obj->is_Con())) {
  83         return true;
  84       }
  85     }
  86     if (n->is_CallStaticJava() &&
  87         n->as_CallStaticJava()->is_boxing_method()) {
  88       return true;
  89     }
  90   }
  91   return false;
  92 }
  93 
  94 void ConnectionGraph::do_analysis(Compile *C, PhaseIterGVN *igvn) {
  95   Compile::TracePhase tp("escapeAnalysis", &Phase::timers[Phase::_t_escapeAnalysis]);
  96   ResourceMark rm;
  97 
  98   // Add ConP#NULL and ConN#NULL nodes before ConnectionGraph construction
  99   // to create space for them in ConnectionGraph::_nodes[].
 100   Node* oop_null = igvn->zerocon(T_OBJECT);
 101   Node* noop_null = igvn->zerocon(T_NARROWOOP);
 102   int invocation = 0;
 103   if (C->congraph() != NULL) {
 104     invocation = C->congraph()->_invocation + 1;
 105   }
 106   ConnectionGraph* congraph = new(C->comp_arena()) ConnectionGraph(C, igvn, invocation);
 107   // Perform escape analysis
 108   if (congraph->compute_escape()) {
 109     // There are non escaping objects.
 110     C->set_congraph(congraph);
 111   }
 112   // Cleanup.
 113   if (oop_null->outcnt() == 0) {
 114     igvn->hash_delete(oop_null);
 115   }
 116   if (noop_null->outcnt() == 0) {
 117     igvn->hash_delete(noop_null);
 118   }
 119 }
 120 
 121 bool ConnectionGraph::compute_escape() {
 122   Compile* C = _compile;
 123   PhaseGVN* igvn = _igvn;
 124 
 125   // Worklists used by EA.
 126   Unique_Node_List delayed_worklist;
 127   GrowableArray<Node*> alloc_worklist;
 128   GrowableArray<Node*> ptr_cmp_worklist;
 129   GrowableArray<MemBarStoreStoreNode*> storestore_worklist;
 130   GrowableArray<ArrayCopyNode*>  arraycopy_worklist;
 131   GrowableArray<PointsToNode*>   ptnodes_worklist;
 132   GrowableArray<JavaObjectNode*> java_objects_worklist;
 133   GrowableArray<JavaObjectNode*> non_escaped_allocs_worklist;
 134   GrowableArray<FieldNode*>      oop_fields_worklist;
 135   GrowableArray<SafePointNode*>  sfn_worklist;
 136   GrowableArray<MergeMemNode*>   mergemem_worklist;
 137   DEBUG_ONLY( GrowableArray<Node*> addp_worklist; )
 138 
 139   { Compile::TracePhase tp("connectionGraph", &Phase::timers[Phase::_t_connectionGraph]);
 140 
 141   // 1. Populate Connection Graph (CG) with PointsTo nodes.
 142   ideal_nodes.map(C->live_nodes(), NULL);  // preallocate space
 143   // Initialize worklist
 144   if (C->root() != NULL) {
 145     ideal_nodes.push(C->root());
 146   }
 147   // Processed ideal nodes are unique on ideal_nodes list
 148   // but several ideal nodes are mapped to the phantom_obj.
 149   // To avoid duplicated entries on the following worklists
 150   // add the phantom_obj only once to them.
 151   ptnodes_worklist.append(phantom_obj);
 152   java_objects_worklist.append(phantom_obj);
 153   for( uint next = 0; next < ideal_nodes.size(); ++next ) {
 154     Node* n = ideal_nodes.at(next);
 155     // Create PointsTo nodes and add them to Connection Graph. Called
 156     // only once per ideal node since ideal_nodes is Unique_Node list.
 157     add_node_to_connection_graph(n, &delayed_worklist);
 158     PointsToNode* ptn = ptnode_adr(n->_idx);
 159     if (ptn != NULL && ptn != phantom_obj) {
 160       ptnodes_worklist.append(ptn);
 161       if (ptn->is_JavaObject()) {
 162         java_objects_worklist.append(ptn->as_JavaObject());
 163         if ((n->is_Allocate() || n->is_CallStaticJava()) &&
 164             (ptn->escape_state() < PointsToNode::GlobalEscape)) {
 165           // Only allocations and java static calls results are interesting.
 166           non_escaped_allocs_worklist.append(ptn->as_JavaObject());
 167         }
 168       } else if (ptn->is_Field() && ptn->as_Field()->is_oop()) {
 169         oop_fields_worklist.append(ptn->as_Field());
 170       }
 171     }
 172     // Collect some interesting nodes for further use.
 173     switch (n->Opcode()) {
 174       case Op_MergeMem:
 175         // Collect all MergeMem nodes to add memory slices for
 176         // scalar replaceable objects in split_unique_types().
 177         mergemem_worklist.append(n->as_MergeMem());
 178         break;
 179       case Op_CmpP:
 180       case Op_CmpN:
 181         // Collect compare pointers nodes.
 182         if (OptimizePtrCompare) {
 183           ptr_cmp_worklist.append(n);
 184         }
 185         break;
 186       case Op_MemBarStoreStore:
 187         // Collect all MemBarStoreStore nodes so that depending on the
 188         // escape status of the associated Allocate node some of them
 189         // may be eliminated.
 190         storestore_worklist.append(n->as_MemBarStoreStore());
 191         break;
 192       case Op_MemBarRelease:
 193         if (n->req() > MemBarNode::Precedent) {
 194           record_for_optimizer(n);
 195         }
 196         break;
 197 #ifdef ASSERT
 198       case Op_AddP:
 199         // Collect address nodes for graph verification.
 200         addp_worklist.append(n);
 201         break;
 202 #endif
 203       case Op_ArrayCopy:
 204         // Keep a list of ArrayCopy nodes so if one of its input is non
 205         // escaping, we can record a unique type
 206         arraycopy_worklist.append(n->as_ArrayCopy());
 207         break;
 208       default:
 209         // not interested now, ignore...
 210         break;
 211     }
 212     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 213       Node* m = n->fast_out(i);   // Get user
 214       ideal_nodes.push(m);
 215     }
 216     if (n->is_SafePoint()) {
 217       sfn_worklist.append(n->as_SafePoint());
 218     }
 219   }
 220 
 221 #ifndef PRODUCT
 222   if (_compile->directive()->TraceEscapeAnalysisOption) {
 223     tty->print("+++++ Initial worklist for ");
 224     _compile->method()->print_name();
 225     tty->print_cr(" (ea_inv=%d)", _invocation);
 226     for (int i = 0; i < ptnodes_worklist.length(); i++) {
 227       PointsToNode* ptn = ptnodes_worklist.at(i);
 228       ptn->dump();
 229     }
 230     tty->print_cr("+++++ Calculating escape states and scalar replaceability");
 231   }
 232 #endif
 233 
 234   if (non_escaped_allocs_worklist.length() == 0) {
 235     _collecting = false;
 236     NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
 237     return false; // Nothing to do.
 238   }
 239   // Add final simple edges to graph.
 240   while(delayed_worklist.size() > 0) {
 241     Node* n = delayed_worklist.pop();
 242     add_final_edges(n);
 243   }
 244 
 245 #ifdef ASSERT
 246   if (VerifyConnectionGraph) {
 247     // Verify that no new simple edges could be created and all
 248     // local vars has edges.
 249     _verify = true;
 250     int ptnodes_length = ptnodes_worklist.length();
 251     for (int next = 0; next < ptnodes_length; ++next) {
 252       PointsToNode* ptn = ptnodes_worklist.at(next);
 253       add_final_edges(ptn->ideal_node());
 254       if (ptn->is_LocalVar() && ptn->edge_count() == 0) {
 255         ptn->dump();
 256         assert(ptn->as_LocalVar()->edge_count() > 0, "sanity");
 257       }
 258     }
 259     _verify = false;
 260   }
 261 #endif
 262   // Bytecode analyzer BCEscapeAnalyzer, used for Call nodes
 263   // processing, calls to CI to resolve symbols (types, fields, methods)
 264   // referenced in bytecode. During symbol resolution VM may throw
 265   // an exception which CI cleans and converts to compilation failure.
 266   if (C->failing()) {
 267     NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
 268     return false;
 269   }
 270 
 271   // 2. Finish Graph construction by propagating references to all
 272   //    java objects through graph.
 273   if (!complete_connection_graph(ptnodes_worklist, non_escaped_allocs_worklist,
 274                                  java_objects_worklist, oop_fields_worklist)) {
 275     // All objects escaped or hit time or iterations limits.
 276     _collecting = false;
 277     NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
 278     return false;
 279   }
 280 
 281   // 3. Adjust scalar_replaceable state of nonescaping objects and push
 282   //    scalar replaceable allocations on alloc_worklist for processing
 283   //    in split_unique_types().
 284   int non_escaped_length = non_escaped_allocs_worklist.length();
 285   for (int next = 0; next < non_escaped_length; next++) {
 286     JavaObjectNode* ptn = non_escaped_allocs_worklist.at(next);
 287     bool noescape = (ptn->escape_state() == PointsToNode::NoEscape);
 288     Node* n = ptn->ideal_node();
 289     if (n->is_Allocate()) {
 290       n->as_Allocate()->_is_non_escaping = noescape;
 291     }
 292     if (noescape && ptn->scalar_replaceable()) {
 293       adjust_scalar_replaceable_state(ptn);
 294       if (ptn->scalar_replaceable()) {
 295         alloc_worklist.append(ptn->ideal_node());
 296       }
 297     }
 298   }
 299 
 300 #ifdef ASSERT
 301   if (VerifyConnectionGraph) {
 302     // Verify that graph is complete - no new edges could be added or needed.
 303     verify_connection_graph(ptnodes_worklist, non_escaped_allocs_worklist,
 304                             java_objects_worklist, addp_worklist);
 305   }
 306   assert(C->unique() == nodes_size(), "no new ideal nodes should be added during ConnectionGraph build");
 307   assert(null_obj->escape_state() == PointsToNode::NoEscape &&
 308          null_obj->edge_count() == 0 &&
 309          !null_obj->arraycopy_src() &&
 310          !null_obj->arraycopy_dst(), "sanity");
 311 #endif
 312 
 313   _collecting = false;
 314 
 315   } // TracePhase t3("connectionGraph")
 316 
 317   // 4. Optimize ideal graph based on EA information.
 318   bool has_non_escaping_obj = (non_escaped_allocs_worklist.length() > 0);
 319   if (has_non_escaping_obj) {
 320     optimize_ideal_graph(ptr_cmp_worklist, storestore_worklist);
 321   }
 322 
 323 #ifndef PRODUCT
 324   if (PrintEscapeAnalysis) {
 325     dump(ptnodes_worklist); // Dump ConnectionGraph
 326   }
 327 #endif
 328 
 329 #ifdef ASSERT
 330   if (VerifyConnectionGraph) {
 331     int alloc_length = alloc_worklist.length();
 332     for (int next = 0; next < alloc_length; ++next) {
 333       Node* n = alloc_worklist.at(next);
 334       PointsToNode* ptn = ptnode_adr(n->_idx);
 335       assert(ptn->escape_state() == PointsToNode::NoEscape && ptn->scalar_replaceable(), "sanity");
 336     }
 337   }
 338 #endif
 339 
 340   // 5. Separate memory graph for scalar replaceable allcations.
 341   bool has_scalar_replaceable_candidates = (alloc_worklist.length() > 0);
 342   if (has_scalar_replaceable_candidates &&
 343       C->AliasLevel() >= 3 && EliminateAllocations) {
 344     // Now use the escape information to create unique types for
 345     // scalar replaceable objects.
 346     split_unique_types(alloc_worklist, arraycopy_worklist, mergemem_worklist);
 347     if (C->failing()) {
 348       NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
 349       return false;
 350     }
 351     C->print_method(PHASE_AFTER_EA, 2);
 352 
 353 #ifdef ASSERT
 354   } else if (Verbose && (PrintEscapeAnalysis || PrintEliminateAllocations)) {
 355     tty->print("=== No allocations eliminated for ");
 356     C->method()->print_short_name();
 357     if (!EliminateAllocations) {
 358       tty->print(" since EliminateAllocations is off ===");
 359     } else if(!has_scalar_replaceable_candidates) {
 360       tty->print(" since there are no scalar replaceable candidates ===");
 361     } else if(C->AliasLevel() < 3) {
 362       tty->print(" since AliasLevel < 3 ===");
 363     }
 364     tty->cr();
 365 #endif
 366   }
 367 
 368   // Annotate at safepoints if they have <= ArgEscape objects in their scope and at
 369   // java calls if they pass ArgEscape objects as parameters.
 370   if (has_non_escaping_obj &&
 371       (C->env()->should_retain_local_variables() ||
 372        C->env()->jvmti_can_get_owned_monitor_info() ||
 373        C->env()->jvmti_can_walk_any_space() ||
 374        DeoptimizeObjectsALot)) {
 375     int sfn_length = sfn_worklist.length();
 376     for (int next = 0; next < sfn_length; next++) {
 377       SafePointNode* sfn = sfn_worklist.at(next);
 378       sfn->set_has_ea_local_in_scope(has_ea_local_in_scope(sfn));
 379       if (sfn->is_CallJava()) {
 380         CallJavaNode* call = sfn->as_CallJava();
 381         call->set_arg_escape(has_arg_escape(call));
 382       }
 383     }
 384   }
 385 
 386   NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
 387   return has_non_escaping_obj;
 388 }
 389 
 390 // Returns true if there is an object in the scope of sfn that does not escape globally.
 391 bool ConnectionGraph::has_ea_local_in_scope(SafePointNode* sfn) {
 392   Compile* C = _compile;
 393   for (JVMState* jvms = sfn->jvms(); jvms != NULL; jvms = jvms->caller()) {
 394     if (C->env()->should_retain_local_variables() || C->env()->jvmti_can_walk_any_space() ||
 395         DeoptimizeObjectsALot) {
 396       // Jvmti agents can access locals. Must provide info about local objects at runtime.
 397       int num_locs = jvms->loc_size();
 398       for (int idx = 0; idx < num_locs; idx++) {
 399         Node* l = sfn->local(jvms, idx);
 400         if (not_global_escape(l)) {
 401           return true;
 402         }
 403       }
 404     }
 405     if (C->env()->jvmti_can_get_owned_monitor_info() ||
 406         C->env()->jvmti_can_walk_any_space() || DeoptimizeObjectsALot) {
 407       // Jvmti agents can read monitors. Must provide info about locked objects at runtime.
 408       int num_mon = jvms->nof_monitors();
 409       for (int idx = 0; idx < num_mon; idx++) {
 410         Node* m = sfn->monitor_obj(jvms, idx);
 411         if (m != NULL && not_global_escape(m)) {
 412           return true;
 413         }
 414       }
 415     }
 416   }
 417   return false;
 418 }
 419 
 420 // Returns true if at least one of the arguments to the call is an object
 421 // that does not escape globally.
 422 bool ConnectionGraph::has_arg_escape(CallJavaNode* call) {
 423   if (call->method() != NULL) {
 424     uint max_idx = TypeFunc::Parms + call->method()->arg_size();
 425     for (uint idx = TypeFunc::Parms; idx < max_idx; idx++) {
 426       Node* p = call->in(idx);
 427       if (not_global_escape(p)) {
 428         return true;
 429       }
 430     }
 431   } else {
 432     const char* name = call->as_CallStaticJava()->_name;
 433     assert(name != NULL, "no name");
 434     // no arg escapes through uncommon traps
 435     if (strcmp(name, "uncommon_trap") != 0) {
 436       // process_call_arguments() assumes that all arguments escape globally
 437       const TypeTuple* d = call->tf()->domain();
 438       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
 439         const Type* at = d->field_at(i);
 440         if (at->isa_oopptr() != NULL) {
 441           return true;
 442         }
 443       }
 444     }
 445   }
 446   return false;
 447 }
 448 
 449 
 450 
 451 // Utility function for nodes that load an object
 452 void ConnectionGraph::add_objload_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
 453   // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
 454   // ThreadLocal has RawPtr type.
 455   const Type* t = _igvn->type(n);
 456   if (t->make_ptr() != NULL) {
 457     Node* adr = n->in(MemNode::Address);
 458 #ifdef ASSERT
 459     if (!adr->is_AddP()) {
 460       assert(_igvn->type(adr)->isa_rawptr(), "sanity");
 461     } else {
 462       assert((ptnode_adr(adr->_idx) == NULL ||
 463               ptnode_adr(adr->_idx)->as_Field()->is_oop()), "sanity");
 464     }
 465 #endif
 466     add_local_var_and_edge(n, PointsToNode::NoEscape,
 467                            adr, delayed_worklist);
 468   }
 469 }
 470 
 471 // Populate Connection Graph with PointsTo nodes and create simple
 472 // connection graph edges.
 473 void ConnectionGraph::add_node_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
 474   assert(!_verify, "this method should not be called for verification");
 475   PhaseGVN* igvn = _igvn;
 476   uint n_idx = n->_idx;
 477   PointsToNode* n_ptn = ptnode_adr(n_idx);
 478   if (n_ptn != NULL) {
 479     return; // No need to redefine PointsTo node during first iteration.
 480   }
 481   int opcode = n->Opcode();
 482   bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->escape_add_to_con_graph(this, igvn, delayed_worklist, n, opcode);
 483   if (gc_handled) {
 484     return; // Ignore node if already handled by GC.
 485   }
 486 
 487   if (n->is_Call()) {
 488     // Arguments to allocation and locking don't escape.
 489     if (n->is_AbstractLock()) {
 490       // Put Lock and Unlock nodes on IGVN worklist to process them during
 491       // first IGVN optimization when escape information is still available.
 492       record_for_optimizer(n);
 493     } else if (n->is_Allocate()) {
 494       add_call_node(n->as_Call());
 495       record_for_optimizer(n);
 496     } else {
 497       if (n->is_CallStaticJava()) {
 498         const char* name = n->as_CallStaticJava()->_name;
 499         if (name != NULL && strcmp(name, "uncommon_trap") == 0) {
 500           return; // Skip uncommon traps
 501         }
 502       }
 503       // Don't mark as processed since call's arguments have to be processed.
 504       delayed_worklist->push(n);
 505       // Check if a call returns an object.
 506       if ((n->as_Call()->returns_pointer() &&
 507            n->as_Call()->proj_out_or_null(TypeFunc::Parms) != NULL) ||
 508           (n->is_CallStaticJava() &&
 509            n->as_CallStaticJava()->is_boxing_method())) {
 510         add_call_node(n->as_Call());
 511       }
 512     }
 513     return;
 514   }
 515   // Put this check here to process call arguments since some call nodes
 516   // point to phantom_obj.
 517   if (n_ptn == phantom_obj || n_ptn == null_obj) {
 518     return; // Skip predefined nodes.
 519   }
 520   switch (opcode) {
 521     case Op_AddP: {
 522       Node* base = get_addp_base(n);
 523       PointsToNode* ptn_base = ptnode_adr(base->_idx);
 524       // Field nodes are created for all field types. They are used in
 525       // adjust_scalar_replaceable_state() and split_unique_types().
 526       // Note, non-oop fields will have only base edges in Connection
 527       // Graph because such fields are not used for oop loads and stores.
 528       int offset = address_offset(n, igvn);
 529       add_field(n, PointsToNode::NoEscape, offset);
 530       if (ptn_base == NULL) {
 531         delayed_worklist->push(n); // Process it later.
 532       } else {
 533         n_ptn = ptnode_adr(n_idx);
 534         add_base(n_ptn->as_Field(), ptn_base);
 535       }
 536       break;
 537     }
 538     case Op_CastX2P: {
 539       map_ideal_node(n, phantom_obj);
 540       break;
 541     }
 542     case Op_CastPP:
 543     case Op_CheckCastPP:
 544     case Op_EncodeP:
 545     case Op_DecodeN:
 546     case Op_EncodePKlass:
 547     case Op_DecodeNKlass: {
 548       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), delayed_worklist);
 549       break;
 550     }
 551     case Op_CMoveP: {
 552       add_local_var(n, PointsToNode::NoEscape);
 553       // Do not add edges during first iteration because some could be
 554       // not defined yet.
 555       delayed_worklist->push(n);
 556       break;
 557     }
 558     case Op_ConP:
 559     case Op_ConN:
 560     case Op_ConNKlass: {
 561       // assume all oop constants globally escape except for null
 562       PointsToNode::EscapeState es;
 563       const Type* t = igvn->type(n);
 564       if (t == TypePtr::NULL_PTR || t == TypeNarrowOop::NULL_PTR) {
 565         es = PointsToNode::NoEscape;
 566       } else {
 567         es = PointsToNode::GlobalEscape;
 568       }
 569       add_java_object(n, es);
 570       break;
 571     }
 572     case Op_CreateEx: {
 573       // assume that all exception objects globally escape
 574       map_ideal_node(n, phantom_obj);
 575       break;
 576     }
 577     case Op_LoadKlass:
 578     case Op_LoadNKlass: {
 579       // Unknown class is loaded
 580       map_ideal_node(n, phantom_obj);
 581       break;
 582     }
 583     case Op_LoadP:
 584     case Op_LoadN: {
 585       add_objload_to_connection_graph(n, delayed_worklist);
 586       break;
 587     }
 588     case Op_Parm: {
 589       map_ideal_node(n, phantom_obj);
 590       break;
 591     }
 592     case Op_PartialSubtypeCheck: {
 593       // Produces Null or notNull and is used in only in CmpP so
 594       // phantom_obj could be used.
 595       map_ideal_node(n, phantom_obj); // Result is unknown
 596       break;
 597     }
 598     case Op_Phi: {
 599       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
 600       // ThreadLocal has RawPtr type.
 601       const Type* t = n->as_Phi()->type();
 602       if (t->make_ptr() != NULL) {
 603         add_local_var(n, PointsToNode::NoEscape);
 604         // Do not add edges during first iteration because some could be
 605         // not defined yet.
 606         delayed_worklist->push(n);
 607       }
 608       break;
 609     }
 610     case Op_Proj: {
 611       // we are only interested in the oop result projection from a call
 612       if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
 613           n->in(0)->as_Call()->returns_pointer()) {
 614         add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist);
 615       }
 616       break;
 617     }
 618     case Op_Rethrow: // Exception object escapes
 619     case Op_Return: {
 620       if (n->req() > TypeFunc::Parms &&
 621           igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
 622         // Treat Return value as LocalVar with GlobalEscape escape state.
 623         add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), delayed_worklist);
 624       }
 625       break;
 626     }
 627     case Op_CompareAndExchangeP:
 628     case Op_CompareAndExchangeN:
 629     case Op_GetAndSetP:
 630     case Op_GetAndSetN: {
 631       add_objload_to_connection_graph(n, delayed_worklist);
 632       // fall-through
 633     }
 634     case Op_StoreP:
 635     case Op_StoreN:
 636     case Op_StoreNKlass:
 637     case Op_WeakCompareAndSwapP:
 638     case Op_WeakCompareAndSwapN:
 639     case Op_CompareAndSwapP:
 640     case Op_CompareAndSwapN: {
 641       add_to_congraph_unsafe_access(n, opcode, delayed_worklist);
 642       break;
 643     }
 644     case Op_AryEq:
 645     case Op_CountPositives:
 646     case Op_StrComp:
 647     case Op_StrEquals:
 648     case Op_StrIndexOf:
 649     case Op_StrIndexOfChar:
 650     case Op_StrInflatedCopy:
 651     case Op_StrCompressedCopy:
 652     case Op_EncodeISOArray: {
 653       add_local_var(n, PointsToNode::ArgEscape);
 654       delayed_worklist->push(n); // Process it later.
 655       break;
 656     }
 657     case Op_ThreadLocal: {
 658       add_java_object(n, PointsToNode::ArgEscape);
 659       break;
 660     }
 661     case Op_Blackhole: {
 662       // All blackhole pointer arguments are globally escaping.
 663       // Only do this if there is at least one pointer argument.
 664       // Do not add edges during first iteration because some could be
 665       // not defined yet, defer to final step.
 666       for (uint i = 0; i < n->req(); i++) {
 667         Node* in = n->in(i);
 668         if (in != nullptr) {
 669           const Type* at = _igvn->type(in);
 670           if (!at->isa_ptr()) continue;
 671 
 672           add_local_var(n, PointsToNode::GlobalEscape);
 673           delayed_worklist->push(n);
 674           break;
 675         }
 676       }
 677       break;
 678     }
 679     default:
 680       ; // Do nothing for nodes not related to EA.
 681   }
 682   return;
 683 }
 684 
 685 // Add final simple edges to graph.
 686 void ConnectionGraph::add_final_edges(Node *n) {
 687   PointsToNode* n_ptn = ptnode_adr(n->_idx);
 688 #ifdef ASSERT
 689   if (_verify && n_ptn->is_JavaObject())
 690     return; // This method does not change graph for JavaObject.
 691 #endif
 692 
 693   if (n->is_Call()) {
 694     process_call_arguments(n->as_Call());
 695     return;
 696   }
 697   assert(n->is_Store() || n->is_LoadStore() ||
 698          (n_ptn != NULL) && (n_ptn->ideal_node() != NULL),
 699          "node should be registered already");
 700   int opcode = n->Opcode();
 701   bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->escape_add_final_edges(this, _igvn, n, opcode);
 702   if (gc_handled) {
 703     return; // Ignore node if already handled by GC.
 704   }
 705   switch (opcode) {
 706     case Op_AddP: {
 707       Node* base = get_addp_base(n);
 708       PointsToNode* ptn_base = ptnode_adr(base->_idx);
 709       assert(ptn_base != NULL, "field's base should be registered");
 710       add_base(n_ptn->as_Field(), ptn_base);
 711       break;
 712     }
 713     case Op_CastPP:
 714     case Op_CheckCastPP:
 715     case Op_EncodeP:
 716     case Op_DecodeN:
 717     case Op_EncodePKlass:
 718     case Op_DecodeNKlass: {
 719       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), NULL);
 720       break;
 721     }
 722     case Op_CMoveP: {
 723       for (uint i = CMoveNode::IfFalse; i < n->req(); i++) {
 724         Node* in = n->in(i);
 725         if (in == NULL) {
 726           continue;  // ignore NULL
 727         }
 728         Node* uncast_in = in->uncast();
 729         if (uncast_in->is_top() || uncast_in == n) {
 730           continue;  // ignore top or inputs which go back this node
 731         }
 732         PointsToNode* ptn = ptnode_adr(in->_idx);
 733         assert(ptn != NULL, "node should be registered");
 734         add_edge(n_ptn, ptn);
 735       }
 736       break;
 737     }
 738     case Op_LoadP:
 739     case Op_LoadN: {
 740       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
 741       // ThreadLocal has RawPtr type.
 742       assert(_igvn->type(n)->make_ptr() != NULL, "Unexpected node type");
 743       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(MemNode::Address), NULL);
 744       break;
 745     }
 746     case Op_Phi: {
 747       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
 748       // ThreadLocal has RawPtr type.
 749       assert(n->as_Phi()->type()->make_ptr() != NULL, "Unexpected node type");
 750       for (uint i = 1; i < n->req(); i++) {
 751         Node* in = n->in(i);
 752         if (in == NULL) {
 753           continue;  // ignore NULL
 754         }
 755         Node* uncast_in = in->uncast();
 756         if (uncast_in->is_top() || uncast_in == n) {
 757           continue;  // ignore top or inputs which go back this node
 758         }
 759         PointsToNode* ptn = ptnode_adr(in->_idx);
 760         assert(ptn != NULL, "node should be registered");
 761         add_edge(n_ptn, ptn);
 762       }
 763       break;
 764     }
 765     case Op_Proj: {
 766       // we are only interested in the oop result projection from a call
 767       assert(n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
 768              n->in(0)->as_Call()->returns_pointer(), "Unexpected node type");
 769       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), NULL);
 770       break;
 771     }
 772     case Op_Rethrow: // Exception object escapes
 773     case Op_Return: {
 774       assert(n->req() > TypeFunc::Parms && _igvn->type(n->in(TypeFunc::Parms))->isa_oopptr(),
 775              "Unexpected node type");
 776       // Treat Return value as LocalVar with GlobalEscape escape state.
 777       add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), NULL);
 778       break;
 779     }
 780     case Op_CompareAndExchangeP:
 781     case Op_CompareAndExchangeN:
 782     case Op_GetAndSetP:
 783     case Op_GetAndSetN:{
 784       assert(_igvn->type(n)->make_ptr() != NULL, "Unexpected node type");
 785       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(MemNode::Address), NULL);
 786       // fall-through
 787     }
 788     case Op_CompareAndSwapP:
 789     case Op_CompareAndSwapN:
 790     case Op_WeakCompareAndSwapP:
 791     case Op_WeakCompareAndSwapN:
 792     case Op_StoreP:
 793     case Op_StoreN:
 794     case Op_StoreNKlass:{
 795       add_final_edges_unsafe_access(n, opcode);
 796       break;
 797     }
 798     case Op_AryEq:
 799     case Op_CountPositives:
 800     case Op_StrComp:
 801     case Op_StrEquals:
 802     case Op_StrIndexOf:
 803     case Op_StrIndexOfChar:
 804     case Op_StrInflatedCopy:
 805     case Op_StrCompressedCopy:
 806     case Op_EncodeISOArray: {
 807       // char[]/byte[] arrays passed to string intrinsic do not escape but
 808       // they are not scalar replaceable. Adjust escape state for them.
 809       // Start from in(2) edge since in(1) is memory edge.
 810       for (uint i = 2; i < n->req(); i++) {
 811         Node* adr = n->in(i);
 812         const Type* at = _igvn->type(adr);
 813         if (!adr->is_top() && at->isa_ptr()) {
 814           assert(at == Type::TOP || at == TypePtr::NULL_PTR ||
 815                  at->isa_ptr() != NULL, "expecting a pointer");
 816           if (adr->is_AddP()) {
 817             adr = get_addp_base(adr);
 818           }
 819           PointsToNode* ptn = ptnode_adr(adr->_idx);
 820           assert(ptn != NULL, "node should be registered");
 821           add_edge(n_ptn, ptn);
 822         }
 823       }
 824       break;
 825     }
 826     case Op_Blackhole: {
 827       // All blackhole pointer arguments are globally escaping.
 828       for (uint i = 0; i < n->req(); i++) {
 829         Node* in = n->in(i);
 830         if (in != nullptr) {
 831           const Type* at = _igvn->type(in);
 832           if (!at->isa_ptr()) continue;
 833 
 834           if (in->is_AddP()) {
 835             in = get_addp_base(in);
 836           }
 837 
 838           PointsToNode* ptn = ptnode_adr(in->_idx);
 839           assert(ptn != nullptr, "should be defined already");
 840           set_escape_state(ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "blackhole"));
 841           add_edge(n_ptn, ptn);
 842         }
 843       }
 844       break;
 845     }
 846     default: {
 847       // This method should be called only for EA specific nodes which may
 848       // miss some edges when they were created.
 849 #ifdef ASSERT
 850       n->dump(1);
 851 #endif
 852       guarantee(false, "unknown node");
 853     }
 854   }
 855   return;
 856 }
 857 
 858 void ConnectionGraph::add_to_congraph_unsafe_access(Node* n, uint opcode, Unique_Node_List* delayed_worklist) {
 859   Node* adr = n->in(MemNode::Address);
 860   const Type* adr_type = _igvn->type(adr);
 861   adr_type = adr_type->make_ptr();
 862   if (adr_type == NULL) {
 863     return; // skip dead nodes
 864   }
 865   if (adr_type->isa_oopptr()
 866       || ((opcode == Op_StoreP || opcode == Op_StoreN || opcode == Op_StoreNKlass)
 867           && adr_type == TypeRawPtr::NOTNULL
 868           && is_captured_store_address(adr))) {
 869     delayed_worklist->push(n); // Process it later.
 870 #ifdef ASSERT
 871     assert (adr->is_AddP(), "expecting an AddP");
 872     if (adr_type == TypeRawPtr::NOTNULL) {
 873       // Verify a raw address for a store captured by Initialize node.
 874       int offs = (int) _igvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
 875       assert(offs != Type::OffsetBot, "offset must be a constant");
 876     }
 877 #endif
 878   } else {
 879     // Ignore copy the displaced header to the BoxNode (OSR compilation).
 880     if (adr->is_BoxLock()) {
 881       return;
 882     }
 883     // Stored value escapes in unsafe access.
 884     if ((opcode == Op_StoreP) && adr_type->isa_rawptr()) {
 885       delayed_worklist->push(n); // Process unsafe access later.
 886       return;
 887     }
 888 #ifdef ASSERT
 889     n->dump(1);
 890     assert(false, "not unsafe");
 891 #endif
 892   }
 893 }
 894 
 895 bool ConnectionGraph::add_final_edges_unsafe_access(Node* n, uint opcode) {
 896   Node* adr = n->in(MemNode::Address);
 897   const Type *adr_type = _igvn->type(adr);
 898   adr_type = adr_type->make_ptr();
 899 #ifdef ASSERT
 900   if (adr_type == NULL) {
 901     n->dump(1);
 902     assert(adr_type != NULL, "dead node should not be on list");
 903     return true;
 904   }
 905 #endif
 906 
 907   if (adr_type->isa_oopptr()
 908       || ((opcode == Op_StoreP || opcode == Op_StoreN || opcode == Op_StoreNKlass)
 909            && adr_type == TypeRawPtr::NOTNULL
 910            && is_captured_store_address(adr))) {
 911     // Point Address to Value
 912     PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
 913     assert(adr_ptn != NULL &&
 914            adr_ptn->as_Field()->is_oop(), "node should be registered");
 915     Node* val = n->in(MemNode::ValueIn);
 916     PointsToNode* ptn = ptnode_adr(val->_idx);
 917     assert(ptn != NULL, "node should be registered");
 918     add_edge(adr_ptn, ptn);
 919     return true;
 920   } else if ((opcode == Op_StoreP) && adr_type->isa_rawptr()) {
 921     // Stored value escapes in unsafe access.
 922     Node* val = n->in(MemNode::ValueIn);
 923     PointsToNode* ptn = ptnode_adr(val->_idx);
 924     assert(ptn != NULL, "node should be registered");
 925     set_escape_state(ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "stored at raw address"));
 926     // Add edge to object for unsafe access with offset.
 927     PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
 928     assert(adr_ptn != NULL, "node should be registered");
 929     if (adr_ptn->is_Field()) {
 930       assert(adr_ptn->as_Field()->is_oop(), "should be oop field");
 931       add_edge(adr_ptn, ptn);
 932     }
 933     return true;
 934   }
 935 #ifdef ASSERT
 936   n->dump(1);
 937   assert(false, "not unsafe");
 938 #endif
 939   return false;
 940 }
 941 
 942 void ConnectionGraph::add_call_node(CallNode* call) {
 943   assert(call->returns_pointer(), "only for call which returns pointer");
 944   uint call_idx = call->_idx;
 945   if (call->is_Allocate()) {
 946     Node* k = call->in(AllocateNode::KlassNode);
 947     const TypeKlassPtr* kt = k->bottom_type()->isa_klassptr();
 948     assert(kt != NULL, "TypeKlassPtr  required.");
 949     PointsToNode::EscapeState es = PointsToNode::NoEscape;
 950     bool scalar_replaceable = true;
 951     NOT_PRODUCT(const char* nsr_reason = "");
 952     if (call->is_AllocateArray()) {
 953       if (!kt->isa_aryklassptr()) { // StressReflectiveCode
 954         es = PointsToNode::GlobalEscape;
 955       } else {
 956         int length = call->in(AllocateNode::ALength)->find_int_con(-1);
 957         if (length < 0) {
 958           // Not scalar replaceable if the length is not constant.
 959           scalar_replaceable = false;
 960           NOT_PRODUCT(nsr_reason = "has a non-constant length");
 961         } else if (length > EliminateAllocationArraySizeLimit) {
 962           // Not scalar replaceable if the length is too big.
 963           scalar_replaceable = false;
 964           NOT_PRODUCT(nsr_reason = "has a length that is too big");
 965         }
 966       }
 967     } else {  // Allocate instance
 968       if (!kt->isa_instklassptr()) { // StressReflectiveCode
 969         es = PointsToNode::GlobalEscape;
 970       } else {
 971         const TypeInstKlassPtr* ikt = kt->is_instklassptr();
 972         ciInstanceKlass* ik = ikt->klass_is_exact() ? ikt->exact_klass()->as_instance_klass() : ikt->instance_klass();
 973         if (ik->is_subclass_of(_compile->env()->Thread_klass()) ||
 974             ik->is_subclass_of(_compile->env()->Reference_klass()) ||
 975             !ik->can_be_instantiated() ||
 976             ik->has_finalizer()) {
 977           es = PointsToNode::GlobalEscape;
 978         } else {
 979           int nfields = ik->as_instance_klass()->nof_nonstatic_fields();
 980           if (nfields > EliminateAllocationFieldsLimit) {
 981             // Not scalar replaceable if there are too many fields.
 982             scalar_replaceable = false;
 983             NOT_PRODUCT(nsr_reason = "has too many fields");
 984           }
 985         }
 986       }
 987     }
 988     add_java_object(call, es);
 989     PointsToNode* ptn = ptnode_adr(call_idx);
 990     if (!scalar_replaceable && ptn->scalar_replaceable()) {
 991       set_not_scalar_replaceable(ptn NOT_PRODUCT(COMMA nsr_reason));
 992     }
 993   } else if (call->is_CallStaticJava()) {
 994     // Call nodes could be different types:
 995     //
 996     // 1. CallDynamicJavaNode (what happened during call is unknown):
 997     //
 998     //    - mapped to GlobalEscape JavaObject node if oop is returned;
 999     //
1000     //    - all oop arguments are escaping globally;
1001     //
1002     // 2. CallStaticJavaNode (execute bytecode analysis if possible):
1003     //
1004     //    - the same as CallDynamicJavaNode if can't do bytecode analysis;
1005     //
1006     //    - mapped to GlobalEscape JavaObject node if unknown oop is returned;
1007     //    - mapped to NoEscape JavaObject node if non-escaping object allocated
1008     //      during call is returned;
1009     //    - mapped to ArgEscape LocalVar node pointed to object arguments
1010     //      which are returned and does not escape during call;
1011     //
1012     //    - oop arguments escaping status is defined by bytecode analysis;
1013     //
1014     // For a static call, we know exactly what method is being called.
1015     // Use bytecode estimator to record whether the call's return value escapes.
1016     ciMethod* meth = call->as_CallJava()->method();
1017     if (meth == NULL) {
1018       const char* name = call->as_CallStaticJava()->_name;
1019       assert(strncmp(name, "_multianewarray", 15) == 0, "TODO: add failed case check");
1020       // Returns a newly allocated non-escaped object.
1021       add_java_object(call, PointsToNode::NoEscape);
1022       set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of multinewarray"));
1023     } else if (meth->is_boxing_method()) {
1024       // Returns boxing object
1025       PointsToNode::EscapeState es;
1026       vmIntrinsics::ID intr = meth->intrinsic_id();
1027       if (intr == vmIntrinsics::_floatValue || intr == vmIntrinsics::_doubleValue) {
1028         // It does not escape if object is always allocated.
1029         es = PointsToNode::NoEscape;
1030       } else {
1031         // It escapes globally if object could be loaded from cache.
1032         es = PointsToNode::GlobalEscape;
1033       }
1034       add_java_object(call, es);
1035     } else {
1036       BCEscapeAnalyzer* call_analyzer = meth->get_bcea();
1037       call_analyzer->copy_dependencies(_compile->dependencies());
1038       if (call_analyzer->is_return_allocated()) {
1039         // Returns a newly allocated non-escaped object, simply
1040         // update dependency information.
1041         // Mark it as NoEscape so that objects referenced by
1042         // it's fields will be marked as NoEscape at least.
1043         add_java_object(call, PointsToNode::NoEscape);
1044         set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of call"));
1045       } else {
1046         // Determine whether any arguments are returned.
1047         const TypeTuple* d = call->tf()->domain();
1048         bool ret_arg = false;
1049         for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1050           if (d->field_at(i)->isa_ptr() != NULL &&
1051               call_analyzer->is_arg_returned(i - TypeFunc::Parms)) {
1052             ret_arg = true;
1053             break;
1054           }
1055         }
1056         if (ret_arg) {
1057           add_local_var(call, PointsToNode::ArgEscape);
1058         } else {
1059           // Returns unknown object.
1060           map_ideal_node(call, phantom_obj);
1061         }
1062       }
1063     }
1064   } else {
1065     // An other type of call, assume the worst case:
1066     // returned value is unknown and globally escapes.
1067     assert(call->Opcode() == Op_CallDynamicJava, "add failed case check");
1068     map_ideal_node(call, phantom_obj);
1069   }
1070 }
1071 
1072 void ConnectionGraph::process_call_arguments(CallNode *call) {
1073     bool is_arraycopy = false;
1074     switch (call->Opcode()) {
1075 #ifdef ASSERT
1076     case Op_Allocate:
1077     case Op_AllocateArray:
1078     case Op_Lock:
1079     case Op_Unlock:
1080       assert(false, "should be done already");
1081       break;
1082 #endif
1083     case Op_ArrayCopy:
1084     case Op_CallLeafNoFP:
1085       // Most array copies are ArrayCopy nodes at this point but there
1086       // are still a few direct calls to the copy subroutines (See
1087       // PhaseStringOpts::copy_string())
1088       is_arraycopy = (call->Opcode() == Op_ArrayCopy) ||
1089         call->as_CallLeaf()->is_call_to_arraycopystub();
1090       // fall through
1091     case Op_CallLeafVector:
1092     case Op_CallLeaf: {
1093       // Stub calls, objects do not escape but they are not scale replaceable.
1094       // Adjust escape state for outgoing arguments.
1095       const TypeTuple * d = call->tf()->domain();
1096       bool src_has_oops = false;
1097       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1098         const Type* at = d->field_at(i);
1099         Node *arg = call->in(i);
1100         if (arg == NULL) {
1101           continue;
1102         }
1103         const Type *aat = _igvn->type(arg);
1104         if (arg->is_top() || !at->isa_ptr() || !aat->isa_ptr()) {
1105           continue;
1106         }
1107         if (arg->is_AddP()) {
1108           //
1109           // The inline_native_clone() case when the arraycopy stub is called
1110           // after the allocation before Initialize and CheckCastPP nodes.
1111           // Or normal arraycopy for object arrays case.
1112           //
1113           // Set AddP's base (Allocate) as not scalar replaceable since
1114           // pointer to the base (with offset) is passed as argument.
1115           //
1116           arg = get_addp_base(arg);
1117         }
1118         PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
1119         assert(arg_ptn != NULL, "should be registered");
1120         PointsToNode::EscapeState arg_esc = arg_ptn->escape_state();
1121         if (is_arraycopy || arg_esc < PointsToNode::ArgEscape) {
1122           assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
1123                  aat->isa_ptr() != NULL, "expecting an Ptr");
1124           bool arg_has_oops = aat->isa_oopptr() &&
1125                               (aat->isa_instptr() ||
1126                                (aat->isa_aryptr() && (aat->isa_aryptr()->elem() == Type::BOTTOM || aat->isa_aryptr()->elem()->make_oopptr() != NULL)));
1127           if (i == TypeFunc::Parms) {
1128             src_has_oops = arg_has_oops;
1129           }
1130           //
1131           // src or dst could be j.l.Object when other is basic type array:
1132           //
1133           //   arraycopy(char[],0,Object*,0,size);
1134           //   arraycopy(Object*,0,char[],0,size);
1135           //
1136           // Don't add edges in such cases.
1137           //
1138           bool arg_is_arraycopy_dest = src_has_oops && is_arraycopy &&
1139                                        arg_has_oops && (i > TypeFunc::Parms);
1140 #ifdef ASSERT
1141           if (!(is_arraycopy ||
1142                 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(call) ||
1143                 (call->as_CallLeaf()->_name != NULL &&
1144                  (strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32") == 0 ||
1145                   strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32C") == 0 ||
1146                   strcmp(call->as_CallLeaf()->_name, "updateBytesAdler32") == 0 ||
1147                   strcmp(call->as_CallLeaf()->_name, "aescrypt_encryptBlock") == 0 ||
1148                   strcmp(call->as_CallLeaf()->_name, "aescrypt_decryptBlock") == 0 ||
1149                   strcmp(call->as_CallLeaf()->_name, "cipherBlockChaining_encryptAESCrypt") == 0 ||
1150                   strcmp(call->as_CallLeaf()->_name, "cipherBlockChaining_decryptAESCrypt") == 0 ||
1151                   strcmp(call->as_CallLeaf()->_name, "electronicCodeBook_encryptAESCrypt") == 0 ||
1152                   strcmp(call->as_CallLeaf()->_name, "electronicCodeBook_decryptAESCrypt") == 0 ||
1153                   strcmp(call->as_CallLeaf()->_name, "counterMode_AESCrypt") == 0 ||
1154                   strcmp(call->as_CallLeaf()->_name, "galoisCounterMode_AESCrypt") == 0 ||
1155                   strcmp(call->as_CallLeaf()->_name, "ghash_processBlocks") == 0 ||
1156                   strcmp(call->as_CallLeaf()->_name, "encodeBlock") == 0 ||
1157                   strcmp(call->as_CallLeaf()->_name, "decodeBlock") == 0 ||
1158                   strcmp(call->as_CallLeaf()->_name, "md5_implCompress") == 0 ||
1159                   strcmp(call->as_CallLeaf()->_name, "md5_implCompressMB") == 0 ||
1160                   strcmp(call->as_CallLeaf()->_name, "sha1_implCompress") == 0 ||
1161                   strcmp(call->as_CallLeaf()->_name, "sha1_implCompressMB") == 0 ||
1162                   strcmp(call->as_CallLeaf()->_name, "sha256_implCompress") == 0 ||
1163                   strcmp(call->as_CallLeaf()->_name, "sha256_implCompressMB") == 0 ||
1164                   strcmp(call->as_CallLeaf()->_name, "sha512_implCompress") == 0 ||
1165                   strcmp(call->as_CallLeaf()->_name, "sha512_implCompressMB") == 0 ||
1166                   strcmp(call->as_CallLeaf()->_name, "sha3_implCompress") == 0 ||
1167                   strcmp(call->as_CallLeaf()->_name, "sha3_implCompressMB") == 0 ||
1168                   strcmp(call->as_CallLeaf()->_name, "multiplyToLen") == 0 ||
1169                   strcmp(call->as_CallLeaf()->_name, "squareToLen") == 0 ||
1170                   strcmp(call->as_CallLeaf()->_name, "mulAdd") == 0 ||
1171                   strcmp(call->as_CallLeaf()->_name, "montgomery_multiply") == 0 ||
1172                   strcmp(call->as_CallLeaf()->_name, "montgomery_square") == 0 ||
1173                   strcmp(call->as_CallLeaf()->_name, "bigIntegerRightShiftWorker") == 0 ||
1174                   strcmp(call->as_CallLeaf()->_name, "bigIntegerLeftShiftWorker") == 0 ||
1175                   strcmp(call->as_CallLeaf()->_name, "vectorizedMismatch") == 0 ||
1176                   strcmp(call->as_CallLeaf()->_name, "get_class_id_intrinsic") == 0)
1177                  ))) {
1178             call->dump();
1179             fatal("EA unexpected CallLeaf %s", call->as_CallLeaf()->_name);
1180           }
1181 #endif
1182           // Always process arraycopy's destination object since
1183           // we need to add all possible edges to references in
1184           // source object.
1185           if (arg_esc >= PointsToNode::ArgEscape &&
1186               !arg_is_arraycopy_dest) {
1187             continue;
1188           }
1189           PointsToNode::EscapeState es = PointsToNode::ArgEscape;
1190           if (call->is_ArrayCopy()) {
1191             ArrayCopyNode* ac = call->as_ArrayCopy();
1192             if (ac->is_clonebasic() ||
1193                 ac->is_arraycopy_validated() ||
1194                 ac->is_copyof_validated() ||
1195                 ac->is_copyofrange_validated()) {
1196               es = PointsToNode::NoEscape;
1197             }
1198           }
1199           set_escape_state(arg_ptn, es NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
1200           if (arg_is_arraycopy_dest) {
1201             Node* src = call->in(TypeFunc::Parms);
1202             if (src->is_AddP()) {
1203               src = get_addp_base(src);
1204             }
1205             PointsToNode* src_ptn = ptnode_adr(src->_idx);
1206             assert(src_ptn != NULL, "should be registered");
1207             if (arg_ptn != src_ptn) {
1208               // Special arraycopy edge:
1209               // A destination object's field can't have the source object
1210               // as base since objects escape states are not related.
1211               // Only escape state of destination object's fields affects
1212               // escape state of fields in source object.
1213               add_arraycopy(call, es, src_ptn, arg_ptn);
1214             }
1215           }
1216         }
1217       }
1218       break;
1219     }
1220     case Op_CallStaticJava: {
1221       // For a static call, we know exactly what method is being called.
1222       // Use bytecode estimator to record the call's escape affects
1223 #ifdef ASSERT
1224       const char* name = call->as_CallStaticJava()->_name;
1225       assert((name == NULL || strcmp(name, "uncommon_trap") != 0), "normal calls only");
1226 #endif
1227       ciMethod* meth = call->as_CallJava()->method();
1228       if ((meth != NULL) && meth->is_boxing_method()) {
1229         break; // Boxing methods do not modify any oops.
1230       }
1231       BCEscapeAnalyzer* call_analyzer = (meth !=NULL) ? meth->get_bcea() : NULL;
1232       // fall-through if not a Java method or no analyzer information
1233       if (call_analyzer != NULL) {
1234         PointsToNode* call_ptn = ptnode_adr(call->_idx);
1235         const TypeTuple* d = call->tf()->domain();
1236         for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1237           const Type* at = d->field_at(i);
1238           int k = i - TypeFunc::Parms;
1239           Node* arg = call->in(i);
1240           PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
1241           if (at->isa_ptr() != NULL &&
1242               call_analyzer->is_arg_returned(k)) {
1243             // The call returns arguments.
1244             if (call_ptn != NULL) { // Is call's result used?
1245               assert(call_ptn->is_LocalVar(), "node should be registered");
1246               assert(arg_ptn != NULL, "node should be registered");
1247               add_edge(call_ptn, arg_ptn);
1248             }
1249           }
1250           if (at->isa_oopptr() != NULL &&
1251               arg_ptn->escape_state() < PointsToNode::GlobalEscape) {
1252             if (!call_analyzer->is_arg_stack(k)) {
1253               // The argument global escapes
1254               set_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
1255             } else {
1256               set_escape_state(arg_ptn, PointsToNode::ArgEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
1257               if (!call_analyzer->is_arg_local(k)) {
1258                 // The argument itself doesn't escape, but any fields might
1259                 set_fields_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
1260               }
1261             }
1262           }
1263         }
1264         if (call_ptn != NULL && call_ptn->is_LocalVar()) {
1265           // The call returns arguments.
1266           assert(call_ptn->edge_count() > 0, "sanity");
1267           if (!call_analyzer->is_return_local()) {
1268             // Returns also unknown object.
1269             add_edge(call_ptn, phantom_obj);
1270           }
1271         }
1272         break;
1273       }
1274     }
1275     default: {
1276       // Fall-through here if not a Java method or no analyzer information
1277       // or some other type of call, assume the worst case: all arguments
1278       // globally escape.
1279       const TypeTuple* d = call->tf()->domain();
1280       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1281         const Type* at = d->field_at(i);
1282         if (at->isa_oopptr() != NULL) {
1283           Node* arg = call->in(i);
1284           if (arg->is_AddP()) {
1285             arg = get_addp_base(arg);
1286           }
1287           assert(ptnode_adr(arg->_idx) != NULL, "should be defined already");
1288           set_escape_state(ptnode_adr(arg->_idx), PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
1289         }
1290       }
1291     }
1292   }
1293 }
1294 
1295 
1296 // Finish Graph construction.
1297 bool ConnectionGraph::complete_connection_graph(
1298                          GrowableArray<PointsToNode*>&   ptnodes_worklist,
1299                          GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist,
1300                          GrowableArray<JavaObjectNode*>& java_objects_worklist,
1301                          GrowableArray<FieldNode*>&      oop_fields_worklist) {
1302   // Normally only 1-3 passes needed to build Connection Graph depending
1303   // on graph complexity. Observed 8 passes in jvm2008 compiler.compiler.
1304   // Set limit to 20 to catch situation when something did go wrong and
1305   // bailout Escape Analysis.
1306   // Also limit build time to 20 sec (60 in debug VM), EscapeAnalysisTimeout flag.
1307 #define GRAPH_BUILD_ITER_LIMIT 20
1308 
1309   // Propagate GlobalEscape and ArgEscape escape states and check that
1310   // we still have non-escaping objects. The method pushs on _worklist
1311   // Field nodes which reference phantom_object.
1312   if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_allocs_worklist)) {
1313     return false; // Nothing to do.
1314   }
1315   // Now propagate references to all JavaObject nodes.
1316   int java_objects_length = java_objects_worklist.length();
1317   elapsedTimer build_time;
1318   build_time.start();
1319   elapsedTimer time;
1320   bool timeout = false;
1321   int new_edges = 1;
1322   int iterations = 0;
1323   do {
1324     while ((new_edges > 0) &&
1325            (iterations++ < GRAPH_BUILD_ITER_LIMIT)) {
1326       double start_time = time.seconds();
1327       time.start();
1328       new_edges = 0;
1329       // Propagate references to phantom_object for nodes pushed on _worklist
1330       // by find_non_escaped_objects() and find_field_value().
1331       new_edges += add_java_object_edges(phantom_obj, false);
1332       for (int next = 0; next < java_objects_length; ++next) {
1333         JavaObjectNode* ptn = java_objects_worklist.at(next);
1334         new_edges += add_java_object_edges(ptn, true);
1335 
1336 #define SAMPLE_SIZE 4
1337         if ((next % SAMPLE_SIZE) == 0) {
1338           // Each 4 iterations calculate how much time it will take
1339           // to complete graph construction.
1340           time.stop();
1341           // Poll for requests from shutdown mechanism to quiesce compiler
1342           // because Connection graph construction may take long time.
1343           CompileBroker::maybe_block();
1344           double stop_time = time.seconds();
1345           double time_per_iter = (stop_time - start_time) / (double)SAMPLE_SIZE;
1346           double time_until_end = time_per_iter * (double)(java_objects_length - next);
1347           if ((start_time + time_until_end) >= EscapeAnalysisTimeout) {
1348             timeout = true;
1349             break; // Timeout
1350           }
1351           start_time = stop_time;
1352           time.start();
1353         }
1354 #undef SAMPLE_SIZE
1355 
1356       }
1357       if (timeout) break;
1358       if (new_edges > 0) {
1359         // Update escape states on each iteration if graph was updated.
1360         if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_allocs_worklist)) {
1361           return false; // Nothing to do.
1362         }
1363       }
1364       time.stop();
1365       if (time.seconds() >= EscapeAnalysisTimeout) {
1366         timeout = true;
1367         break;
1368       }
1369     }
1370     if ((iterations < GRAPH_BUILD_ITER_LIMIT) && !timeout) {
1371       time.start();
1372       // Find fields which have unknown value.
1373       int fields_length = oop_fields_worklist.length();
1374       for (int next = 0; next < fields_length; next++) {
1375         FieldNode* field = oop_fields_worklist.at(next);
1376         if (field->edge_count() == 0) {
1377           new_edges += find_field_value(field);
1378           // This code may added new edges to phantom_object.
1379           // Need an other cycle to propagate references to phantom_object.
1380         }
1381       }
1382       time.stop();
1383       if (time.seconds() >= EscapeAnalysisTimeout) {
1384         timeout = true;
1385         break;
1386       }
1387     } else {
1388       new_edges = 0; // Bailout
1389     }
1390   } while (new_edges > 0);
1391 
1392   build_time.stop();
1393   _build_time = build_time.seconds();
1394   _build_iterations = iterations;
1395 
1396   // Bailout if passed limits.
1397   if ((iterations >= GRAPH_BUILD_ITER_LIMIT) || timeout) {
1398     Compile* C = _compile;
1399     if (C->log() != NULL) {
1400       C->log()->begin_elem("connectionGraph_bailout reason='reached ");
1401       C->log()->text("%s", timeout ? "time" : "iterations");
1402       C->log()->end_elem(" limit'");
1403     }
1404     assert(ExitEscapeAnalysisOnTimeout, "infinite EA connection graph build during invocation %d (%f sec, %d iterations) with %d nodes and worklist size %d",
1405            _invocation, _build_time, _build_iterations, nodes_size(), ptnodes_worklist.length());
1406     // Possible infinite build_connection_graph loop,
1407     // bailout (no changes to ideal graph were made).
1408     return false;
1409   }
1410 
1411 #undef GRAPH_BUILD_ITER_LIMIT
1412 
1413   // Find fields initialized by NULL for non-escaping Allocations.
1414   int non_escaped_length = non_escaped_allocs_worklist.length();
1415   for (int next = 0; next < non_escaped_length; next++) {
1416     JavaObjectNode* ptn = non_escaped_allocs_worklist.at(next);
1417     PointsToNode::EscapeState es = ptn->escape_state();
1418     assert(es <= PointsToNode::ArgEscape, "sanity");
1419     if (es == PointsToNode::NoEscape) {
1420       if (find_init_values_null(ptn, _igvn) > 0) {
1421         // Adding references to NULL object does not change escape states
1422         // since it does not escape. Also no fields are added to NULL object.
1423         add_java_object_edges(null_obj, false);
1424       }
1425     }
1426     Node* n = ptn->ideal_node();
1427     if (n->is_Allocate()) {
1428       // The object allocated by this Allocate node will never be
1429       // seen by an other thread. Mark it so that when it is
1430       // expanded no MemBarStoreStore is added.
1431       InitializeNode* ini = n->as_Allocate()->initialization();
1432       if (ini != NULL)
1433         ini->set_does_not_escape();
1434     }
1435   }
1436   return true; // Finished graph construction.
1437 }
1438 
1439 // Propagate GlobalEscape and ArgEscape escape states to all nodes
1440 // and check that we still have non-escaping java objects.
1441 bool ConnectionGraph::find_non_escaped_objects(GrowableArray<PointsToNode*>& ptnodes_worklist,
1442                                                GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist) {
1443   GrowableArray<PointsToNode*> escape_worklist;
1444   // First, put all nodes with GlobalEscape and ArgEscape states on worklist.
1445   int ptnodes_length = ptnodes_worklist.length();
1446   for (int next = 0; next < ptnodes_length; ++next) {
1447     PointsToNode* ptn = ptnodes_worklist.at(next);
1448     if (ptn->escape_state() >= PointsToNode::ArgEscape ||
1449         ptn->fields_escape_state() >= PointsToNode::ArgEscape) {
1450       escape_worklist.push(ptn);
1451     }
1452   }
1453   // Set escape states to referenced nodes (edges list).
1454   while (escape_worklist.length() > 0) {
1455     PointsToNode* ptn = escape_worklist.pop();
1456     PointsToNode::EscapeState es  = ptn->escape_state();
1457     PointsToNode::EscapeState field_es = ptn->fields_escape_state();
1458     if (ptn->is_Field() && ptn->as_Field()->is_oop() &&
1459         es >= PointsToNode::ArgEscape) {
1460       // GlobalEscape or ArgEscape state of field means it has unknown value.
1461       if (add_edge(ptn, phantom_obj)) {
1462         // New edge was added
1463         add_field_uses_to_worklist(ptn->as_Field());
1464       }
1465     }
1466     for (EdgeIterator i(ptn); i.has_next(); i.next()) {
1467       PointsToNode* e = i.get();
1468       if (e->is_Arraycopy()) {
1469         assert(ptn->arraycopy_dst(), "sanity");
1470         // Propagate only fields escape state through arraycopy edge.
1471         if (e->fields_escape_state() < field_es) {
1472           set_fields_escape_state(e, field_es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
1473           escape_worklist.push(e);
1474         }
1475       } else if (es >= field_es) {
1476         // fields_escape_state is also set to 'es' if it is less than 'es'.
1477         if (e->escape_state() < es) {
1478           set_escape_state(e, es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
1479           escape_worklist.push(e);
1480         }
1481       } else {
1482         // Propagate field escape state.
1483         bool es_changed = false;
1484         if (e->fields_escape_state() < field_es) {
1485           set_fields_escape_state(e, field_es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
1486           es_changed = true;
1487         }
1488         if ((e->escape_state() < field_es) &&
1489             e->is_Field() && ptn->is_JavaObject() &&
1490             e->as_Field()->is_oop()) {
1491           // Change escape state of referenced fields.
1492           set_escape_state(e, field_es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
1493           es_changed = true;
1494         } else if (e->escape_state() < es) {
1495           set_escape_state(e, es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
1496           es_changed = true;
1497         }
1498         if (es_changed) {
1499           escape_worklist.push(e);
1500         }
1501       }
1502     }
1503   }
1504   // Remove escaped objects from non_escaped list.
1505   for (int next = non_escaped_allocs_worklist.length()-1; next >= 0 ; --next) {
1506     JavaObjectNode* ptn = non_escaped_allocs_worklist.at(next);
1507     if (ptn->escape_state() >= PointsToNode::GlobalEscape) {
1508       non_escaped_allocs_worklist.delete_at(next);
1509     }
1510     if (ptn->escape_state() == PointsToNode::NoEscape) {
1511       // Find fields in non-escaped allocations which have unknown value.
1512       find_init_values_phantom(ptn);
1513     }
1514   }
1515   return (non_escaped_allocs_worklist.length() > 0);
1516 }
1517 
1518 // Add all references to JavaObject node by walking over all uses.
1519 int ConnectionGraph::add_java_object_edges(JavaObjectNode* jobj, bool populate_worklist) {
1520   int new_edges = 0;
1521   if (populate_worklist) {
1522     // Populate _worklist by uses of jobj's uses.
1523     for (UseIterator i(jobj); i.has_next(); i.next()) {
1524       PointsToNode* use = i.get();
1525       if (use->is_Arraycopy()) {
1526         continue;
1527       }
1528       add_uses_to_worklist(use);
1529       if (use->is_Field() && use->as_Field()->is_oop()) {
1530         // Put on worklist all field's uses (loads) and
1531         // related field nodes (same base and offset).
1532         add_field_uses_to_worklist(use->as_Field());
1533       }
1534     }
1535   }
1536   for (int l = 0; l < _worklist.length(); l++) {
1537     PointsToNode* use = _worklist.at(l);
1538     if (PointsToNode::is_base_use(use)) {
1539       // Add reference from jobj to field and from field to jobj (field's base).
1540       use = PointsToNode::get_use_node(use)->as_Field();
1541       if (add_base(use->as_Field(), jobj)) {
1542         new_edges++;
1543       }
1544       continue;
1545     }
1546     assert(!use->is_JavaObject(), "sanity");
1547     if (use->is_Arraycopy()) {
1548       if (jobj == null_obj) { // NULL object does not have field edges
1549         continue;
1550       }
1551       // Added edge from Arraycopy node to arraycopy's source java object
1552       if (add_edge(use, jobj)) {
1553         jobj->set_arraycopy_src();
1554         new_edges++;
1555       }
1556       // and stop here.
1557       continue;
1558     }
1559     if (!add_edge(use, jobj)) {
1560       continue; // No new edge added, there was such edge already.
1561     }
1562     new_edges++;
1563     if (use->is_LocalVar()) {
1564       add_uses_to_worklist(use);
1565       if (use->arraycopy_dst()) {
1566         for (EdgeIterator i(use); i.has_next(); i.next()) {
1567           PointsToNode* e = i.get();
1568           if (e->is_Arraycopy()) {
1569             if (jobj == null_obj) { // NULL object does not have field edges
1570               continue;
1571             }
1572             // Add edge from arraycopy's destination java object to Arraycopy node.
1573             if (add_edge(jobj, e)) {
1574               new_edges++;
1575               jobj->set_arraycopy_dst();
1576             }
1577           }
1578         }
1579       }
1580     } else {
1581       // Added new edge to stored in field values.
1582       // Put on worklist all field's uses (loads) and
1583       // related field nodes (same base and offset).
1584       add_field_uses_to_worklist(use->as_Field());
1585     }
1586   }
1587   _worklist.clear();
1588   _in_worklist.reset();
1589   return new_edges;
1590 }
1591 
1592 // Put on worklist all related field nodes.
1593 void ConnectionGraph::add_field_uses_to_worklist(FieldNode* field) {
1594   assert(field->is_oop(), "sanity");
1595   int offset = field->offset();
1596   add_uses_to_worklist(field);
1597   // Loop over all bases of this field and push on worklist Field nodes
1598   // with the same offset and base (since they may reference the same field).
1599   for (BaseIterator i(field); i.has_next(); i.next()) {
1600     PointsToNode* base = i.get();
1601     add_fields_to_worklist(field, base);
1602     // Check if the base was source object of arraycopy and go over arraycopy's
1603     // destination objects since values stored to a field of source object are
1604     // accessible by uses (loads) of fields of destination objects.
1605     if (base->arraycopy_src()) {
1606       for (UseIterator j(base); j.has_next(); j.next()) {
1607         PointsToNode* arycp = j.get();
1608         if (arycp->is_Arraycopy()) {
1609           for (UseIterator k(arycp); k.has_next(); k.next()) {
1610             PointsToNode* abase = k.get();
1611             if (abase->arraycopy_dst() && abase != base) {
1612               // Look for the same arraycopy reference.
1613               add_fields_to_worklist(field, abase);
1614             }
1615           }
1616         }
1617       }
1618     }
1619   }
1620 }
1621 
1622 // Put on worklist all related field nodes.
1623 void ConnectionGraph::add_fields_to_worklist(FieldNode* field, PointsToNode* base) {
1624   int offset = field->offset();
1625   if (base->is_LocalVar()) {
1626     for (UseIterator j(base); j.has_next(); j.next()) {
1627       PointsToNode* f = j.get();
1628       if (PointsToNode::is_base_use(f)) { // Field
1629         f = PointsToNode::get_use_node(f);
1630         if (f == field || !f->as_Field()->is_oop()) {
1631           continue;
1632         }
1633         int offs = f->as_Field()->offset();
1634         if (offs == offset || offset == Type::OffsetBot || offs == Type::OffsetBot) {
1635           add_to_worklist(f);
1636         }
1637       }
1638     }
1639   } else {
1640     assert(base->is_JavaObject(), "sanity");
1641     if (// Skip phantom_object since it is only used to indicate that
1642         // this field's content globally escapes.
1643         (base != phantom_obj) &&
1644         // NULL object node does not have fields.
1645         (base != null_obj)) {
1646       for (EdgeIterator i(base); i.has_next(); i.next()) {
1647         PointsToNode* f = i.get();
1648         // Skip arraycopy edge since store to destination object field
1649         // does not update value in source object field.
1650         if (f->is_Arraycopy()) {
1651           assert(base->arraycopy_dst(), "sanity");
1652           continue;
1653         }
1654         if (f == field || !f->as_Field()->is_oop()) {
1655           continue;
1656         }
1657         int offs = f->as_Field()->offset();
1658         if (offs == offset || offset == Type::OffsetBot || offs == Type::OffsetBot) {
1659           add_to_worklist(f);
1660         }
1661       }
1662     }
1663   }
1664 }
1665 
1666 // Find fields which have unknown value.
1667 int ConnectionGraph::find_field_value(FieldNode* field) {
1668   // Escaped fields should have init value already.
1669   assert(field->escape_state() == PointsToNode::NoEscape, "sanity");
1670   int new_edges = 0;
1671   for (BaseIterator i(field); i.has_next(); i.next()) {
1672     PointsToNode* base = i.get();
1673     if (base->is_JavaObject()) {
1674       // Skip Allocate's fields which will be processed later.
1675       if (base->ideal_node()->is_Allocate()) {
1676         return 0;
1677       }
1678       assert(base == null_obj, "only NULL ptr base expected here");
1679     }
1680   }
1681   if (add_edge(field, phantom_obj)) {
1682     // New edge was added
1683     new_edges++;
1684     add_field_uses_to_worklist(field);
1685   }
1686   return new_edges;
1687 }
1688 
1689 // Find fields initializing values for allocations.
1690 int ConnectionGraph::find_init_values_phantom(JavaObjectNode* pta) {
1691   assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
1692   Node* alloc = pta->ideal_node();
1693 
1694   // Do nothing for Allocate nodes since its fields values are
1695   // "known" unless they are initialized by arraycopy/clone.
1696   if (alloc->is_Allocate() && !pta->arraycopy_dst()) {
1697     return 0;
1698   }
1699   assert(pta->arraycopy_dst() || alloc->as_CallStaticJava(), "sanity");
1700 #ifdef ASSERT
1701   if (!pta->arraycopy_dst() && alloc->as_CallStaticJava()->method() == NULL) {
1702     const char* name = alloc->as_CallStaticJava()->_name;
1703     assert(strncmp(name, "_multianewarray", 15) == 0, "sanity");
1704   }
1705 #endif
1706   // Non-escaped allocation returned from Java or runtime call have unknown values in fields.
1707   int new_edges = 0;
1708   for (EdgeIterator i(pta); i.has_next(); i.next()) {
1709     PointsToNode* field = i.get();
1710     if (field->is_Field() && field->as_Field()->is_oop()) {
1711       if (add_edge(field, phantom_obj)) {
1712         // New edge was added
1713         new_edges++;
1714         add_field_uses_to_worklist(field->as_Field());
1715       }
1716     }
1717   }
1718   return new_edges;
1719 }
1720 
1721 // Find fields initializing values for allocations.
1722 int ConnectionGraph::find_init_values_null(JavaObjectNode* pta, PhaseTransform* phase) {
1723   assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
1724   Node* alloc = pta->ideal_node();
1725   // Do nothing for Call nodes since its fields values are unknown.
1726   if (!alloc->is_Allocate()) {
1727     return 0;
1728   }
1729   InitializeNode* ini = alloc->as_Allocate()->initialization();
1730   bool visited_bottom_offset = false;
1731   GrowableArray<int> offsets_worklist;
1732   int new_edges = 0;
1733 
1734   // Check if an oop field's initializing value is recorded and add
1735   // a corresponding NULL if field's value if it is not recorded.
1736   // Connection Graph does not record a default initialization by NULL
1737   // captured by Initialize node.
1738   //
1739   for (EdgeIterator i(pta); i.has_next(); i.next()) {
1740     PointsToNode* field = i.get(); // Field (AddP)
1741     if (!field->is_Field() || !field->as_Field()->is_oop()) {
1742       continue; // Not oop field
1743     }
1744     int offset = field->as_Field()->offset();
1745     if (offset == Type::OffsetBot) {
1746       if (!visited_bottom_offset) {
1747         // OffsetBot is used to reference array's element,
1748         // always add reference to NULL to all Field nodes since we don't
1749         // known which element is referenced.
1750         if (add_edge(field, null_obj)) {
1751           // New edge was added
1752           new_edges++;
1753           add_field_uses_to_worklist(field->as_Field());
1754           visited_bottom_offset = true;
1755         }
1756       }
1757     } else {
1758       // Check only oop fields.
1759       const Type* adr_type = field->ideal_node()->as_AddP()->bottom_type();
1760       if (adr_type->isa_rawptr()) {
1761 #ifdef ASSERT
1762         // Raw pointers are used for initializing stores so skip it
1763         // since it should be recorded already
1764         Node* base = get_addp_base(field->ideal_node());
1765         assert(adr_type->isa_rawptr() && is_captured_store_address(field->ideal_node()), "unexpected pointer type");
1766 #endif
1767         continue;
1768       }
1769       if (!offsets_worklist.contains(offset)) {
1770         offsets_worklist.append(offset);
1771         Node* value = NULL;
1772         if (ini != NULL) {
1773           // StoreP::memory_type() == T_ADDRESS
1774           BasicType ft = UseCompressedOops ? T_NARROWOOP : T_ADDRESS;
1775           Node* store = ini->find_captured_store(offset, type2aelembytes(ft, true), phase);
1776           // Make sure initializing store has the same type as this AddP.
1777           // This AddP may reference non existing field because it is on a
1778           // dead branch of bimorphic call which is not eliminated yet.
1779           if (store != NULL && store->is_Store() &&
1780               store->as_Store()->memory_type() == ft) {
1781             value = store->in(MemNode::ValueIn);
1782 #ifdef ASSERT
1783             if (VerifyConnectionGraph) {
1784               // Verify that AddP already points to all objects the value points to.
1785               PointsToNode* val = ptnode_adr(value->_idx);
1786               assert((val != NULL), "should be processed already");
1787               PointsToNode* missed_obj = NULL;
1788               if (val->is_JavaObject()) {
1789                 if (!field->points_to(val->as_JavaObject())) {
1790                   missed_obj = val;
1791                 }
1792               } else {
1793                 if (!val->is_LocalVar() || (val->edge_count() == 0)) {
1794                   tty->print_cr("----------init store has invalid value -----");
1795                   store->dump();
1796                   val->dump();
1797                   assert(val->is_LocalVar() && (val->edge_count() > 0), "should be processed already");
1798                 }
1799                 for (EdgeIterator j(val); j.has_next(); j.next()) {
1800                   PointsToNode* obj = j.get();
1801                   if (obj->is_JavaObject()) {
1802                     if (!field->points_to(obj->as_JavaObject())) {
1803                       missed_obj = obj;
1804                       break;
1805                     }
1806                   }
1807                 }
1808               }
1809               if (missed_obj != NULL) {
1810                 tty->print_cr("----------field---------------------------------");
1811                 field->dump();
1812                 tty->print_cr("----------missed referernce to object-----------");
1813                 missed_obj->dump();
1814                 tty->print_cr("----------object referernced by init store -----");
1815                 store->dump();
1816                 val->dump();
1817                 assert(!field->points_to(missed_obj->as_JavaObject()), "missed JavaObject reference");
1818               }
1819             }
1820 #endif
1821           } else {
1822             // There could be initializing stores which follow allocation.
1823             // For example, a volatile field store is not collected
1824             // by Initialize node.
1825             //
1826             // Need to check for dependent loads to separate such stores from
1827             // stores which follow loads. For now, add initial value NULL so
1828             // that compare pointers optimization works correctly.
1829           }
1830         }
1831         if (value == NULL) {
1832           // A field's initializing value was not recorded. Add NULL.
1833           if (add_edge(field, null_obj)) {
1834             // New edge was added
1835             new_edges++;
1836             add_field_uses_to_worklist(field->as_Field());
1837           }
1838         }
1839       }
1840     }
1841   }
1842   return new_edges;
1843 }
1844 
1845 // Adjust scalar_replaceable state after Connection Graph is built.
1846 void ConnectionGraph::adjust_scalar_replaceable_state(JavaObjectNode* jobj) {
1847   // Search for non-escaping objects which are not scalar replaceable
1848   // and mark them to propagate the state to referenced objects.
1849 
1850   for (UseIterator i(jobj); i.has_next(); i.next()) {
1851     PointsToNode* use = i.get();
1852     if (use->is_Arraycopy()) {
1853       continue;
1854     }
1855     if (use->is_Field()) {
1856       FieldNode* field = use->as_Field();
1857       assert(field->is_oop() && field->scalar_replaceable(), "sanity");
1858       // 1. An object is not scalar replaceable if the field into which it is
1859       // stored has unknown offset (stored into unknown element of an array).
1860       if (field->offset() == Type::OffsetBot) {
1861         set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is stored at unknown offset"));
1862         return;
1863       }
1864       // 2. An object is not scalar replaceable if the field into which it is
1865       // stored has multiple bases one of which is null.
1866       if (field->base_count() > 1) {
1867         for (BaseIterator i(field); i.has_next(); i.next()) {
1868           PointsToNode* base = i.get();
1869           if (base == null_obj) {
1870             set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is stored into field with potentially null base"));
1871             return;
1872           }
1873         }
1874       }
1875     }
1876     assert(use->is_Field() || use->is_LocalVar(), "sanity");
1877     // 3. An object is not scalar replaceable if it is merged with other objects.
1878     for (EdgeIterator j(use); j.has_next(); j.next()) {
1879       PointsToNode* ptn = j.get();
1880       if (ptn->is_JavaObject() && ptn != jobj) {
1881         // Mark all objects.
1882         set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA trace_merged_message(ptn)));
1883         set_not_scalar_replaceable(ptn NOT_PRODUCT(COMMA trace_merged_message(jobj)));
1884       }
1885     }
1886     if (!jobj->scalar_replaceable()) {
1887       return;
1888     }
1889   }
1890 
1891   for (EdgeIterator j(jobj); j.has_next(); j.next()) {
1892     if (j.get()->is_Arraycopy()) {
1893       continue;
1894     }
1895 
1896     // Non-escaping object node should point only to field nodes.
1897     FieldNode* field = j.get()->as_Field();
1898     int offset = field->as_Field()->offset();
1899 
1900     // 4. An object is not scalar replaceable if it has a field with unknown
1901     // offset (array's element is accessed in loop).
1902     if (offset == Type::OffsetBot) {
1903       set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "has field with unknown offset"));
1904       return;
1905     }
1906     // 5. Currently an object is not scalar replaceable if a LoadStore node
1907     // access its field since the field value is unknown after it.
1908     //
1909     Node* n = field->ideal_node();
1910 
1911     // Test for an unsafe access that was parsed as maybe off heap
1912     // (with a CheckCastPP to raw memory).
1913     assert(n->is_AddP(), "expect an address computation");
1914     if (n->in(AddPNode::Base)->is_top() &&
1915         n->in(AddPNode::Address)->Opcode() == Op_CheckCastPP) {
1916       assert(n->in(AddPNode::Address)->bottom_type()->isa_rawptr(), "raw address so raw cast expected");
1917       assert(_igvn->type(n->in(AddPNode::Address)->in(1))->isa_oopptr(), "cast pattern at unsafe access expected");
1918       set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is used as base of mixed unsafe access"));
1919       return;
1920     }
1921 
1922     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1923       Node* u = n->fast_out(i);
1924       if (u->is_LoadStore() || (u->is_Mem() && u->as_Mem()->is_mismatched_access())) {
1925         set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is used in LoadStore or mismatched access"));
1926         return;
1927       }
1928     }
1929 
1930     // 6. Or the address may point to more then one object. This may produce
1931     // the false positive result (set not scalar replaceable)
1932     // since the flow-insensitive escape analysis can't separate
1933     // the case when stores overwrite the field's value from the case
1934     // when stores happened on different control branches.
1935     //
1936     // Note: it will disable scalar replacement in some cases:
1937     //
1938     //    Point p[] = new Point[1];
1939     //    p[0] = new Point(); // Will be not scalar replaced
1940     //
1941     // but it will save us from incorrect optimizations in next cases:
1942     //
1943     //    Point p[] = new Point[1];
1944     //    if ( x ) p[0] = new Point(); // Will be not scalar replaced
1945     //
1946     if (field->base_count() > 1) {
1947       for (BaseIterator i(field); i.has_next(); i.next()) {
1948         PointsToNode* base = i.get();
1949         // Don't take into account LocalVar nodes which
1950         // may point to only one object which should be also
1951         // this field's base by now.
1952         if (base->is_JavaObject() && base != jobj) {
1953           // Mark all bases.
1954           set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "may point to more than one object"));
1955           set_not_scalar_replaceable(base NOT_PRODUCT(COMMA "may point to more than one object"));
1956         }
1957       }
1958     }
1959   }
1960 }
1961 
1962 #ifdef ASSERT
1963 void ConnectionGraph::verify_connection_graph(
1964                          GrowableArray<PointsToNode*>&   ptnodes_worklist,
1965                          GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist,
1966                          GrowableArray<JavaObjectNode*>& java_objects_worklist,
1967                          GrowableArray<Node*>& addp_worklist) {
1968   // Verify that graph is complete - no new edges could be added.
1969   int java_objects_length = java_objects_worklist.length();
1970   int non_escaped_length  = non_escaped_allocs_worklist.length();
1971   int new_edges = 0;
1972   for (int next = 0; next < java_objects_length; ++next) {
1973     JavaObjectNode* ptn = java_objects_worklist.at(next);
1974     new_edges += add_java_object_edges(ptn, true);
1975   }
1976   assert(new_edges == 0, "graph was not complete");
1977   // Verify that escape state is final.
1978   int length = non_escaped_allocs_worklist.length();
1979   find_non_escaped_objects(ptnodes_worklist, non_escaped_allocs_worklist);
1980   assert((non_escaped_length == non_escaped_allocs_worklist.length()) &&
1981          (non_escaped_length == length) &&
1982          (_worklist.length() == 0), "escape state was not final");
1983 
1984   // Verify fields information.
1985   int addp_length = addp_worklist.length();
1986   for (int next = 0; next < addp_length; ++next ) {
1987     Node* n = addp_worklist.at(next);
1988     FieldNode* field = ptnode_adr(n->_idx)->as_Field();
1989     if (field->is_oop()) {
1990       // Verify that field has all bases
1991       Node* base = get_addp_base(n);
1992       PointsToNode* ptn = ptnode_adr(base->_idx);
1993       if (ptn->is_JavaObject()) {
1994         assert(field->has_base(ptn->as_JavaObject()), "sanity");
1995       } else {
1996         assert(ptn->is_LocalVar(), "sanity");
1997         for (EdgeIterator i(ptn); i.has_next(); i.next()) {
1998           PointsToNode* e = i.get();
1999           if (e->is_JavaObject()) {
2000             assert(field->has_base(e->as_JavaObject()), "sanity");
2001           }
2002         }
2003       }
2004       // Verify that all fields have initializing values.
2005       if (field->edge_count() == 0) {
2006         tty->print_cr("----------field does not have references----------");
2007         field->dump();
2008         for (BaseIterator i(field); i.has_next(); i.next()) {
2009           PointsToNode* base = i.get();
2010           tty->print_cr("----------field has next base---------------------");
2011           base->dump();
2012           if (base->is_JavaObject() && (base != phantom_obj) && (base != null_obj)) {
2013             tty->print_cr("----------base has fields-------------------------");
2014             for (EdgeIterator j(base); j.has_next(); j.next()) {
2015               j.get()->dump();
2016             }
2017             tty->print_cr("----------base has references---------------------");
2018             for (UseIterator j(base); j.has_next(); j.next()) {
2019               j.get()->dump();
2020             }
2021           }
2022         }
2023         for (UseIterator i(field); i.has_next(); i.next()) {
2024           i.get()->dump();
2025         }
2026         assert(field->edge_count() > 0, "sanity");
2027       }
2028     }
2029   }
2030 }
2031 #endif
2032 
2033 // Optimize ideal graph.
2034 void ConnectionGraph::optimize_ideal_graph(GrowableArray<Node*>& ptr_cmp_worklist,
2035                                            GrowableArray<MemBarStoreStoreNode*>& storestore_worklist) {
2036   Compile* C = _compile;
2037   PhaseIterGVN* igvn = _igvn;
2038   if (EliminateLocks) {
2039     // Mark locks before changing ideal graph.
2040     int cnt = C->macro_count();
2041     for (int i = 0; i < cnt; i++) {
2042       Node *n = C->macro_node(i);
2043       if (n->is_AbstractLock()) { // Lock and Unlock nodes
2044         AbstractLockNode* alock = n->as_AbstractLock();
2045         if (!alock->is_non_esc_obj()) {
2046           if (not_global_escape(alock->obj_node())) {
2047             assert(!alock->is_eliminated() || alock->is_coarsened(), "sanity");
2048             // The lock could be marked eliminated by lock coarsening
2049             // code during first IGVN before EA. Replace coarsened flag
2050             // to eliminate all associated locks/unlocks.
2051 #ifdef ASSERT
2052             alock->log_lock_optimization(C, "eliminate_lock_set_non_esc3");
2053 #endif
2054             alock->set_non_esc_obj();
2055           }
2056         }
2057       }
2058     }
2059   }
2060 
2061   if (OptimizePtrCompare) {
2062     for (int i = 0; i < ptr_cmp_worklist.length(); i++) {
2063       Node *n = ptr_cmp_worklist.at(i);
2064       const TypeInt* tcmp = optimize_ptr_compare(n);
2065       if (tcmp->singleton()) {
2066         Node* cmp = igvn->makecon(tcmp);
2067 #ifndef PRODUCT
2068         if (PrintOptimizePtrCompare) {
2069           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"));
2070           if (Verbose) {
2071             n->dump(1);
2072           }
2073         }
2074 #endif
2075         igvn->replace_node(n, cmp);
2076       }
2077     }
2078   }
2079 
2080   // For MemBarStoreStore nodes added in library_call.cpp, check
2081   // escape status of associated AllocateNode and optimize out
2082   // MemBarStoreStore node if the allocated object never escapes.
2083   for (int i = 0; i < storestore_worklist.length(); i++) {
2084     Node* storestore = storestore_worklist.at(i);
2085     Node* alloc = storestore->in(MemBarNode::Precedent)->in(0);
2086     if (alloc->is_Allocate() && not_global_escape(alloc)) {
2087       MemBarNode* mb = MemBarNode::make(C, Op_MemBarCPUOrder, Compile::AliasIdxBot);
2088       mb->init_req(TypeFunc::Memory,  storestore->in(TypeFunc::Memory));
2089       mb->init_req(TypeFunc::Control, storestore->in(TypeFunc::Control));
2090       igvn->register_new_node_with_optimizer(mb);
2091       igvn->replace_node(storestore, mb);
2092     }
2093   }
2094 }
2095 
2096 // Optimize objects compare.
2097 const TypeInt* ConnectionGraph::optimize_ptr_compare(Node* n) {
2098   assert(OptimizePtrCompare, "sanity");
2099   assert(n->Opcode() == Op_CmpN || n->Opcode() == Op_CmpP, "must be");
2100   const TypeInt* EQ = TypeInt::CC_EQ; // [0] == ZERO
2101   const TypeInt* NE = TypeInt::CC_GT; // [1] == ONE
2102   const TypeInt* UNKNOWN = TypeInt::CC;    // [-1, 0,1]
2103 
2104   PointsToNode* ptn1 = ptnode_adr(n->in(1)->_idx);
2105   PointsToNode* ptn2 = ptnode_adr(n->in(2)->_idx);
2106   JavaObjectNode* jobj1 = unique_java_object(n->in(1));
2107   JavaObjectNode* jobj2 = unique_java_object(n->in(2));
2108   assert(ptn1->is_JavaObject() || ptn1->is_LocalVar(), "sanity");
2109   assert(ptn2->is_JavaObject() || ptn2->is_LocalVar(), "sanity");
2110 
2111   // Check simple cases first.
2112   if (jobj1 != NULL) {
2113     if (jobj1->escape_state() == PointsToNode::NoEscape) {
2114       if (jobj1 == jobj2) {
2115         // Comparing the same not escaping object.
2116         return EQ;
2117       }
2118       Node* obj = jobj1->ideal_node();
2119       // Comparing not escaping allocation.
2120       if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
2121           !ptn2->points_to(jobj1)) {
2122         return NE; // This includes nullness check.
2123       }
2124     }
2125   }
2126   if (jobj2 != NULL) {
2127     if (jobj2->escape_state() == PointsToNode::NoEscape) {
2128       Node* obj = jobj2->ideal_node();
2129       // Comparing not escaping allocation.
2130       if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
2131           !ptn1->points_to(jobj2)) {
2132         return NE; // This includes nullness check.
2133       }
2134     }
2135   }
2136   if (jobj1 != NULL && jobj1 != phantom_obj &&
2137       jobj2 != NULL && jobj2 != phantom_obj &&
2138       jobj1->ideal_node()->is_Con() &&
2139       jobj2->ideal_node()->is_Con()) {
2140     // Klass or String constants compare. Need to be careful with
2141     // compressed pointers - compare types of ConN and ConP instead of nodes.
2142     const Type* t1 = jobj1->ideal_node()->get_ptr_type();
2143     const Type* t2 = jobj2->ideal_node()->get_ptr_type();
2144     if (t1->make_ptr() == t2->make_ptr()) {
2145       return EQ;
2146     } else {
2147       return NE;
2148     }
2149   }
2150   if (ptn1->meet(ptn2)) {
2151     return UNKNOWN; // Sets are not disjoint
2152   }
2153 
2154   // Sets are disjoint.
2155   bool set1_has_unknown_ptr = ptn1->points_to(phantom_obj);
2156   bool set2_has_unknown_ptr = ptn2->points_to(phantom_obj);
2157   bool set1_has_null_ptr    = ptn1->points_to(null_obj);
2158   bool set2_has_null_ptr    = ptn2->points_to(null_obj);
2159   if ((set1_has_unknown_ptr && set2_has_null_ptr) ||
2160       (set2_has_unknown_ptr && set1_has_null_ptr)) {
2161     // Check nullness of unknown object.
2162     return UNKNOWN;
2163   }
2164 
2165   // Disjointness by itself is not sufficient since
2166   // alias analysis is not complete for escaped objects.
2167   // Disjoint sets are definitely unrelated only when
2168   // at least one set has only not escaping allocations.
2169   if (!set1_has_unknown_ptr && !set1_has_null_ptr) {
2170     if (ptn1->non_escaping_allocation()) {
2171       return NE;
2172     }
2173   }
2174   if (!set2_has_unknown_ptr && !set2_has_null_ptr) {
2175     if (ptn2->non_escaping_allocation()) {
2176       return NE;
2177     }
2178   }
2179   return UNKNOWN;
2180 }
2181 
2182 // Connection Graph construction functions.
2183 
2184 void ConnectionGraph::add_local_var(Node *n, PointsToNode::EscapeState es) {
2185   PointsToNode* ptadr = _nodes.at(n->_idx);
2186   if (ptadr != NULL) {
2187     assert(ptadr->is_LocalVar() && ptadr->ideal_node() == n, "sanity");
2188     return;
2189   }
2190   Compile* C = _compile;
2191   ptadr = new (C->comp_arena()) LocalVarNode(this, n, es);
2192   map_ideal_node(n, ptadr);
2193 }
2194 
2195 void ConnectionGraph::add_java_object(Node *n, PointsToNode::EscapeState es) {
2196   PointsToNode* ptadr = _nodes.at(n->_idx);
2197   if (ptadr != NULL) {
2198     assert(ptadr->is_JavaObject() && ptadr->ideal_node() == n, "sanity");
2199     return;
2200   }
2201   Compile* C = _compile;
2202   ptadr = new (C->comp_arena()) JavaObjectNode(this, n, es);
2203   map_ideal_node(n, ptadr);
2204 }
2205 
2206 void ConnectionGraph::add_field(Node *n, PointsToNode::EscapeState es, int offset) {
2207   PointsToNode* ptadr = _nodes.at(n->_idx);
2208   if (ptadr != NULL) {
2209     assert(ptadr->is_Field() && ptadr->ideal_node() == n, "sanity");
2210     return;
2211   }
2212   bool unsafe = false;
2213   bool is_oop = is_oop_field(n, offset, &unsafe);
2214   if (unsafe) {
2215     es = PointsToNode::GlobalEscape;
2216   }
2217   Compile* C = _compile;
2218   FieldNode* field = new (C->comp_arena()) FieldNode(this, n, es, offset, is_oop);
2219   map_ideal_node(n, field);
2220 }
2221 
2222 void ConnectionGraph::add_arraycopy(Node *n, PointsToNode::EscapeState es,
2223                                     PointsToNode* src, PointsToNode* dst) {
2224   assert(!src->is_Field() && !dst->is_Field(), "only for JavaObject and LocalVar");
2225   assert((src != null_obj) && (dst != null_obj), "not for ConP NULL");
2226   PointsToNode* ptadr = _nodes.at(n->_idx);
2227   if (ptadr != NULL) {
2228     assert(ptadr->is_Arraycopy() && ptadr->ideal_node() == n, "sanity");
2229     return;
2230   }
2231   Compile* C = _compile;
2232   ptadr = new (C->comp_arena()) ArraycopyNode(this, n, es);
2233   map_ideal_node(n, ptadr);
2234   // Add edge from arraycopy node to source object.
2235   (void)add_edge(ptadr, src);
2236   src->set_arraycopy_src();
2237   // Add edge from destination object to arraycopy node.
2238   (void)add_edge(dst, ptadr);
2239   dst->set_arraycopy_dst();
2240 }
2241 
2242 bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) {
2243   const Type* adr_type = n->as_AddP()->bottom_type();
2244   BasicType bt = T_INT;
2245   if (offset == Type::OffsetBot) {
2246     // Check only oop fields.
2247     if (!adr_type->isa_aryptr() ||
2248         adr_type->isa_aryptr()->elem() == Type::BOTTOM ||
2249         adr_type->isa_aryptr()->elem()->make_oopptr() != NULL) {
2250       // OffsetBot is used to reference array's element. Ignore first AddP.
2251       if (find_second_addp(n, n->in(AddPNode::Base)) == NULL) {
2252         bt = T_OBJECT;
2253       }
2254     }
2255   } else if (offset != oopDesc::klass_offset_in_bytes()) {
2256     if (adr_type->isa_instptr()) {
2257       ciField* field = _compile->alias_type(adr_type->isa_instptr())->field();
2258       if (field != NULL) {
2259         bt = field->layout_type();
2260       } else {
2261         // Check for unsafe oop field access
2262         if (n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN) ||
2263             n->has_out_with(Op_GetAndSetP, Op_GetAndSetN, Op_CompareAndExchangeP, Op_CompareAndExchangeN) ||
2264             n->has_out_with(Op_CompareAndSwapP, Op_CompareAndSwapN, Op_WeakCompareAndSwapP, Op_WeakCompareAndSwapN) ||
2265             BarrierSet::barrier_set()->barrier_set_c2()->escape_has_out_with_unsafe_object(n)) {
2266           bt = T_OBJECT;
2267           (*unsafe) = true;
2268         }
2269       }
2270     } else if (adr_type->isa_aryptr()) {
2271       if (offset == arrayOopDesc::length_offset_in_bytes()) {
2272         // Ignore array length load.
2273       } else if (find_second_addp(n, n->in(AddPNode::Base)) != NULL) {
2274         // Ignore first AddP.
2275       } else {
2276         const Type* elemtype = adr_type->isa_aryptr()->elem();
2277         bt = elemtype->array_element_basic_type();
2278       }
2279     } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
2280       // Allocation initialization, ThreadLocal field access, unsafe access
2281       if (n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN) ||
2282           n->has_out_with(Op_GetAndSetP, Op_GetAndSetN, Op_CompareAndExchangeP, Op_CompareAndExchangeN) ||
2283           n->has_out_with(Op_CompareAndSwapP, Op_CompareAndSwapN, Op_WeakCompareAndSwapP, Op_WeakCompareAndSwapN) ||
2284           BarrierSet::barrier_set()->barrier_set_c2()->escape_has_out_with_unsafe_object(n)) {
2285         bt = T_OBJECT;
2286       }
2287     }
2288   }
2289   // Note: T_NARROWOOP is not classed as a real reference type
2290   return (is_reference_type(bt) || bt == T_NARROWOOP);
2291 }
2292 
2293 // Returns unique pointed java object or NULL.
2294 JavaObjectNode* ConnectionGraph::unique_java_object(Node *n) {
2295   assert(!_collecting, "should not call when constructed graph");
2296   // If the node was created after the escape computation we can't answer.
2297   uint idx = n->_idx;
2298   if (idx >= nodes_size()) {
2299     return NULL;
2300   }
2301   PointsToNode* ptn = ptnode_adr(idx);
2302   if (ptn == NULL) {
2303     return NULL;
2304   }
2305   if (ptn->is_JavaObject()) {
2306     return ptn->as_JavaObject();
2307   }
2308   assert(ptn->is_LocalVar(), "sanity");
2309   // Check all java objects it points to.
2310   JavaObjectNode* jobj = NULL;
2311   for (EdgeIterator i(ptn); i.has_next(); i.next()) {
2312     PointsToNode* e = i.get();
2313     if (e->is_JavaObject()) {
2314       if (jobj == NULL) {
2315         jobj = e->as_JavaObject();
2316       } else if (jobj != e) {
2317         return NULL;
2318       }
2319     }
2320   }
2321   return jobj;
2322 }
2323 
2324 // Return true if this node points only to non-escaping allocations.
2325 bool PointsToNode::non_escaping_allocation() {
2326   if (is_JavaObject()) {
2327     Node* n = ideal_node();
2328     if (n->is_Allocate() || n->is_CallStaticJava()) {
2329       return (escape_state() == PointsToNode::NoEscape);
2330     } else {
2331       return false;
2332     }
2333   }
2334   assert(is_LocalVar(), "sanity");
2335   // Check all java objects it points to.
2336   for (EdgeIterator i(this); i.has_next(); i.next()) {
2337     PointsToNode* e = i.get();
2338     if (e->is_JavaObject()) {
2339       Node* n = e->ideal_node();
2340       if ((e->escape_state() != PointsToNode::NoEscape) ||
2341           !(n->is_Allocate() || n->is_CallStaticJava())) {
2342         return false;
2343       }
2344     }
2345   }
2346   return true;
2347 }
2348 
2349 // Return true if we know the node does not escape globally.
2350 bool ConnectionGraph::not_global_escape(Node *n) {
2351   assert(!_collecting, "should not call during graph construction");
2352   // If the node was created after the escape computation we can't answer.
2353   uint idx = n->_idx;
2354   if (idx >= nodes_size()) {
2355     return false;
2356   }
2357   PointsToNode* ptn = ptnode_adr(idx);
2358   if (ptn == NULL) {
2359     return false; // not in congraph (e.g. ConI)
2360   }
2361   PointsToNode::EscapeState es = ptn->escape_state();
2362   // If we have already computed a value, return it.
2363   if (es >= PointsToNode::GlobalEscape) {
2364     return false;
2365   }
2366   if (ptn->is_JavaObject()) {
2367     return true; // (es < PointsToNode::GlobalEscape);
2368   }
2369   assert(ptn->is_LocalVar(), "sanity");
2370   // Check all java objects it points to.
2371   for (EdgeIterator i(ptn); i.has_next(); i.next()) {
2372     if (i.get()->escape_state() >= PointsToNode::GlobalEscape) {
2373       return false;
2374     }
2375   }
2376   return true;
2377 }
2378 
2379 
2380 // Helper functions
2381 
2382 // Return true if this node points to specified node or nodes it points to.
2383 bool PointsToNode::points_to(JavaObjectNode* ptn) const {
2384   if (is_JavaObject()) {
2385     return (this == ptn);
2386   }
2387   assert(is_LocalVar() || is_Field(), "sanity");
2388   for (EdgeIterator i(this); i.has_next(); i.next()) {
2389     if (i.get() == ptn) {
2390       return true;
2391     }
2392   }
2393   return false;
2394 }
2395 
2396 // Return true if one node points to an other.
2397 bool PointsToNode::meet(PointsToNode* ptn) {
2398   if (this == ptn) {
2399     return true;
2400   } else if (ptn->is_JavaObject()) {
2401     return this->points_to(ptn->as_JavaObject());
2402   } else if (this->is_JavaObject()) {
2403     return ptn->points_to(this->as_JavaObject());
2404   }
2405   assert(this->is_LocalVar() && ptn->is_LocalVar(), "sanity");
2406   int ptn_count =  ptn->edge_count();
2407   for (EdgeIterator i(this); i.has_next(); i.next()) {
2408     PointsToNode* this_e = i.get();
2409     for (int j = 0; j < ptn_count; j++) {
2410       if (this_e == ptn->edge(j)) {
2411         return true;
2412       }
2413     }
2414   }
2415   return false;
2416 }
2417 
2418 #ifdef ASSERT
2419 // Return true if bases point to this java object.
2420 bool FieldNode::has_base(JavaObjectNode* jobj) const {
2421   for (BaseIterator i(this); i.has_next(); i.next()) {
2422     if (i.get() == jobj) {
2423       return true;
2424     }
2425   }
2426   return false;
2427 }
2428 #endif
2429 
2430 bool ConnectionGraph::is_captured_store_address(Node* addp) {
2431   // Handle simple case first.
2432   assert(_igvn->type(addp)->isa_oopptr() == NULL, "should be raw access");
2433   if (addp->in(AddPNode::Address)->is_Proj() && addp->in(AddPNode::Address)->in(0)->is_Allocate()) {
2434     return true;
2435   } else if (addp->in(AddPNode::Address)->is_Phi()) {
2436     for (DUIterator_Fast imax, i = addp->fast_outs(imax); i < imax; i++) {
2437       Node* addp_use = addp->fast_out(i);
2438       if (addp_use->is_Store()) {
2439         for (DUIterator_Fast jmax, j = addp_use->fast_outs(jmax); j < jmax; j++) {
2440           if (addp_use->fast_out(j)->is_Initialize()) {
2441             return true;
2442           }
2443         }
2444       }
2445     }
2446   }
2447   return false;
2448 }
2449 
2450 int ConnectionGraph::address_offset(Node* adr, PhaseTransform *phase) {
2451   const Type *adr_type = phase->type(adr);
2452   if (adr->is_AddP() && adr_type->isa_oopptr() == NULL && is_captured_store_address(adr)) {
2453     // We are computing a raw address for a store captured by an Initialize
2454     // compute an appropriate address type. AddP cases #3 and #5 (see below).
2455     int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
2456     assert(offs != Type::OffsetBot ||
2457            adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
2458            "offset must be a constant or it is initialization of array");
2459     return offs;
2460   }
2461   const TypePtr *t_ptr = adr_type->isa_ptr();
2462   assert(t_ptr != NULL, "must be a pointer type");
2463   return t_ptr->offset();
2464 }
2465 
2466 Node* ConnectionGraph::get_addp_base(Node *addp) {
2467   assert(addp->is_AddP(), "must be AddP");
2468   //
2469   // AddP cases for Base and Address inputs:
2470   // case #1. Direct object's field reference:
2471   //     Allocate
2472   //       |
2473   //     Proj #5 ( oop result )
2474   //       |
2475   //     CheckCastPP (cast to instance type)
2476   //      | |
2477   //     AddP  ( base == address )
2478   //
2479   // case #2. Indirect object's field reference:
2480   //      Phi
2481   //       |
2482   //     CastPP (cast to instance type)
2483   //      | |
2484   //     AddP  ( base == address )
2485   //
2486   // case #3. Raw object's field reference for Initialize node:
2487   //      Allocate
2488   //        |
2489   //      Proj #5 ( oop result )
2490   //  top   |
2491   //     \  |
2492   //     AddP  ( base == top )
2493   //
2494   // case #4. Array's element reference:
2495   //   {CheckCastPP | CastPP}
2496   //     |  | |
2497   //     |  AddP ( array's element offset )
2498   //     |  |
2499   //     AddP ( array's offset )
2500   //
2501   // case #5. Raw object's field reference for arraycopy stub call:
2502   //          The inline_native_clone() case when the arraycopy stub is called
2503   //          after the allocation before Initialize and CheckCastPP nodes.
2504   //      Allocate
2505   //        |
2506   //      Proj #5 ( oop result )
2507   //       | |
2508   //       AddP  ( base == address )
2509   //
2510   // case #6. Constant Pool, ThreadLocal, CastX2P or
2511   //          Raw object's field reference:
2512   //      {ConP, ThreadLocal, CastX2P, raw Load}
2513   //  top   |
2514   //     \  |
2515   //     AddP  ( base == top )
2516   //
2517   // case #7. Klass's field reference.
2518   //      LoadKlass
2519   //       | |
2520   //       AddP  ( base == address )
2521   //
2522   // case #8. narrow Klass's field reference.
2523   //      LoadNKlass
2524   //       |
2525   //      DecodeN
2526   //       | |
2527   //       AddP  ( base == address )
2528   //
2529   // case #9. Mixed unsafe access
2530   //    {instance}
2531   //        |
2532   //      CheckCastPP (raw)
2533   //  top   |
2534   //     \  |
2535   //     AddP  ( base == top )
2536   //
2537   Node *base = addp->in(AddPNode::Base);
2538   if (base->uncast()->is_top()) { // The AddP case #3 and #6 and #9.
2539     base = addp->in(AddPNode::Address);
2540     while (base->is_AddP()) {
2541       // Case #6 (unsafe access) may have several chained AddP nodes.
2542       assert(base->in(AddPNode::Base)->uncast()->is_top(), "expected unsafe access address only");
2543       base = base->in(AddPNode::Address);
2544     }
2545     if (base->Opcode() == Op_CheckCastPP &&
2546         base->bottom_type()->isa_rawptr() &&
2547         _igvn->type(base->in(1))->isa_oopptr()) {
2548       base = base->in(1); // Case #9
2549     } else {
2550       Node* uncast_base = base->uncast();
2551       int opcode = uncast_base->Opcode();
2552       assert(opcode == Op_ConP || opcode == Op_ThreadLocal ||
2553              opcode == Op_CastX2P || uncast_base->is_DecodeNarrowPtr() ||
2554              (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_rawptr() != NULL)) ||
2555              is_captured_store_address(addp), "sanity");
2556     }
2557   }
2558   return base;
2559 }
2560 
2561 Node* ConnectionGraph::find_second_addp(Node* addp, Node* n) {
2562   assert(addp->is_AddP() && addp->outcnt() > 0, "Don't process dead nodes");
2563   Node* addp2 = addp->raw_out(0);
2564   if (addp->outcnt() == 1 && addp2->is_AddP() &&
2565       addp2->in(AddPNode::Base) == n &&
2566       addp2->in(AddPNode::Address) == addp) {
2567     assert(addp->in(AddPNode::Base) == n, "expecting the same base");
2568     //
2569     // Find array's offset to push it on worklist first and
2570     // as result process an array's element offset first (pushed second)
2571     // to avoid CastPP for the array's offset.
2572     // Otherwise the inserted CastPP (LocalVar) will point to what
2573     // the AddP (Field) points to. Which would be wrong since
2574     // the algorithm expects the CastPP has the same point as
2575     // as AddP's base CheckCastPP (LocalVar).
2576     //
2577     //    ArrayAllocation
2578     //     |
2579     //    CheckCastPP
2580     //     |
2581     //    memProj (from ArrayAllocation CheckCastPP)
2582     //     |  ||
2583     //     |  ||   Int (element index)
2584     //     |  ||    |   ConI (log(element size))
2585     //     |  ||    |   /
2586     //     |  ||   LShift
2587     //     |  ||  /
2588     //     |  AddP (array's element offset)
2589     //     |  |
2590     //     |  | ConI (array's offset: #12(32-bits) or #24(64-bits))
2591     //     | / /
2592     //     AddP (array's offset)
2593     //      |
2594     //     Load/Store (memory operation on array's element)
2595     //
2596     return addp2;
2597   }
2598   return NULL;
2599 }
2600 
2601 //
2602 // Adjust the type and inputs of an AddP which computes the
2603 // address of a field of an instance
2604 //
2605 bool ConnectionGraph::split_AddP(Node *addp, Node *base) {
2606   PhaseGVN* igvn = _igvn;
2607   const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
2608   assert(base_t != NULL && base_t->is_known_instance(), "expecting instance oopptr");
2609   const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
2610   if (t == NULL) {
2611     // We are computing a raw address for a store captured by an Initialize
2612     // compute an appropriate address type (cases #3 and #5).
2613     assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
2614     assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
2615     intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
2616     assert(offs != Type::OffsetBot, "offset must be a constant");
2617     t = base_t->add_offset(offs)->is_oopptr();
2618   }
2619   int inst_id =  base_t->instance_id();
2620   assert(!t->is_known_instance() || t->instance_id() == inst_id,
2621                              "old type must be non-instance or match new type");
2622 
2623   // The type 't' could be subclass of 'base_t'.
2624   // As result t->offset() could be large then base_t's size and it will
2625   // cause the failure in add_offset() with narrow oops since TypeOopPtr()
2626   // constructor verifies correctness of the offset.
2627   //
2628   // It could happened on subclass's branch (from the type profiling
2629   // inlining) which was not eliminated during parsing since the exactness
2630   // of the allocation type was not propagated to the subclass type check.
2631   //
2632   // Or the type 't' could be not related to 'base_t' at all.
2633   // It could happened when CHA type is different from MDO type on a dead path
2634   // (for example, from instanceof check) which is not collapsed during parsing.
2635   //
2636   // Do nothing for such AddP node and don't process its users since
2637   // this code branch will go away.
2638   //
2639   if (!t->is_known_instance() &&
2640       !base_t->maybe_java_subtype_of(t)) {
2641      return false; // bail out
2642   }
2643   const TypeOopPtr *tinst = base_t->add_offset(t->offset())->is_oopptr();
2644   // Do NOT remove the next line: ensure a new alias index is allocated
2645   // for the instance type. Note: C++ will not remove it since the call
2646   // has side effect.
2647   int alias_idx = _compile->get_alias_index(tinst);
2648   igvn->set_type(addp, tinst);
2649   // record the allocation in the node map
2650   set_map(addp, get_map(base->_idx));
2651   // Set addp's Base and Address to 'base'.
2652   Node *abase = addp->in(AddPNode::Base);
2653   Node *adr   = addp->in(AddPNode::Address);
2654   if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
2655       adr->in(0)->_idx == (uint)inst_id) {
2656     // Skip AddP cases #3 and #5.
2657   } else {
2658     assert(!abase->is_top(), "sanity"); // AddP case #3
2659     if (abase != base) {
2660       igvn->hash_delete(addp);
2661       addp->set_req(AddPNode::Base, base);
2662       if (abase == adr) {
2663         addp->set_req(AddPNode::Address, base);
2664       } else {
2665         // AddP case #4 (adr is array's element offset AddP node)
2666 #ifdef ASSERT
2667         const TypeOopPtr *atype = igvn->type(adr)->isa_oopptr();
2668         assert(adr->is_AddP() && atype != NULL &&
2669                atype->instance_id() == inst_id, "array's element offset should be processed first");
2670 #endif
2671       }
2672       igvn->hash_insert(addp);
2673     }
2674   }
2675   // Put on IGVN worklist since at least addp's type was changed above.
2676   record_for_optimizer(addp);
2677   return true;
2678 }
2679 
2680 //
2681 // Create a new version of orig_phi if necessary. Returns either the newly
2682 // created phi or an existing phi.  Sets create_new to indicate whether a new
2683 // phi was created.  Cache the last newly created phi in the node map.
2684 //
2685 PhiNode *ConnectionGraph::create_split_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist, bool &new_created) {
2686   Compile *C = _compile;
2687   PhaseGVN* igvn = _igvn;
2688   new_created = false;
2689   int phi_alias_idx = C->get_alias_index(orig_phi->adr_type());
2690   // nothing to do if orig_phi is bottom memory or matches alias_idx
2691   if (phi_alias_idx == alias_idx) {
2692     return orig_phi;
2693   }
2694   // Have we recently created a Phi for this alias index?
2695   PhiNode *result = get_map_phi(orig_phi->_idx);
2696   if (result != NULL && C->get_alias_index(result->adr_type()) == alias_idx) {
2697     return result;
2698   }
2699   // Previous check may fail when the same wide memory Phi was split into Phis
2700   // for different memory slices. Search all Phis for this region.
2701   if (result != NULL) {
2702     Node* region = orig_phi->in(0);
2703     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
2704       Node* phi = region->fast_out(i);
2705       if (phi->is_Phi() &&
2706           C->get_alias_index(phi->as_Phi()->adr_type()) == alias_idx) {
2707         assert(phi->_idx >= nodes_size(), "only new Phi per instance memory slice");
2708         return phi->as_Phi();
2709       }
2710     }
2711   }
2712   if (C->live_nodes() + 2*NodeLimitFudgeFactor > C->max_node_limit()) {
2713     if (C->do_escape_analysis() == true && !C->failing()) {
2714       // Retry compilation without escape analysis.
2715       // If this is the first failure, the sentinel string will "stick"
2716       // to the Compile object, and the C2Compiler will see it and retry.
2717       C->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
2718     }
2719     return NULL;
2720   }
2721   orig_phi_worklist.append_if_missing(orig_phi);
2722   const TypePtr *atype = C->get_adr_type(alias_idx);
2723   result = PhiNode::make(orig_phi->in(0), NULL, Type::MEMORY, atype);
2724   C->copy_node_notes_to(result, orig_phi);
2725   igvn->set_type(result, result->bottom_type());
2726   record_for_optimizer(result);
2727   set_map(orig_phi, result);
2728   new_created = true;
2729   return result;
2730 }
2731 
2732 //
2733 // Return a new version of Memory Phi "orig_phi" with the inputs having the
2734 // specified alias index.
2735 //
2736 PhiNode *ConnectionGraph::split_memory_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist) {
2737   assert(alias_idx != Compile::AliasIdxBot, "can't split out bottom memory");
2738   Compile *C = _compile;
2739   PhaseGVN* igvn = _igvn;
2740   bool new_phi_created;
2741   PhiNode *result = create_split_phi(orig_phi, alias_idx, orig_phi_worklist, new_phi_created);
2742   if (!new_phi_created) {
2743     return result;
2744   }
2745   GrowableArray<PhiNode *>  phi_list;
2746   GrowableArray<uint>  cur_input;
2747   PhiNode *phi = orig_phi;
2748   uint idx = 1;
2749   bool finished = false;
2750   while(!finished) {
2751     while (idx < phi->req()) {
2752       Node *mem = find_inst_mem(phi->in(idx), alias_idx, orig_phi_worklist);
2753       if (mem != NULL && mem->is_Phi()) {
2754         PhiNode *newphi = create_split_phi(mem->as_Phi(), alias_idx, orig_phi_worklist, new_phi_created);
2755         if (new_phi_created) {
2756           // found an phi for which we created a new split, push current one on worklist and begin
2757           // processing new one
2758           phi_list.push(phi);
2759           cur_input.push(idx);
2760           phi = mem->as_Phi();
2761           result = newphi;
2762           idx = 1;
2763           continue;
2764         } else {
2765           mem = newphi;
2766         }
2767       }
2768       if (C->failing()) {
2769         return NULL;
2770       }
2771       result->set_req(idx++, mem);
2772     }
2773 #ifdef ASSERT
2774     // verify that the new Phi has an input for each input of the original
2775     assert( phi->req() == result->req(), "must have same number of inputs.");
2776     assert( result->in(0) != NULL && result->in(0) == phi->in(0), "regions must match");
2777 #endif
2778     // Check if all new phi's inputs have specified alias index.
2779     // Otherwise use old phi.
2780     for (uint i = 1; i < phi->req(); i++) {
2781       Node* in = result->in(i);
2782       assert((phi->in(i) == NULL) == (in == NULL), "inputs must correspond.");
2783     }
2784     // we have finished processing a Phi, see if there are any more to do
2785     finished = (phi_list.length() == 0 );
2786     if (!finished) {
2787       phi = phi_list.pop();
2788       idx = cur_input.pop();
2789       PhiNode *prev_result = get_map_phi(phi->_idx);
2790       prev_result->set_req(idx++, result);
2791       result = prev_result;
2792     }
2793   }
2794   return result;
2795 }
2796 
2797 //
2798 // The next methods are derived from methods in MemNode.
2799 //
2800 Node* ConnectionGraph::step_through_mergemem(MergeMemNode *mmem, int alias_idx, const TypeOopPtr *toop) {
2801   Node *mem = mmem;
2802   // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
2803   // means an array I have not precisely typed yet.  Do not do any
2804   // alias stuff with it any time soon.
2805   if (toop->base() != Type::AnyPtr &&
2806       !(toop->isa_instptr() &&
2807         toop->is_instptr()->instance_klass()->is_java_lang_Object() &&
2808         toop->offset() == Type::OffsetBot)) {
2809     mem = mmem->memory_at(alias_idx);
2810     // Update input if it is progress over what we have now
2811   }
2812   return mem;
2813 }
2814 
2815 //
2816 // Move memory users to their memory slices.
2817 //
2818 void ConnectionGraph::move_inst_mem(Node* n, GrowableArray<PhiNode *>  &orig_phis) {
2819   Compile* C = _compile;
2820   PhaseGVN* igvn = _igvn;
2821   const TypePtr* tp = igvn->type(n->in(MemNode::Address))->isa_ptr();
2822   assert(tp != NULL, "ptr type");
2823   int alias_idx = C->get_alias_index(tp);
2824   int general_idx = C->get_general_index(alias_idx);
2825 
2826   // Move users first
2827   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2828     Node* use = n->fast_out(i);
2829     if (use->is_MergeMem()) {
2830       MergeMemNode* mmem = use->as_MergeMem();
2831       assert(n == mmem->memory_at(alias_idx), "should be on instance memory slice");
2832       if (n != mmem->memory_at(general_idx) || alias_idx == general_idx) {
2833         continue; // Nothing to do
2834       }
2835       // Replace previous general reference to mem node.
2836       uint orig_uniq = C->unique();
2837       Node* m = find_inst_mem(n, general_idx, orig_phis);
2838       assert(orig_uniq == C->unique(), "no new nodes");
2839       mmem->set_memory_at(general_idx, m);
2840       --imax;
2841       --i;
2842     } else if (use->is_MemBar()) {
2843       assert(!use->is_Initialize(), "initializing stores should not be moved");
2844       if (use->req() > MemBarNode::Precedent &&
2845           use->in(MemBarNode::Precedent) == n) {
2846         // Don't move related membars.
2847         record_for_optimizer(use);
2848         continue;
2849       }
2850       tp = use->as_MemBar()->adr_type()->isa_ptr();
2851       if ((tp != NULL && C->get_alias_index(tp) == alias_idx) ||
2852           alias_idx == general_idx) {
2853         continue; // Nothing to do
2854       }
2855       // Move to general memory slice.
2856       uint orig_uniq = C->unique();
2857       Node* m = find_inst_mem(n, general_idx, orig_phis);
2858       assert(orig_uniq == C->unique(), "no new nodes");
2859       igvn->hash_delete(use);
2860       imax -= use->replace_edge(n, m, igvn);
2861       igvn->hash_insert(use);
2862       record_for_optimizer(use);
2863       --i;
2864 #ifdef ASSERT
2865     } else if (use->is_Mem()) {
2866       if (use->Opcode() == Op_StoreCM && use->in(MemNode::OopStore) == n) {
2867         // Don't move related cardmark.
2868         continue;
2869       }
2870       // Memory nodes should have new memory input.
2871       tp = igvn->type(use->in(MemNode::Address))->isa_ptr();
2872       assert(tp != NULL, "ptr type");
2873       int idx = C->get_alias_index(tp);
2874       assert(get_map(use->_idx) != NULL || idx == alias_idx,
2875              "Following memory nodes should have new memory input or be on the same memory slice");
2876     } else if (use->is_Phi()) {
2877       // Phi nodes should be split and moved already.
2878       tp = use->as_Phi()->adr_type()->isa_ptr();
2879       assert(tp != NULL, "ptr type");
2880       int idx = C->get_alias_index(tp);
2881       assert(idx == alias_idx, "Following Phi nodes should be on the same memory slice");
2882     } else {
2883       use->dump();
2884       assert(false, "should not be here");
2885 #endif
2886     }
2887   }
2888 }
2889 
2890 //
2891 // Search memory chain of "mem" to find a MemNode whose address
2892 // is the specified alias index.
2893 //
2894 Node* ConnectionGraph::find_inst_mem(Node *orig_mem, int alias_idx, GrowableArray<PhiNode *>  &orig_phis) {
2895   if (orig_mem == NULL) {
2896     return orig_mem;
2897   }
2898   Compile* C = _compile;
2899   PhaseGVN* igvn = _igvn;
2900   const TypeOopPtr *toop = C->get_adr_type(alias_idx)->isa_oopptr();
2901   bool is_instance = (toop != NULL) && toop->is_known_instance();
2902   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
2903   Node *prev = NULL;
2904   Node *result = orig_mem;
2905   while (prev != result) {
2906     prev = result;
2907     if (result == start_mem) {
2908       break;  // hit one of our sentinels
2909     }
2910     if (result->is_Mem()) {
2911       const Type *at = igvn->type(result->in(MemNode::Address));
2912       if (at == Type::TOP) {
2913         break; // Dead
2914       }
2915       assert (at->isa_ptr() != NULL, "pointer type required.");
2916       int idx = C->get_alias_index(at->is_ptr());
2917       if (idx == alias_idx) {
2918         break; // Found
2919       }
2920       if (!is_instance && (at->isa_oopptr() == NULL ||
2921                            !at->is_oopptr()->is_known_instance())) {
2922         break; // Do not skip store to general memory slice.
2923       }
2924       result = result->in(MemNode::Memory);
2925     }
2926     if (!is_instance) {
2927       continue;  // don't search further for non-instance types
2928     }
2929     // skip over a call which does not affect this memory slice
2930     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
2931       Node *proj_in = result->in(0);
2932       if (proj_in->is_Allocate() && proj_in->_idx == (uint)toop->instance_id()) {
2933         break;  // hit one of our sentinels
2934       } else if (proj_in->is_Call()) {
2935         // ArrayCopy node processed here as well
2936         CallNode *call = proj_in->as_Call();
2937         if (!call->may_modify(toop, igvn)) {
2938           result = call->in(TypeFunc::Memory);
2939         }
2940       } else if (proj_in->is_Initialize()) {
2941         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
2942         // Stop if this is the initialization for the object instance which
2943         // which contains this memory slice, otherwise skip over it.
2944         if (alloc == NULL || alloc->_idx != (uint)toop->instance_id()) {
2945           result = proj_in->in(TypeFunc::Memory);
2946         }
2947       } else if (proj_in->is_MemBar()) {
2948         // Check if there is an array copy for a clone
2949         // Step over GC barrier when ReduceInitialCardMarks is disabled
2950         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2951         Node* control_proj_ac = bs->step_over_gc_barrier(proj_in->in(0));
2952 
2953         if (control_proj_ac->is_Proj() && control_proj_ac->in(0)->is_ArrayCopy()) {
2954           // Stop if it is a clone
2955           ArrayCopyNode* ac = control_proj_ac->in(0)->as_ArrayCopy();
2956           if (ac->may_modify(toop, igvn)) {
2957             break;
2958           }
2959         }
2960         result = proj_in->in(TypeFunc::Memory);
2961       }
2962     } else if (result->is_MergeMem()) {
2963       MergeMemNode *mmem = result->as_MergeMem();
2964       result = step_through_mergemem(mmem, alias_idx, toop);
2965       if (result == mmem->base_memory()) {
2966         // Didn't find instance memory, search through general slice recursively.
2967         result = mmem->memory_at(C->get_general_index(alias_idx));
2968         result = find_inst_mem(result, alias_idx, orig_phis);
2969         if (C->failing()) {
2970           return NULL;
2971         }
2972         mmem->set_memory_at(alias_idx, result);
2973       }
2974     } else if (result->is_Phi() &&
2975                C->get_alias_index(result->as_Phi()->adr_type()) != alias_idx) {
2976       Node *un = result->as_Phi()->unique_input(igvn);
2977       if (un != NULL) {
2978         orig_phis.append_if_missing(result->as_Phi());
2979         result = un;
2980       } else {
2981         break;
2982       }
2983     } else if (result->is_ClearArray()) {
2984       if (!ClearArrayNode::step_through(&result, (uint)toop->instance_id(), igvn)) {
2985         // Can not bypass initialization of the instance
2986         // we are looking for.
2987         break;
2988       }
2989       // Otherwise skip it (the call updated 'result' value).
2990     } else if (result->Opcode() == Op_SCMemProj) {
2991       Node* mem = result->in(0);
2992       Node* adr = NULL;
2993       if (mem->is_LoadStore()) {
2994         adr = mem->in(MemNode::Address);
2995       } else {
2996         assert(mem->Opcode() == Op_EncodeISOArray ||
2997                mem->Opcode() == Op_StrCompressedCopy, "sanity");
2998         adr = mem->in(3); // Memory edge corresponds to destination array
2999       }
3000       const Type *at = igvn->type(adr);
3001       if (at != Type::TOP) {
3002         assert(at->isa_ptr() != NULL, "pointer type required.");
3003         int idx = C->get_alias_index(at->is_ptr());
3004         if (idx == alias_idx) {
3005           // Assert in debug mode
3006           assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
3007           break; // In product mode return SCMemProj node
3008         }
3009       }
3010       result = mem->in(MemNode::Memory);
3011     } else if (result->Opcode() == Op_StrInflatedCopy) {
3012       Node* adr = result->in(3); // Memory edge corresponds to destination array
3013       const Type *at = igvn->type(adr);
3014       if (at != Type::TOP) {
3015         assert(at->isa_ptr() != NULL, "pointer type required.");
3016         int idx = C->get_alias_index(at->is_ptr());
3017         if (idx == alias_idx) {
3018           // Assert in debug mode
3019           assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
3020           break; // In product mode return SCMemProj node
3021         }
3022       }
3023       result = result->in(MemNode::Memory);
3024     }
3025   }
3026   if (result->is_Phi()) {
3027     PhiNode *mphi = result->as_Phi();
3028     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
3029     const TypePtr *t = mphi->adr_type();
3030     if (!is_instance) {
3031       // Push all non-instance Phis on the orig_phis worklist to update inputs
3032       // during Phase 4 if needed.
3033       orig_phis.append_if_missing(mphi);
3034     } else if (C->get_alias_index(t) != alias_idx) {
3035       // Create a new Phi with the specified alias index type.
3036       result = split_memory_phi(mphi, alias_idx, orig_phis);
3037     }
3038   }
3039   // the result is either MemNode, PhiNode, InitializeNode.
3040   return result;
3041 }
3042 
3043 //
3044 //  Convert the types of non-escaped object to instance types where possible,
3045 //  propagate the new type information through the graph, and update memory
3046 //  edges and MergeMem inputs to reflect the new type.
3047 //
3048 //  We start with allocations (and calls which may be allocations)  on alloc_worklist.
3049 //  The processing is done in 4 phases:
3050 //
3051 //  Phase 1:  Process possible allocations from alloc_worklist.  Create instance
3052 //            types for the CheckCastPP for allocations where possible.
3053 //            Propagate the new types through users as follows:
3054 //               casts and Phi:  push users on alloc_worklist
3055 //               AddP:  cast Base and Address inputs to the instance type
3056 //                      push any AddP users on alloc_worklist and push any memnode
3057 //                      users onto memnode_worklist.
3058 //  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
3059 //            search the Memory chain for a store with the appropriate type
3060 //            address type.  If a Phi is found, create a new version with
3061 //            the appropriate memory slices from each of the Phi inputs.
3062 //            For stores, process the users as follows:
3063 //               MemNode:  push on memnode_worklist
3064 //               MergeMem: push on mergemem_worklist
3065 //  Phase 3:  Process MergeMem nodes from mergemem_worklist.  Walk each memory slice
3066 //            moving the first node encountered of each  instance type to the
3067 //            the input corresponding to its alias index.
3068 //            appropriate memory slice.
3069 //  Phase 4:  Update the inputs of non-instance memory Phis and the Memory input of memnodes.
3070 //
3071 // In the following example, the CheckCastPP nodes are the cast of allocation
3072 // results and the allocation of node 29 is non-escaped and eligible to be an
3073 // instance type.
3074 //
3075 // We start with:
3076 //
3077 //     7 Parm #memory
3078 //    10  ConI  "12"
3079 //    19  CheckCastPP   "Foo"
3080 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
3081 //    29  CheckCastPP   "Foo"
3082 //    30  AddP  _ 29 29 10  Foo+12  alias_index=4
3083 //
3084 //    40  StoreP  25   7  20   ... alias_index=4
3085 //    50  StoreP  35  40  30   ... alias_index=4
3086 //    60  StoreP  45  50  20   ... alias_index=4
3087 //    70  LoadP    _  60  30   ... alias_index=4
3088 //    80  Phi     75  50  60   Memory alias_index=4
3089 //    90  LoadP    _  80  30   ... alias_index=4
3090 //   100  LoadP    _  80  20   ... alias_index=4
3091 //
3092 //
3093 // Phase 1 creates an instance type for node 29 assigning it an instance id of 24
3094 // and creating a new alias index for node 30.  This gives:
3095 //
3096 //     7 Parm #memory
3097 //    10  ConI  "12"
3098 //    19  CheckCastPP   "Foo"
3099 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
3100 //    29  CheckCastPP   "Foo"  iid=24
3101 //    30  AddP  _ 29 29 10  Foo+12  alias_index=6  iid=24
3102 //
3103 //    40  StoreP  25   7  20   ... alias_index=4
3104 //    50  StoreP  35  40  30   ... alias_index=6
3105 //    60  StoreP  45  50  20   ... alias_index=4
3106 //    70  LoadP    _  60  30   ... alias_index=6
3107 //    80  Phi     75  50  60   Memory alias_index=4
3108 //    90  LoadP    _  80  30   ... alias_index=6
3109 //   100  LoadP    _  80  20   ... alias_index=4
3110 //
3111 // In phase 2, new memory inputs are computed for the loads and stores,
3112 // And a new version of the phi is created.  In phase 4, the inputs to
3113 // node 80 are updated and then the memory nodes are updated with the
3114 // values computed in phase 2.  This results in:
3115 //
3116 //     7 Parm #memory
3117 //    10  ConI  "12"
3118 //    19  CheckCastPP   "Foo"
3119 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
3120 //    29  CheckCastPP   "Foo"  iid=24
3121 //    30  AddP  _ 29 29 10  Foo+12  alias_index=6  iid=24
3122 //
3123 //    40  StoreP  25  7   20   ... alias_index=4
3124 //    50  StoreP  35  7   30   ... alias_index=6
3125 //    60  StoreP  45  40  20   ... alias_index=4
3126 //    70  LoadP    _  50  30   ... alias_index=6
3127 //    80  Phi     75  40  60   Memory alias_index=4
3128 //   120  Phi     75  50  50   Memory alias_index=6
3129 //    90  LoadP    _ 120  30   ... alias_index=6
3130 //   100  LoadP    _  80  20   ... alias_index=4
3131 //
3132 void ConnectionGraph::split_unique_types(GrowableArray<Node *>  &alloc_worklist,
3133                                          GrowableArray<ArrayCopyNode*> &arraycopy_worklist,
3134                                          GrowableArray<MergeMemNode*> &mergemem_worklist) {
3135   GrowableArray<Node *>  memnode_worklist;
3136   GrowableArray<PhiNode *>  orig_phis;
3137   PhaseIterGVN  *igvn = _igvn;
3138   uint new_index_start = (uint) _compile->num_alias_types();
3139   VectorSet visited;
3140   ideal_nodes.clear(); // Reset for use with set_map/get_map.
3141   uint unique_old = _compile->unique();
3142 
3143   //  Phase 1:  Process possible allocations from alloc_worklist.
3144   //  Create instance types for the CheckCastPP for allocations where possible.
3145   //
3146   // (Note: don't forget to change the order of the second AddP node on
3147   //  the alloc_worklist if the order of the worklist processing is changed,
3148   //  see the comment in find_second_addp().)
3149   //
3150   while (alloc_worklist.length() != 0) {
3151     Node *n = alloc_worklist.pop();
3152     uint ni = n->_idx;
3153     if (n->is_Call()) {
3154       CallNode *alloc = n->as_Call();
3155       // copy escape information to call node
3156       PointsToNode* ptn = ptnode_adr(alloc->_idx);
3157       PointsToNode::EscapeState es = ptn->escape_state();
3158       // We have an allocation or call which returns a Java object,
3159       // see if it is non-escaped.
3160       if (es != PointsToNode::NoEscape || !ptn->scalar_replaceable()) {
3161         continue;
3162       }
3163       // Find CheckCastPP for the allocate or for the return value of a call
3164       n = alloc->result_cast();
3165       if (n == NULL) {            // No uses except Initialize node
3166         if (alloc->is_Allocate()) {
3167           // Set the scalar_replaceable flag for allocation
3168           // so it could be eliminated if it has no uses.
3169           alloc->as_Allocate()->_is_scalar_replaceable = true;
3170         }
3171         continue;
3172       }
3173       if (!n->is_CheckCastPP()) { // not unique CheckCastPP.
3174         // we could reach here for allocate case if one init is associated with many allocs.
3175         if (alloc->is_Allocate()) {
3176           alloc->as_Allocate()->_is_scalar_replaceable = false;
3177         }
3178         continue;
3179       }
3180 
3181       // The inline code for Object.clone() casts the allocation result to
3182       // java.lang.Object and then to the actual type of the allocated
3183       // object. Detect this case and use the second cast.
3184       // Also detect j.l.reflect.Array.newInstance(jobject, jint) case when
3185       // the allocation result is cast to java.lang.Object and then
3186       // to the actual Array type.
3187       if (alloc->is_Allocate() && n->as_Type()->type() == TypeInstPtr::NOTNULL
3188           && (alloc->is_AllocateArray() ||
3189               igvn->type(alloc->in(AllocateNode::KlassNode)) != TypeInstKlassPtr::OBJECT)) {
3190         Node *cast2 = NULL;
3191         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3192           Node *use = n->fast_out(i);
3193           if (use->is_CheckCastPP()) {
3194             cast2 = use;
3195             break;
3196           }
3197         }
3198         if (cast2 != NULL) {
3199           n = cast2;
3200         } else {
3201           // Non-scalar replaceable if the allocation type is unknown statically
3202           // (reflection allocation), the object can't be restored during
3203           // deoptimization without precise type.
3204           continue;
3205         }
3206       }
3207 
3208       const TypeOopPtr *t = igvn->type(n)->isa_oopptr();
3209       if (t == NULL) {
3210         continue;  // not a TypeOopPtr
3211       }
3212       if (!t->klass_is_exact()) {
3213         continue; // not an unique type
3214       }
3215       if (alloc->is_Allocate()) {
3216         // Set the scalar_replaceable flag for allocation
3217         // so it could be eliminated.
3218         alloc->as_Allocate()->_is_scalar_replaceable = true;
3219       }
3220       set_escape_state(ptnode_adr(n->_idx), es NOT_PRODUCT(COMMA trace_propagate_message(ptn))); // CheckCastPP escape state
3221       // in order for an object to be scalar-replaceable, it must be:
3222       //   - a direct allocation (not a call returning an object)
3223       //   - non-escaping
3224       //   - eligible to be a unique type
3225       //   - not determined to be ineligible by escape analysis
3226       set_map(alloc, n);
3227       set_map(n, alloc);
3228       const TypeOopPtr* tinst = t->cast_to_instance_id(ni);
3229       igvn->hash_delete(n);
3230       igvn->set_type(n,  tinst);
3231       n->raise_bottom_type(tinst);
3232       igvn->hash_insert(n);
3233       record_for_optimizer(n);
3234       // Allocate an alias index for the header fields. Accesses to
3235       // the header emitted during macro expansion wouldn't have
3236       // correct memory state otherwise.
3237       _compile->get_alias_index(tinst->add_offset(oopDesc::mark_offset_in_bytes()));
3238       _compile->get_alias_index(tinst->add_offset(oopDesc::klass_offset_in_bytes()));
3239       if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
3240 
3241         // First, put on the worklist all Field edges from Connection Graph
3242         // which is more accurate than putting immediate users from Ideal Graph.
3243         for (EdgeIterator e(ptn); e.has_next(); e.next()) {
3244           PointsToNode* tgt = e.get();
3245           if (tgt->is_Arraycopy()) {
3246             continue;
3247           }
3248           Node* use = tgt->ideal_node();
3249           assert(tgt->is_Field() && use->is_AddP(),
3250                  "only AddP nodes are Field edges in CG");
3251           if (use->outcnt() > 0) { // Don't process dead nodes
3252             Node* addp2 = find_second_addp(use, use->in(AddPNode::Base));
3253             if (addp2 != NULL) {
3254               assert(alloc->is_AllocateArray(),"array allocation was expected");
3255               alloc_worklist.append_if_missing(addp2);
3256             }
3257             alloc_worklist.append_if_missing(use);
3258           }
3259         }
3260 
3261         // An allocation may have an Initialize which has raw stores. Scan
3262         // the users of the raw allocation result and push AddP users
3263         // on alloc_worklist.
3264         Node *raw_result = alloc->proj_out_or_null(TypeFunc::Parms);
3265         assert (raw_result != NULL, "must have an allocation result");
3266         for (DUIterator_Fast imax, i = raw_result->fast_outs(imax); i < imax; i++) {
3267           Node *use = raw_result->fast_out(i);
3268           if (use->is_AddP() && use->outcnt() > 0) { // Don't process dead nodes
3269             Node* addp2 = find_second_addp(use, raw_result);
3270             if (addp2 != NULL) {
3271               assert(alloc->is_AllocateArray(),"array allocation was expected");
3272               alloc_worklist.append_if_missing(addp2);
3273             }
3274             alloc_worklist.append_if_missing(use);
3275           } else if (use->is_MemBar()) {
3276             memnode_worklist.append_if_missing(use);
3277           }
3278         }
3279       }
3280     } else if (n->is_AddP()) {
3281       JavaObjectNode* jobj = unique_java_object(get_addp_base(n));
3282       if (jobj == NULL || jobj == phantom_obj) {
3283 #ifdef ASSERT
3284         ptnode_adr(get_addp_base(n)->_idx)->dump();
3285         ptnode_adr(n->_idx)->dump();
3286         assert(jobj != NULL && jobj != phantom_obj, "escaped allocation");
3287 #endif
3288         _compile->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
3289         return;
3290       }
3291       Node *base = get_map(jobj->idx());  // CheckCastPP node
3292       if (!split_AddP(n, base)) continue; // wrong type from dead path
3293     } else if (n->is_Phi() ||
3294                n->is_CheckCastPP() ||
3295                n->is_EncodeP() ||
3296                n->is_DecodeN() ||
3297                (n->is_ConstraintCast() && n->Opcode() == Op_CastPP)) {
3298       if (visited.test_set(n->_idx)) {
3299         assert(n->is_Phi(), "loops only through Phi's");
3300         continue;  // already processed
3301       }
3302       JavaObjectNode* jobj = unique_java_object(n);
3303       if (jobj == NULL || jobj == phantom_obj) {
3304 #ifdef ASSERT
3305         ptnode_adr(n->_idx)->dump();
3306         assert(jobj != NULL && jobj != phantom_obj, "escaped allocation");
3307 #endif
3308         _compile->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
3309         return;
3310       } else {
3311         Node *val = get_map(jobj->idx());   // CheckCastPP node
3312         TypeNode *tn = n->as_Type();
3313         const TypeOopPtr* tinst = igvn->type(val)->isa_oopptr();
3314         assert(tinst != NULL && tinst->is_known_instance() &&
3315                tinst->instance_id() == jobj->idx() , "instance type expected.");
3316 
3317         const Type *tn_type = igvn->type(tn);
3318         const TypeOopPtr *tn_t;
3319         if (tn_type->isa_narrowoop()) {
3320           tn_t = tn_type->make_ptr()->isa_oopptr();
3321         } else {
3322           tn_t = tn_type->isa_oopptr();
3323         }
3324         if (tn_t != NULL && tinst->maybe_java_subtype_of(tn_t)) {
3325           if (tn_type->isa_narrowoop()) {
3326             tn_type = tinst->make_narrowoop();
3327           } else {
3328             tn_type = tinst;
3329           }
3330           igvn->hash_delete(tn);
3331           igvn->set_type(tn, tn_type);
3332           tn->set_type(tn_type);
3333           igvn->hash_insert(tn);
3334           record_for_optimizer(n);
3335         } else {
3336           assert(tn_type == TypePtr::NULL_PTR ||
3337                  tn_t != NULL && !tinst->maybe_java_subtype_of(tn_t),
3338                  "unexpected type");
3339           continue; // Skip dead path with different type
3340         }
3341       }
3342     } else {
3343       debug_only(n->dump();)
3344       assert(false, "EA: unexpected node");
3345       continue;
3346     }
3347     // push allocation's users on appropriate worklist
3348     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3349       Node *use = n->fast_out(i);
3350       if(use->is_Mem() && use->in(MemNode::Address) == n) {
3351         // Load/store to instance's field
3352         memnode_worklist.append_if_missing(use);
3353       } else if (use->is_MemBar()) {
3354         if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
3355           memnode_worklist.append_if_missing(use);
3356         }
3357       } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
3358         Node* addp2 = find_second_addp(use, n);
3359         if (addp2 != NULL) {
3360           alloc_worklist.append_if_missing(addp2);
3361         }
3362         alloc_worklist.append_if_missing(use);
3363       } else if (use->is_Phi() ||
3364                  use->is_CheckCastPP() ||
3365                  use->is_EncodeNarrowPtr() ||
3366                  use->is_DecodeNarrowPtr() ||
3367                  (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
3368         alloc_worklist.append_if_missing(use);
3369 #ifdef ASSERT
3370       } else if (use->is_Mem()) {
3371         assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
3372       } else if (use->is_MergeMem()) {
3373         assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
3374       } else if (use->is_SafePoint()) {
3375         // Look for MergeMem nodes for calls which reference unique allocation
3376         // (through CheckCastPP nodes) even for debug info.
3377         Node* m = use->in(TypeFunc::Memory);
3378         if (m->is_MergeMem()) {
3379           assert(mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
3380         }
3381       } else if (use->Opcode() == Op_EncodeISOArray) {
3382         if (use->in(MemNode::Memory) == n || use->in(3) == n) {
3383           // EncodeISOArray overwrites destination array
3384           memnode_worklist.append_if_missing(use);
3385         }
3386       } else {
3387         uint op = use->Opcode();
3388         if ((op == Op_StrCompressedCopy || op == Op_StrInflatedCopy) &&
3389             (use->in(MemNode::Memory) == n)) {
3390           // They overwrite memory edge corresponding to destination array,
3391           memnode_worklist.append_if_missing(use);
3392         } else if (!(op == Op_CmpP || op == Op_Conv2B ||
3393               op == Op_CastP2X || op == Op_StoreCM ||
3394               op == Op_FastLock || op == Op_AryEq || op == Op_StrComp ||
3395               op == Op_CountPositives ||
3396               op == Op_StrCompressedCopy || op == Op_StrInflatedCopy ||
3397               op == Op_StrEquals || op == Op_StrIndexOf || op == Op_StrIndexOfChar ||
3398               op == Op_SubTypeCheck ||
3399               BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use))) {
3400           n->dump();
3401           use->dump();
3402           assert(false, "EA: missing allocation reference path");
3403         }
3404 #endif
3405       }
3406     }
3407 
3408   }
3409 
3410   // Go over all ArrayCopy nodes and if one of the inputs has a unique
3411   // type, record it in the ArrayCopy node so we know what memory this
3412   // node uses/modified.
3413   for (int next = 0; next < arraycopy_worklist.length(); next++) {
3414     ArrayCopyNode* ac = arraycopy_worklist.at(next);
3415     Node* dest = ac->in(ArrayCopyNode::Dest);
3416     if (dest->is_AddP()) {
3417       dest = get_addp_base(dest);
3418     }
3419     JavaObjectNode* jobj = unique_java_object(dest);
3420     if (jobj != NULL) {
3421       Node *base = get_map(jobj->idx());
3422       if (base != NULL) {
3423         const TypeOopPtr *base_t = _igvn->type(base)->isa_oopptr();
3424         ac->_dest_type = base_t;
3425       }
3426     }
3427     Node* src = ac->in(ArrayCopyNode::Src);
3428     if (src->is_AddP()) {
3429       src = get_addp_base(src);
3430     }
3431     jobj = unique_java_object(src);
3432     if (jobj != NULL) {
3433       Node* base = get_map(jobj->idx());
3434       if (base != NULL) {
3435         const TypeOopPtr *base_t = _igvn->type(base)->isa_oopptr();
3436         ac->_src_type = base_t;
3437       }
3438     }
3439   }
3440 
3441   // New alias types were created in split_AddP().
3442   uint new_index_end = (uint) _compile->num_alias_types();
3443   assert(unique_old == _compile->unique(), "there should be no new ideal nodes after Phase 1");
3444 
3445   //  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
3446   //            compute new values for Memory inputs  (the Memory inputs are not
3447   //            actually updated until phase 4.)
3448   if (memnode_worklist.length() == 0)
3449     return;  // nothing to do
3450   while (memnode_worklist.length() != 0) {
3451     Node *n = memnode_worklist.pop();
3452     if (visited.test_set(n->_idx)) {
3453       continue;
3454     }
3455     if (n->is_Phi() || n->is_ClearArray()) {
3456       // we don't need to do anything, but the users must be pushed
3457     } else if (n->is_MemBar()) { // Initialize, MemBar nodes
3458       // we don't need to do anything, but the users must be pushed
3459       n = n->as_MemBar()->proj_out_or_null(TypeFunc::Memory);
3460       if (n == NULL) {
3461         continue;
3462       }
3463     } else if (n->Opcode() == Op_StrCompressedCopy ||
3464                n->Opcode() == Op_EncodeISOArray) {
3465       // get the memory projection
3466       n = n->find_out_with(Op_SCMemProj);
3467       assert(n != NULL && n->Opcode() == Op_SCMemProj, "memory projection required");
3468     } else {
3469       assert(n->is_Mem(), "memory node required.");
3470       Node *addr = n->in(MemNode::Address);
3471       const Type *addr_t = igvn->type(addr);
3472       if (addr_t == Type::TOP) {
3473         continue;
3474       }
3475       assert (addr_t->isa_ptr() != NULL, "pointer type required.");
3476       int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
3477       assert ((uint)alias_idx < new_index_end, "wrong alias index");
3478       Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis);
3479       if (_compile->failing()) {
3480         return;
3481       }
3482       if (mem != n->in(MemNode::Memory)) {
3483         // We delay the memory edge update since we need old one in
3484         // MergeMem code below when instances memory slices are separated.
3485         set_map(n, mem);
3486       }
3487       if (n->is_Load()) {
3488         continue;  // don't push users
3489       } else if (n->is_LoadStore()) {
3490         // get the memory projection
3491         n = n->find_out_with(Op_SCMemProj);
3492         assert(n != NULL && n->Opcode() == Op_SCMemProj, "memory projection required");
3493       }
3494     }
3495     // push user on appropriate worklist
3496     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3497       Node *use = n->fast_out(i);
3498       if (use->is_Phi() || use->is_ClearArray()) {
3499         memnode_worklist.append_if_missing(use);
3500       } else if (use->is_Mem() && use->in(MemNode::Memory) == n) {
3501         if (use->Opcode() == Op_StoreCM) { // Ignore cardmark stores
3502           continue;
3503         }
3504         memnode_worklist.append_if_missing(use);
3505       } else if (use->is_MemBar()) {
3506         if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
3507           memnode_worklist.append_if_missing(use);
3508         }
3509 #ifdef ASSERT
3510       } else if(use->is_Mem()) {
3511         assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
3512       } else if (use->is_MergeMem()) {
3513         assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
3514       } else if (use->Opcode() == Op_EncodeISOArray) {
3515         if (use->in(MemNode::Memory) == n || use->in(3) == n) {
3516           // EncodeISOArray overwrites destination array
3517           memnode_worklist.append_if_missing(use);
3518         }
3519       } else {
3520         uint op = use->Opcode();
3521         if ((use->in(MemNode::Memory) == n) &&
3522             (op == Op_StrCompressedCopy || op == Op_StrInflatedCopy)) {
3523           // They overwrite memory edge corresponding to destination array,
3524           memnode_worklist.append_if_missing(use);
3525         } else if (!(BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use) ||
3526               op == Op_AryEq || op == Op_StrComp || op == Op_CountPositives ||
3527               op == Op_StrCompressedCopy || op == Op_StrInflatedCopy ||
3528               op == Op_StrEquals || op == Op_StrIndexOf || op == Op_StrIndexOfChar)) {
3529           n->dump();
3530           use->dump();
3531           assert(false, "EA: missing memory path");
3532         }
3533 #endif
3534       }
3535     }
3536   }
3537 
3538   //  Phase 3:  Process MergeMem nodes from mergemem_worklist.
3539   //            Walk each memory slice moving the first node encountered of each
3540   //            instance type to the input corresponding to its alias index.
3541   uint length = mergemem_worklist.length();
3542   for( uint next = 0; next < length; ++next ) {
3543     MergeMemNode* nmm = mergemem_worklist.at(next);
3544     assert(!visited.test_set(nmm->_idx), "should not be visited before");
3545     // Note: we don't want to use MergeMemStream here because we only want to
3546     // scan inputs which exist at the start, not ones we add during processing.
3547     // Note 2: MergeMem may already contains instance memory slices added
3548     // during find_inst_mem() call when memory nodes were processed above.
3549     igvn->hash_delete(nmm);
3550     uint nslices = MIN2(nmm->req(), new_index_start);
3551     for (uint i = Compile::AliasIdxRaw+1; i < nslices; i++) {
3552       Node* mem = nmm->in(i);
3553       Node* cur = NULL;
3554       if (mem == NULL || mem->is_top()) {
3555         continue;
3556       }
3557       // First, update mergemem by moving memory nodes to corresponding slices
3558       // if their type became more precise since this mergemem was created.
3559       while (mem->is_Mem()) {
3560         const Type *at = igvn->type(mem->in(MemNode::Address));
3561         if (at != Type::TOP) {
3562           assert (at->isa_ptr() != NULL, "pointer type required.");
3563           uint idx = (uint)_compile->get_alias_index(at->is_ptr());
3564           if (idx == i) {
3565             if (cur == NULL) {
3566               cur = mem;
3567             }
3568           } else {
3569             if (idx >= nmm->req() || nmm->is_empty_memory(nmm->in(idx))) {
3570               nmm->set_memory_at(idx, mem);
3571             }
3572           }
3573         }
3574         mem = mem->in(MemNode::Memory);
3575       }
3576       nmm->set_memory_at(i, (cur != NULL) ? cur : mem);
3577       // Find any instance of the current type if we haven't encountered
3578       // already a memory slice of the instance along the memory chain.
3579       for (uint ni = new_index_start; ni < new_index_end; ni++) {
3580         if((uint)_compile->get_general_index(ni) == i) {
3581           Node *m = (ni >= nmm->req()) ? nmm->empty_memory() : nmm->in(ni);
3582           if (nmm->is_empty_memory(m)) {
3583             Node* result = find_inst_mem(mem, ni, orig_phis);
3584             if (_compile->failing()) {
3585               return;
3586             }
3587             nmm->set_memory_at(ni, result);
3588           }
3589         }
3590       }
3591     }
3592     // Find the rest of instances values
3593     for (uint ni = new_index_start; ni < new_index_end; ni++) {
3594       const TypeOopPtr *tinst = _compile->get_adr_type(ni)->isa_oopptr();
3595       Node* result = step_through_mergemem(nmm, ni, tinst);
3596       if (result == nmm->base_memory()) {
3597         // Didn't find instance memory, search through general slice recursively.
3598         result = nmm->memory_at(_compile->get_general_index(ni));
3599         result = find_inst_mem(result, ni, orig_phis);
3600         if (_compile->failing()) {
3601           return;
3602         }
3603         nmm->set_memory_at(ni, result);
3604       }
3605     }
3606     igvn->hash_insert(nmm);
3607     record_for_optimizer(nmm);
3608   }
3609 
3610   //  Phase 4:  Update the inputs of non-instance memory Phis and
3611   //            the Memory input of memnodes
3612   // First update the inputs of any non-instance Phi's from
3613   // which we split out an instance Phi.  Note we don't have
3614   // to recursively process Phi's encountered on the input memory
3615   // chains as is done in split_memory_phi() since they  will
3616   // also be processed here.
3617   for (int j = 0; j < orig_phis.length(); j++) {
3618     PhiNode *phi = orig_phis.at(j);
3619     int alias_idx = _compile->get_alias_index(phi->adr_type());
3620     igvn->hash_delete(phi);
3621     for (uint i = 1; i < phi->req(); i++) {
3622       Node *mem = phi->in(i);
3623       Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis);
3624       if (_compile->failing()) {
3625         return;
3626       }
3627       if (mem != new_mem) {
3628         phi->set_req(i, new_mem);
3629       }
3630     }
3631     igvn->hash_insert(phi);
3632     record_for_optimizer(phi);
3633   }
3634 
3635   // Update the memory inputs of MemNodes with the value we computed
3636   // in Phase 2 and move stores memory users to corresponding memory slices.
3637   // Disable memory split verification code until the fix for 6984348.
3638   // Currently it produces false negative results since it does not cover all cases.
3639 #if 0 // ifdef ASSERT
3640   visited.Reset();
3641   Node_Stack old_mems(arena, _compile->unique() >> 2);
3642 #endif
3643   for (uint i = 0; i < ideal_nodes.size(); i++) {
3644     Node*    n = ideal_nodes.at(i);
3645     Node* nmem = get_map(n->_idx);
3646     assert(nmem != NULL, "sanity");
3647     if (n->is_Mem()) {
3648 #if 0 // ifdef ASSERT
3649       Node* old_mem = n->in(MemNode::Memory);
3650       if (!visited.test_set(old_mem->_idx)) {
3651         old_mems.push(old_mem, old_mem->outcnt());
3652       }
3653 #endif
3654       assert(n->in(MemNode::Memory) != nmem, "sanity");
3655       if (!n->is_Load()) {
3656         // Move memory users of a store first.
3657         move_inst_mem(n, orig_phis);
3658       }
3659       // Now update memory input
3660       igvn->hash_delete(n);
3661       n->set_req(MemNode::Memory, nmem);
3662       igvn->hash_insert(n);
3663       record_for_optimizer(n);
3664     } else {
3665       assert(n->is_Allocate() || n->is_CheckCastPP() ||
3666              n->is_AddP() || n->is_Phi(), "unknown node used for set_map()");
3667     }
3668   }
3669 #if 0 // ifdef ASSERT
3670   // Verify that memory was split correctly
3671   while (old_mems.is_nonempty()) {
3672     Node* old_mem = old_mems.node();
3673     uint  old_cnt = old_mems.index();
3674     old_mems.pop();
3675     assert(old_cnt == old_mem->outcnt(), "old mem could be lost");
3676   }
3677 #endif
3678 }
3679 
3680 #ifndef PRODUCT
3681 int ConnectionGraph::_no_escape_counter = 0;
3682 int ConnectionGraph::_arg_escape_counter = 0;
3683 int ConnectionGraph::_global_escape_counter = 0;
3684 
3685 static const char *node_type_names[] = {
3686   "UnknownType",
3687   "JavaObject",
3688   "LocalVar",
3689   "Field",
3690   "Arraycopy"
3691 };
3692 
3693 static const char *esc_names[] = {
3694   "UnknownEscape",
3695   "NoEscape",
3696   "ArgEscape",
3697   "GlobalEscape"
3698 };
3699 
3700 void PointsToNode::dump_header(bool print_state, outputStream* out) const {
3701   NodeType nt = node_type();
3702   out->print("%s(%d) ", node_type_names[(int) nt], _pidx);
3703   if (print_state) {
3704     EscapeState es = escape_state();
3705     EscapeState fields_es = fields_escape_state();
3706     out->print("%s(%s) ", esc_names[(int)es], esc_names[(int)fields_es]);
3707     if (nt == PointsToNode::JavaObject && !this->scalar_replaceable()) {
3708       out->print("NSR ");
3709     }
3710   }
3711 }
3712 
3713 void PointsToNode::dump(bool print_state, outputStream* out, bool newline) const {
3714   dump_header(print_state, out);
3715   if (is_Field()) {
3716     FieldNode* f = (FieldNode*)this;
3717     if (f->is_oop()) {
3718       out->print("oop ");
3719     }
3720     if (f->offset() > 0) {
3721       out->print("+%d ", f->offset());
3722     }
3723     out->print("(");
3724     for (BaseIterator i(f); i.has_next(); i.next()) {
3725       PointsToNode* b = i.get();
3726       out->print(" %d%s", b->idx(),(b->is_JavaObject() ? "P" : ""));
3727     }
3728     out->print(" )");
3729   }
3730   out->print("[");
3731   for (EdgeIterator i(this); i.has_next(); i.next()) {
3732     PointsToNode* e = i.get();
3733     out->print(" %d%s%s", e->idx(),(e->is_JavaObject() ? "P" : (e->is_Field() ? "F" : "")), e->is_Arraycopy() ? "cp" : "");
3734   }
3735   out->print(" [");
3736   for (UseIterator i(this); i.has_next(); i.next()) {
3737     PointsToNode* u = i.get();
3738     bool is_base = false;
3739     if (PointsToNode::is_base_use(u)) {
3740       is_base = true;
3741       u = PointsToNode::get_use_node(u)->as_Field();
3742     }
3743     out->print(" %d%s%s", u->idx(), is_base ? "b" : "", u->is_Arraycopy() ? "cp" : "");
3744   }
3745   out->print(" ]]  ");
3746   if (_node == NULL) {
3747     out->print("<null>%s", newline ? "\n" : "");
3748   } else {
3749     _node->dump(newline ? "\n" : "", false, out);
3750   }
3751 }
3752 
3753 void ConnectionGraph::dump(GrowableArray<PointsToNode*>& ptnodes_worklist) {
3754   bool first = true;
3755   int ptnodes_length = ptnodes_worklist.length();
3756   for (int i = 0; i < ptnodes_length; i++) {
3757     PointsToNode *ptn = ptnodes_worklist.at(i);
3758     if (ptn == NULL || !ptn->is_JavaObject()) {
3759       continue;
3760     }
3761     PointsToNode::EscapeState es = ptn->escape_state();
3762     if ((es != PointsToNode::NoEscape) && !Verbose) {
3763       continue;
3764     }
3765     Node* n = ptn->ideal_node();
3766     if (n->is_Allocate() || (n->is_CallStaticJava() &&
3767                              n->as_CallStaticJava()->is_boxing_method())) {
3768       if (first) {
3769         tty->cr();
3770         tty->print("======== Connection graph for ");
3771         _compile->method()->print_short_name();
3772         tty->cr();
3773         tty->print_cr("invocation #%d: %d iterations and %f sec to build connection graph with %d nodes and worklist size %d",
3774                       _invocation, _build_iterations, _build_time, nodes_size(), ptnodes_worklist.length());
3775         tty->cr();
3776         first = false;
3777       }
3778       ptn->dump();
3779       // Print all locals and fields which reference this allocation
3780       for (UseIterator j(ptn); j.has_next(); j.next()) {
3781         PointsToNode* use = j.get();
3782         if (use->is_LocalVar()) {
3783           use->dump(Verbose);
3784         } else if (Verbose) {
3785           use->dump();
3786         }
3787       }
3788       tty->cr();
3789     }
3790   }
3791 }
3792 
3793 void ConnectionGraph::print_statistics() {
3794   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));
3795 }
3796 
3797 void ConnectionGraph::escape_state_statistics(GrowableArray<JavaObjectNode*>& java_objects_worklist) {
3798   if (!PrintOptoStatistics || (_invocation > 0)) { // Collect data only for the first invocation
3799     return;
3800   }
3801   for (int next = 0; next < java_objects_worklist.length(); ++next) {
3802     JavaObjectNode* ptn = java_objects_worklist.at(next);
3803     if (ptn->ideal_node()->is_Allocate()) {
3804       if (ptn->escape_state() == PointsToNode::NoEscape) {
3805         Atomic::inc(&ConnectionGraph::_no_escape_counter);
3806       } else if (ptn->escape_state() == PointsToNode::ArgEscape) {
3807         Atomic::inc(&ConnectionGraph::_arg_escape_counter);
3808       } else if (ptn->escape_state() == PointsToNode::GlobalEscape) {
3809         Atomic::inc(&ConnectionGraph::_global_escape_counter);
3810       } else {
3811         assert(false, "Unexpected Escape State");
3812       }
3813     }
3814   }
3815 }
3816 
3817 void ConnectionGraph::trace_es_update_helper(PointsToNode* ptn, PointsToNode::EscapeState es, bool fields, const char* reason) const {
3818   if (_compile->directive()->TraceEscapeAnalysisOption) {
3819     assert(ptn != nullptr, "should not be null");
3820     assert(reason != nullptr, "should not be null");
3821     ptn->dump_header(true);
3822     PointsToNode::EscapeState new_es = fields ? ptn->escape_state() : es;
3823     PointsToNode::EscapeState new_fields_es = fields ? es : ptn->fields_escape_state();
3824     tty->print_cr("-> %s(%s) %s", esc_names[(int)new_es], esc_names[(int)new_fields_es], reason);
3825   }
3826 }
3827 
3828 const char* ConnectionGraph::trace_propagate_message(PointsToNode* from) const {
3829   if (_compile->directive()->TraceEscapeAnalysisOption) {
3830     stringStream ss;
3831     ss.print("propagated from: ");
3832     from->dump(true, &ss, false);
3833     return ss.as_string();
3834   } else {
3835     return nullptr;
3836   }
3837 }
3838 
3839 const char* ConnectionGraph::trace_arg_escape_message(CallNode* call) const {
3840   if (_compile->directive()->TraceEscapeAnalysisOption) {
3841     stringStream ss;
3842     ss.print("escapes as arg to:");
3843     call->dump("", false, &ss);
3844     return ss.as_string();
3845   } else {
3846     return nullptr;
3847   }
3848 }
3849 
3850 const char* ConnectionGraph::trace_merged_message(PointsToNode* other) const {
3851   if (_compile->directive()->TraceEscapeAnalysisOption) {
3852     stringStream ss;
3853     ss.print("is merged with other object: ");
3854     other->dump_header(true, &ss);
3855     return ss.as_string();
3856   } else {
3857     return nullptr;
3858   }
3859 }
3860 
3861 #endif
3862 
3863 void ConnectionGraph::record_for_optimizer(Node *n) {
3864   _igvn->_worklist.push(n);
3865   _igvn->add_users_to_worklist(n);
3866 }