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