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