1 /*
   2  * Copyright (c) 2005, 2011, 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 "libadt/vectset.hpp"
  28 #include "memory/allocation.hpp"
  29 #include "opto/c2compiler.hpp"
  30 #include "opto/callnode.hpp"
  31 #include "opto/cfgnode.hpp"
  32 #include "opto/compile.hpp"
  33 #include "opto/escape.hpp"
  34 #include "opto/phaseX.hpp"
  35 #include "opto/rootnode.hpp"
  36 
  37 void PointsToNode::add_edge(uint targIdx, PointsToNode::EdgeType et) {
  38   uint v = (targIdx << EdgeShift) + ((uint) et);
  39   if (_edges == NULL) {
  40      Arena *a = Compile::current()->comp_arena();
  41     _edges = new(a) GrowableArray<uint>(a, INITIAL_EDGE_COUNT, 0, 0);
  42   }
  43   _edges->append_if_missing(v);
  44 }
  45 
  46 void PointsToNode::remove_edge(uint targIdx, PointsToNode::EdgeType et) {
  47   uint v = (targIdx << EdgeShift) + ((uint) et);
  48 
  49   _edges->remove(v);
  50 }
  51 
  52 #ifndef PRODUCT
  53 static const char *node_type_names[] = {
  54   "UnknownType",
  55   "JavaObject",
  56   "LocalVar",
  57   "Field"
  58 };
  59 
  60 static const char *esc_names[] = {
  61   "UnknownEscape",
  62   "NoEscape",
  63   "ControlEscape",
  64   "ArgEscape",
  65   "GlobalEscape"
  66 };
  67 
  68 static const char *edge_type_suffix[] = {
  69  "?", // UnknownEdge
  70  "P", // PointsToEdge
  71  "D", // DeferredEdge
  72  "F"  // FieldEdge
  73 };
  74 
  75 void PointsToNode::dump(bool print_state) const {
  76   NodeType nt = node_type();
  77   tty->print("%s ", node_type_names[(int) nt]);
  78   if (print_state) {
  79     EscapeState es = escape_state();
  80     tty->print("%s ", esc_names[(int) es]);
  81   }
  82   tty->print("[[");
  83   for (uint i = 0; i < edge_count(); i++) {
  84     tty->print(" %d%s", edge_target(i), edge_type_suffix[(int) edge_type(i)]);
  85   }
  86   tty->print("]]  ");
  87   if (_node == NULL)
  88     tty->print_cr("<null>");
  89   else
  90     _node->dump();
  91 }
  92 #endif
  93 
  94 ConnectionGraph::ConnectionGraph(Compile * C, PhaseIterGVN *igvn) :
  95   _nodes(C->comp_arena(), C->unique(), C->unique(), PointsToNode()),
  96   _processed(C->comp_arena()),
  97   pt_ptset(C->comp_arena()),
  98   pt_visited(C->comp_arena()),
  99   pt_worklist(C->comp_arena(), 4, 0, 0),
 100   _collecting(true),
 101   _progress(false),
 102   _compile(C),
 103   _igvn(igvn),
 104   _node_map(C->comp_arena()) {
 105 
 106   _phantom_object = C->top()->_idx,
 107   add_node(C->top(), PointsToNode::JavaObject, PointsToNode::GlobalEscape,true);
 108 
 109   // Add ConP(#NULL) and ConN(#NULL) nodes.
 110   Node* oop_null = igvn->zerocon(T_OBJECT);
 111   _oop_null = oop_null->_idx;
 112   assert(_oop_null < nodes_size(), "should be created already");
 113   add_node(oop_null, PointsToNode::JavaObject, PointsToNode::NoEscape, true);
 114 
 115   if (UseCompressedOops) {
 116     Node* noop_null = igvn->zerocon(T_NARROWOOP);
 117     _noop_null = noop_null->_idx;
 118     assert(_noop_null < nodes_size(), "should be created already");
 119     add_node(noop_null, PointsToNode::JavaObject, PointsToNode::NoEscape, true);
 120   } else {
 121     _noop_null = _oop_null; // Should be initialized
 122   }
 123 }
 124 
 125 void ConnectionGraph::add_pointsto_edge(uint from_i, uint to_i) {
 126   PointsToNode *f = ptnode_adr(from_i);
 127   PointsToNode *t = ptnode_adr(to_i);
 128 
 129   assert(f->node_type() != PointsToNode::UnknownType && t->node_type() != PointsToNode::UnknownType, "node types must be set");
 130   assert(f->node_type() == PointsToNode::LocalVar || f->node_type() == PointsToNode::Field, "invalid source of PointsTo edge");
 131   assert(t->node_type() == PointsToNode::JavaObject, "invalid destination of PointsTo edge");
 132   add_edge(f, to_i, PointsToNode::PointsToEdge);
 133 }
 134 
 135 void ConnectionGraph::add_deferred_edge(uint from_i, uint to_i) {
 136   PointsToNode *f = ptnode_adr(from_i);
 137   PointsToNode *t = ptnode_adr(to_i);
 138 
 139   assert(f->node_type() != PointsToNode::UnknownType && t->node_type() != PointsToNode::UnknownType, "node types must be set");
 140   assert(f->node_type() == PointsToNode::LocalVar || f->node_type() == PointsToNode::Field, "invalid source of Deferred edge");
 141   assert(t->node_type() == PointsToNode::LocalVar || t->node_type() == PointsToNode::Field, "invalid destination of Deferred edge");
 142   // don't add a self-referential edge, this can occur during removal of
 143   // deferred edges
 144   if (from_i != to_i)
 145     add_edge(f, to_i, PointsToNode::DeferredEdge);
 146 }
 147 
 148 int ConnectionGraph::address_offset(Node* adr, PhaseTransform *phase) {
 149   const Type *adr_type = phase->type(adr);
 150   if (adr->is_AddP() && adr_type->isa_oopptr() == NULL &&
 151       adr->in(AddPNode::Address)->is_Proj() &&
 152       adr->in(AddPNode::Address)->in(0)->is_Allocate()) {
 153     // We are computing a raw address for a store captured by an Initialize
 154     // compute an appropriate address type. AddP cases #3 and #5 (see below).
 155     int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
 156     assert(offs != Type::OffsetBot ||
 157            adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
 158            "offset must be a constant or it is initialization of array");
 159     return offs;
 160   }
 161   const TypePtr *t_ptr = adr_type->isa_ptr();
 162   assert(t_ptr != NULL, "must be a pointer type");
 163   return t_ptr->offset();
 164 }
 165 
 166 void ConnectionGraph::add_field_edge(uint from_i, uint to_i, int offset) {
 167   PointsToNode *f = ptnode_adr(from_i);
 168   PointsToNode *t = ptnode_adr(to_i);
 169 
 170   assert(f->node_type() != PointsToNode::UnknownType && t->node_type() != PointsToNode::UnknownType, "node types must be set");
 171   assert(f->node_type() == PointsToNode::JavaObject, "invalid destination of Field edge");
 172   assert(t->node_type() == PointsToNode::Field, "invalid destination of Field edge");
 173   assert (t->offset() == -1 || t->offset() == offset, "conflicting field offsets");
 174   t->set_offset(offset);
 175 
 176   add_edge(f, to_i, PointsToNode::FieldEdge);
 177 }
 178 
 179 void ConnectionGraph::set_escape_state(uint ni, PointsToNode::EscapeState es) {
 180   // Don't change non-escaping state of NULL pointer.
 181   if (ni == _noop_null || ni == _oop_null)
 182     return;
 183   PointsToNode *npt = ptnode_adr(ni);
 184   PointsToNode::EscapeState old_es = npt->escape_state();
 185   if (es > old_es)
 186     npt->set_escape_state(es);
 187 }
 188 
 189 void ConnectionGraph::add_node(Node *n, PointsToNode::NodeType nt,
 190                                PointsToNode::EscapeState es, bool done) {
 191   PointsToNode* ptadr = ptnode_adr(n->_idx);
 192   ptadr->_node = n;
 193   ptadr->set_node_type(nt);
 194 
 195   // inline set_escape_state(idx, es);
 196   PointsToNode::EscapeState old_es = ptadr->escape_state();
 197   if (es > old_es)
 198     ptadr->set_escape_state(es);
 199 
 200   if (done)
 201     _processed.set(n->_idx);
 202 }
 203 
 204 PointsToNode::EscapeState ConnectionGraph::escape_state(Node *n) {
 205   uint idx = n->_idx;
 206   PointsToNode::EscapeState es;
 207 
 208   // If we are still collecting or there were no non-escaping allocations
 209   // we don't know the answer yet
 210   if (_collecting)
 211     return PointsToNode::UnknownEscape;
 212 
 213   // if the node was created after the escape computation, return
 214   // UnknownEscape
 215   if (idx >= nodes_size())
 216     return PointsToNode::UnknownEscape;
 217 
 218   es = ptnode_adr(idx)->escape_state();
 219 
 220   // if we have already computed a value, return it
 221   if (es != PointsToNode::UnknownEscape &&
 222       ptnode_adr(idx)->node_type() == PointsToNode::JavaObject)
 223     return es;
 224 
 225   // PointsTo() calls n->uncast() which can return a new ideal node.
 226   if (n->uncast()->_idx >= nodes_size())
 227     return PointsToNode::UnknownEscape;
 228 
 229   PointsToNode::EscapeState orig_es = es;
 230 
 231   // compute max escape state of anything this node could point to
 232   for(VectorSetI i(PointsTo(n)); i.test() && es != PointsToNode::GlobalEscape; ++i) {
 233     uint pt = i.elem;
 234     PointsToNode::EscapeState pes = ptnode_adr(pt)->escape_state();
 235     if (pes > es)
 236       es = pes;
 237   }
 238   if (orig_es != es) {
 239     // cache the computed escape state
 240     assert(es > orig_es, "should have computed an escape state");
 241     set_escape_state(idx, es);
 242   } // orig_es could be PointsToNode::UnknownEscape
 243   return es;
 244 }
 245 
 246 VectorSet* ConnectionGraph::PointsTo(Node * n) {
 247   pt_ptset.Reset();
 248   pt_visited.Reset();
 249   pt_worklist.clear();
 250 
 251 #ifdef ASSERT
 252   Node *orig_n = n;
 253 #endif
 254 
 255   n = n->uncast();
 256   PointsToNode* npt = ptnode_adr(n->_idx);
 257 
 258   // If we have a JavaObject, return just that object
 259   if (npt->node_type() == PointsToNode::JavaObject) {
 260     pt_ptset.set(n->_idx);
 261     return &pt_ptset;
 262   }
 263 #ifdef ASSERT
 264   if (npt->_node == NULL) {
 265     if (orig_n != n)
 266       orig_n->dump();
 267     n->dump();
 268     assert(npt->_node != NULL, "unregistered node");
 269   }
 270 #endif
 271   pt_worklist.push(n->_idx);
 272   while(pt_worklist.length() > 0) {
 273     int ni = pt_worklist.pop();
 274     if (pt_visited.test_set(ni))
 275       continue;
 276 
 277     PointsToNode* pn = ptnode_adr(ni);
 278     // ensure that all inputs of a Phi have been processed
 279     assert(!_collecting || !pn->_node->is_Phi() || _processed.test(ni),"");
 280 
 281     int edges_processed = 0;
 282     uint e_cnt = pn->edge_count();
 283     for (uint e = 0; e < e_cnt; e++) {
 284       uint etgt = pn->edge_target(e);
 285       PointsToNode::EdgeType et = pn->edge_type(e);
 286       if (et == PointsToNode::PointsToEdge) {
 287         pt_ptset.set(etgt);
 288         edges_processed++;
 289       } else if (et == PointsToNode::DeferredEdge) {
 290         pt_worklist.push(etgt);
 291         edges_processed++;
 292       } else {
 293         assert(false,"neither PointsToEdge or DeferredEdge");
 294       }
 295     }
 296     if (edges_processed == 0) {
 297       // no deferred or pointsto edges found.  Assume the value was set
 298       // outside this method.  Add the phantom object to the pointsto set.
 299       pt_ptset.set(_phantom_object);
 300     }
 301   }
 302   return &pt_ptset;
 303 }
 304 
 305 void ConnectionGraph::remove_deferred(uint ni, GrowableArray<uint>* deferred_edges, VectorSet* visited) {
 306   // This method is most expensive during ConnectionGraph construction.
 307   // Reuse vectorSet and an additional growable array for deferred edges.
 308   deferred_edges->clear();
 309   visited->Reset();
 310 
 311   visited->set(ni);
 312   PointsToNode *ptn = ptnode_adr(ni);
 313 
 314   // Mark current edges as visited and move deferred edges to separate array.
 315   for (uint i = 0; i < ptn->edge_count(); ) {
 316     uint t = ptn->edge_target(i);
 317 #ifdef ASSERT
 318     assert(!visited->test_set(t), "expecting no duplications");
 319 #else
 320     visited->set(t);
 321 #endif
 322     if (ptn->edge_type(i) == PointsToNode::DeferredEdge) {
 323       ptn->remove_edge(t, PointsToNode::DeferredEdge);
 324       deferred_edges->append(t);
 325     } else {
 326       i++;
 327     }
 328   }
 329   for (int next = 0; next < deferred_edges->length(); ++next) {
 330     uint t = deferred_edges->at(next);
 331     PointsToNode *ptt = ptnode_adr(t);
 332     uint e_cnt = ptt->edge_count();
 333     for (uint e = 0; e < e_cnt; e++) {
 334       uint etgt = ptt->edge_target(e);
 335       if (visited->test_set(etgt))
 336         continue;
 337 
 338       PointsToNode::EdgeType et = ptt->edge_type(e);
 339       if (et == PointsToNode::PointsToEdge) {
 340         add_pointsto_edge(ni, etgt);
 341         if(etgt == _phantom_object) {
 342           // Special case - field set outside (globally escaping).
 343           set_escape_state(ni, PointsToNode::GlobalEscape);
 344         }
 345       } else if (et == PointsToNode::DeferredEdge) {
 346         deferred_edges->append(etgt);
 347       } else {
 348         assert(false,"invalid connection graph");
 349       }
 350     }
 351   }
 352 }
 353 
 354 
 355 //  Add an edge to node given by "to_i" from any field of adr_i whose offset
 356 //  matches "offset"  A deferred edge is added if to_i is a LocalVar, and
 357 //  a pointsto edge is added if it is a JavaObject
 358 
 359 void ConnectionGraph::add_edge_from_fields(uint adr_i, uint to_i, int offs) {
 360   PointsToNode* an = ptnode_adr(adr_i);
 361   PointsToNode* to = ptnode_adr(to_i);
 362   bool deferred = (to->node_type() == PointsToNode::LocalVar);
 363 
 364   for (uint fe = 0; fe < an->edge_count(); fe++) {
 365     assert(an->edge_type(fe) == PointsToNode::FieldEdge, "expecting a field edge");
 366     int fi = an->edge_target(fe);
 367     PointsToNode* pf = ptnode_adr(fi);
 368     int po = pf->offset();
 369     if (po == offs || po == Type::OffsetBot || offs == Type::OffsetBot) {
 370       if (deferred)
 371         add_deferred_edge(fi, to_i);
 372       else
 373         add_pointsto_edge(fi, to_i);
 374     }
 375   }
 376 }
 377 
 378 // Add a deferred  edge from node given by "from_i" to any field of adr_i
 379 // whose offset matches "offset".
 380 void ConnectionGraph::add_deferred_edge_to_fields(uint from_i, uint adr_i, int offs) {
 381   PointsToNode* an = ptnode_adr(adr_i);
 382   bool is_alloc = an->_node->is_Allocate();
 383   for (uint fe = 0; fe < an->edge_count(); fe++) {
 384     assert(an->edge_type(fe) == PointsToNode::FieldEdge, "expecting a field edge");
 385     int fi = an->edge_target(fe);
 386     PointsToNode* pf = ptnode_adr(fi);
 387     int offset = pf->offset();
 388     if (!is_alloc) {
 389       // Assume the field was set outside this method if it is not Allocation
 390       add_pointsto_edge(fi, _phantom_object);
 391     }
 392     if (offset == offs || offset == Type::OffsetBot || offs == Type::OffsetBot) {
 393       add_deferred_edge(from_i, fi);
 394     }
 395   }
 396 }
 397 
 398 // Helper functions
 399 
 400 static Node* get_addp_base(Node *addp) {
 401   assert(addp->is_AddP(), "must be AddP");
 402   //
 403   // AddP cases for Base and Address inputs:
 404   // case #1. Direct object's field reference:
 405   //     Allocate
 406   //       |
 407   //     Proj #5 ( oop result )
 408   //       |
 409   //     CheckCastPP (cast to instance type)
 410   //      | |
 411   //     AddP  ( base == address )
 412   //
 413   // case #2. Indirect object's field reference:
 414   //      Phi
 415   //       |
 416   //     CastPP (cast to instance type)
 417   //      | |
 418   //     AddP  ( base == address )
 419   //
 420   // case #3. Raw object's field reference for Initialize node:
 421   //      Allocate
 422   //        |
 423   //      Proj #5 ( oop result )
 424   //  top   |
 425   //     \  |
 426   //     AddP  ( base == top )
 427   //
 428   // case #4. Array's element reference:
 429   //   {CheckCastPP | CastPP}
 430   //     |  | |
 431   //     |  AddP ( array's element offset )
 432   //     |  |
 433   //     AddP ( array's offset )
 434   //
 435   // case #5. Raw object's field reference for arraycopy stub call:
 436   //          The inline_native_clone() case when the arraycopy stub is called
 437   //          after the allocation before Initialize and CheckCastPP nodes.
 438   //      Allocate
 439   //        |
 440   //      Proj #5 ( oop result )
 441   //       | |
 442   //       AddP  ( base == address )
 443   //
 444   // case #6. Constant Pool, ThreadLocal, CastX2P or
 445   //          Raw object's field reference:
 446   //      {ConP, ThreadLocal, CastX2P, raw Load}
 447   //  top   |
 448   //     \  |
 449   //     AddP  ( base == top )
 450   //
 451   // case #7. Klass's field reference.
 452   //      LoadKlass
 453   //       | |
 454   //       AddP  ( base == address )
 455   //
 456   // case #8. narrow Klass's field reference.
 457   //      LoadNKlass
 458   //       |
 459   //      DecodeN
 460   //       | |
 461   //       AddP  ( base == address )
 462   //
 463   Node *base = addp->in(AddPNode::Base)->uncast();
 464   if (base->is_top()) { // The AddP case #3 and #6.
 465     base = addp->in(AddPNode::Address)->uncast();
 466     while (base->is_AddP()) {
 467       // Case #6 (unsafe access) may have several chained AddP nodes.
 468       assert(base->in(AddPNode::Base)->is_top(), "expected unsafe access address only");
 469       base = base->in(AddPNode::Address)->uncast();
 470     }
 471     assert(base->Opcode() == Op_ConP || base->Opcode() == Op_ThreadLocal ||
 472            base->Opcode() == Op_CastX2P || base->is_DecodeN() ||
 473            (base->is_Mem() && base->bottom_type() == TypeRawPtr::NOTNULL) ||
 474            (base->is_Proj() && base->in(0)->is_Allocate()), "sanity");
 475   }
 476   return base;
 477 }
 478 
 479 static Node* find_second_addp(Node* addp, Node* n) {
 480   assert(addp->is_AddP() && addp->outcnt() > 0, "Don't process dead nodes");
 481 
 482   Node* addp2 = addp->raw_out(0);
 483   if (addp->outcnt() == 1 && addp2->is_AddP() &&
 484       addp2->in(AddPNode::Base) == n &&
 485       addp2->in(AddPNode::Address) == addp) {
 486 
 487     assert(addp->in(AddPNode::Base) == n, "expecting the same base");
 488     //
 489     // Find array's offset to push it on worklist first and
 490     // as result process an array's element offset first (pushed second)
 491     // to avoid CastPP for the array's offset.
 492     // Otherwise the inserted CastPP (LocalVar) will point to what
 493     // the AddP (Field) points to. Which would be wrong since
 494     // the algorithm expects the CastPP has the same point as
 495     // as AddP's base CheckCastPP (LocalVar).
 496     //
 497     //    ArrayAllocation
 498     //     |
 499     //    CheckCastPP
 500     //     |
 501     //    memProj (from ArrayAllocation CheckCastPP)
 502     //     |  ||
 503     //     |  ||   Int (element index)
 504     //     |  ||    |   ConI (log(element size))
 505     //     |  ||    |   /
 506     //     |  ||   LShift
 507     //     |  ||  /
 508     //     |  AddP (array's element offset)
 509     //     |  |
 510     //     |  | ConI (array's offset: #12(32-bits) or #24(64-bits))
 511     //     | / /
 512     //     AddP (array's offset)
 513     //      |
 514     //     Load/Store (memory operation on array's element)
 515     //
 516     return addp2;
 517   }
 518   return NULL;
 519 }
 520 
 521 //
 522 // Adjust the type and inputs of an AddP which computes the
 523 // address of a field of an instance
 524 //
 525 bool ConnectionGraph::split_AddP(Node *addp, Node *base,  PhaseGVN  *igvn) {
 526   const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
 527   assert(base_t != NULL && base_t->is_known_instance(), "expecting instance oopptr");
 528   const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
 529   if (t == NULL) {
 530     // We are computing a raw address for a store captured by an Initialize
 531     // compute an appropriate address type (cases #3 and #5).
 532     assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
 533     assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
 534     intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
 535     assert(offs != Type::OffsetBot, "offset must be a constant");
 536     t = base_t->add_offset(offs)->is_oopptr();
 537   }
 538   int inst_id =  base_t->instance_id();
 539   assert(!t->is_known_instance() || t->instance_id() == inst_id,
 540                              "old type must be non-instance or match new type");
 541 
 542   // The type 't' could be subclass of 'base_t'.
 543   // As result t->offset() could be large then base_t's size and it will
 544   // cause the failure in add_offset() with narrow oops since TypeOopPtr()
 545   // constructor verifies correctness of the offset.
 546   //
 547   // It could happened on subclass's branch (from the type profiling
 548   // inlining) which was not eliminated during parsing since the exactness
 549   // of the allocation type was not propagated to the subclass type check.
 550   //
 551   // Or the type 't' could be not related to 'base_t' at all.
 552   // It could happened when CHA type is different from MDO type on a dead path
 553   // (for example, from instanceof check) which is not collapsed during parsing.
 554   //
 555   // Do nothing for such AddP node and don't process its users since
 556   // this code branch will go away.
 557   //
 558   if (!t->is_known_instance() &&
 559       !base_t->klass()->is_subtype_of(t->klass())) {
 560      return false; // bail out
 561   }
 562 
 563   const TypeOopPtr *tinst = base_t->add_offset(t->offset())->is_oopptr();
 564   // Do NOT remove the next line: ensure a new alias index is allocated
 565   // for the instance type. Note: C++ will not remove it since the call
 566   // has side effect.
 567   int alias_idx = _compile->get_alias_index(tinst);
 568   igvn->set_type(addp, tinst);
 569   // record the allocation in the node map
 570   assert(ptnode_adr(addp->_idx)->_node != NULL, "should be registered");
 571   set_map(addp->_idx, get_map(base->_idx));
 572 
 573   // Set addp's Base and Address to 'base'.
 574   Node *abase = addp->in(AddPNode::Base);
 575   Node *adr   = addp->in(AddPNode::Address);
 576   if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
 577       adr->in(0)->_idx == (uint)inst_id) {
 578     // Skip AddP cases #3 and #5.
 579   } else {
 580     assert(!abase->is_top(), "sanity"); // AddP case #3
 581     if (abase != base) {
 582       igvn->hash_delete(addp);
 583       addp->set_req(AddPNode::Base, base);
 584       if (abase == adr) {
 585         addp->set_req(AddPNode::Address, base);
 586       } else {
 587         // AddP case #4 (adr is array's element offset AddP node)
 588 #ifdef ASSERT
 589         const TypeOopPtr *atype = igvn->type(adr)->isa_oopptr();
 590         assert(adr->is_AddP() && atype != NULL &&
 591                atype->instance_id() == inst_id, "array's element offset should be processed first");
 592 #endif
 593       }
 594       igvn->hash_insert(addp);
 595     }
 596   }
 597   // Put on IGVN worklist since at least addp's type was changed above.
 598   record_for_optimizer(addp);
 599   return true;
 600 }
 601 
 602 //
 603 // Create a new version of orig_phi if necessary. Returns either the newly
 604 // created phi or an existing phi.  Sets create_new to indicate whether a new
 605 // phi was created.  Cache the last newly created phi in the node map.
 606 //
 607 PhiNode *ConnectionGraph::create_split_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist, PhaseGVN  *igvn, bool &new_created) {
 608   Compile *C = _compile;
 609   new_created = false;
 610   int phi_alias_idx = C->get_alias_index(orig_phi->adr_type());
 611   // nothing to do if orig_phi is bottom memory or matches alias_idx
 612   if (phi_alias_idx == alias_idx) {
 613     return orig_phi;
 614   }
 615   // Have we recently created a Phi for this alias index?
 616   PhiNode *result = get_map_phi(orig_phi->_idx);
 617   if (result != NULL && C->get_alias_index(result->adr_type()) == alias_idx) {
 618     return result;
 619   }
 620   // Previous check may fail when the same wide memory Phi was split into Phis
 621   // for different memory slices. Search all Phis for this region.
 622   if (result != NULL) {
 623     Node* region = orig_phi->in(0);
 624     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
 625       Node* phi = region->fast_out(i);
 626       if (phi->is_Phi() &&
 627           C->get_alias_index(phi->as_Phi()->adr_type()) == alias_idx) {
 628         assert(phi->_idx >= nodes_size(), "only new Phi per instance memory slice");
 629         return phi->as_Phi();
 630       }
 631     }
 632   }
 633   if ((int)C->unique() + 2*NodeLimitFudgeFactor > MaxNodeLimit) {
 634     if (C->do_escape_analysis() == true && !C->failing()) {
 635       // Retry compilation without escape analysis.
 636       // If this is the first failure, the sentinel string will "stick"
 637       // to the Compile object, and the C2Compiler will see it and retry.
 638       C->record_failure(C2Compiler::retry_no_escape_analysis());
 639     }
 640     return NULL;
 641   }
 642   orig_phi_worklist.append_if_missing(orig_phi);
 643   const TypePtr *atype = C->get_adr_type(alias_idx);
 644   result = PhiNode::make(orig_phi->in(0), NULL, Type::MEMORY, atype);
 645   C->copy_node_notes_to(result, orig_phi);
 646   igvn->set_type(result, result->bottom_type());
 647   record_for_optimizer(result);
 648 
 649   debug_only(Node* pn = ptnode_adr(orig_phi->_idx)->_node;)
 650   assert(pn == NULL || pn == orig_phi, "wrong node");
 651   set_map(orig_phi->_idx, result);
 652   ptnode_adr(orig_phi->_idx)->_node = orig_phi;
 653 
 654   new_created = true;
 655   return result;
 656 }
 657 
 658 //
 659 // Return a new version of Memory Phi "orig_phi" with the inputs having the
 660 // specified alias index.
 661 //
 662 PhiNode *ConnectionGraph::split_memory_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist, PhaseGVN  *igvn) {
 663 
 664   assert(alias_idx != Compile::AliasIdxBot, "can't split out bottom memory");
 665   Compile *C = _compile;
 666   bool new_phi_created;
 667   PhiNode *result = create_split_phi(orig_phi, alias_idx, orig_phi_worklist, igvn, new_phi_created);
 668   if (!new_phi_created) {
 669     return result;
 670   }
 671 
 672   GrowableArray<PhiNode *>  phi_list;
 673   GrowableArray<uint>  cur_input;
 674 
 675   PhiNode *phi = orig_phi;
 676   uint idx = 1;
 677   bool finished = false;
 678   while(!finished) {
 679     while (idx < phi->req()) {
 680       Node *mem = find_inst_mem(phi->in(idx), alias_idx, orig_phi_worklist, igvn);
 681       if (mem != NULL && mem->is_Phi()) {
 682         PhiNode *newphi = create_split_phi(mem->as_Phi(), alias_idx, orig_phi_worklist, igvn, new_phi_created);
 683         if (new_phi_created) {
 684           // found an phi for which we created a new split, push current one on worklist and begin
 685           // processing new one
 686           phi_list.push(phi);
 687           cur_input.push(idx);
 688           phi = mem->as_Phi();
 689           result = newphi;
 690           idx = 1;
 691           continue;
 692         } else {
 693           mem = newphi;
 694         }
 695       }
 696       if (C->failing()) {
 697         return NULL;
 698       }
 699       result->set_req(idx++, mem);
 700     }
 701 #ifdef ASSERT
 702     // verify that the new Phi has an input for each input of the original
 703     assert( phi->req() == result->req(), "must have same number of inputs.");
 704     assert( result->in(0) != NULL && result->in(0) == phi->in(0), "regions must match");
 705 #endif
 706     // Check if all new phi's inputs have specified alias index.
 707     // Otherwise use old phi.
 708     for (uint i = 1; i < phi->req(); i++) {
 709       Node* in = result->in(i);
 710       assert((phi->in(i) == NULL) == (in == NULL), "inputs must correspond.");
 711     }
 712     // we have finished processing a Phi, see if there are any more to do
 713     finished = (phi_list.length() == 0 );
 714     if (!finished) {
 715       phi = phi_list.pop();
 716       idx = cur_input.pop();
 717       PhiNode *prev_result = get_map_phi(phi->_idx);
 718       prev_result->set_req(idx++, result);
 719       result = prev_result;
 720     }
 721   }
 722   return result;
 723 }
 724 
 725 
 726 //
 727 // The next methods are derived from methods in MemNode.
 728 //
 729 static Node *step_through_mergemem(MergeMemNode *mmem, int alias_idx, const TypeOopPtr *toop) {
 730   Node *mem = mmem;
 731   // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
 732   // means an array I have not precisely typed yet.  Do not do any
 733   // alias stuff with it any time soon.
 734   if( toop->base() != Type::AnyPtr &&
 735       !(toop->klass() != NULL &&
 736         toop->klass()->is_java_lang_Object() &&
 737         toop->offset() == Type::OffsetBot) ) {
 738     mem = mmem->memory_at(alias_idx);
 739     // Update input if it is progress over what we have now
 740   }
 741   return mem;
 742 }
 743 
 744 //
 745 // Move memory users to their memory slices.
 746 //
 747 void ConnectionGraph::move_inst_mem(Node* n, GrowableArray<PhiNode *>  &orig_phis, PhaseGVN *igvn) {
 748   Compile* C = _compile;
 749 
 750   const TypePtr* tp = igvn->type(n->in(MemNode::Address))->isa_ptr();
 751   assert(tp != NULL, "ptr type");
 752   int alias_idx = C->get_alias_index(tp);
 753   int general_idx = C->get_general_index(alias_idx);
 754 
 755   // Move users first
 756   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 757     Node* use = n->fast_out(i);
 758     if (use->is_MergeMem()) {
 759       MergeMemNode* mmem = use->as_MergeMem();
 760       assert(n == mmem->memory_at(alias_idx), "should be on instance memory slice");
 761       if (n != mmem->memory_at(general_idx) || alias_idx == general_idx) {
 762         continue; // Nothing to do
 763       }
 764       // Replace previous general reference to mem node.
 765       uint orig_uniq = C->unique();
 766       Node* m = find_inst_mem(n, general_idx, orig_phis, igvn);
 767       assert(orig_uniq == C->unique(), "no new nodes");
 768       mmem->set_memory_at(general_idx, m);
 769       --imax;
 770       --i;
 771     } else if (use->is_MemBar()) {
 772       assert(!use->is_Initialize(), "initializing stores should not be moved");
 773       if (use->req() > MemBarNode::Precedent &&
 774           use->in(MemBarNode::Precedent) == n) {
 775         // Don't move related membars.
 776         record_for_optimizer(use);
 777         continue;
 778       }
 779       tp = use->as_MemBar()->adr_type()->isa_ptr();
 780       if (tp != NULL && C->get_alias_index(tp) == alias_idx ||
 781           alias_idx == general_idx) {
 782         continue; // Nothing to do
 783       }
 784       // Move to general memory slice.
 785       uint orig_uniq = C->unique();
 786       Node* m = find_inst_mem(n, general_idx, orig_phis, igvn);
 787       assert(orig_uniq == C->unique(), "no new nodes");
 788       igvn->hash_delete(use);
 789       imax -= use->replace_edge(n, m);
 790       igvn->hash_insert(use);
 791       record_for_optimizer(use);
 792       --i;
 793 #ifdef ASSERT
 794     } else if (use->is_Mem()) {
 795       if (use->Opcode() == Op_StoreCM && use->in(MemNode::OopStore) == n) {
 796         // Don't move related cardmark.
 797         continue;
 798       }
 799       // Memory nodes should have new memory input.
 800       tp = igvn->type(use->in(MemNode::Address))->isa_ptr();
 801       assert(tp != NULL, "ptr type");
 802       int idx = C->get_alias_index(tp);
 803       assert(get_map(use->_idx) != NULL || idx == alias_idx,
 804              "Following memory nodes should have new memory input or be on the same memory slice");
 805     } else if (use->is_Phi()) {
 806       // Phi nodes should be split and moved already.
 807       tp = use->as_Phi()->adr_type()->isa_ptr();
 808       assert(tp != NULL, "ptr type");
 809       int idx = C->get_alias_index(tp);
 810       assert(idx == alias_idx, "Following Phi nodes should be on the same memory slice");
 811     } else {
 812       use->dump();
 813       assert(false, "should not be here");
 814 #endif
 815     }
 816   }
 817 }
 818 
 819 //
 820 // Search memory chain of "mem" to find a MemNode whose address
 821 // is the specified alias index.
 822 //
 823 Node* ConnectionGraph::find_inst_mem(Node *orig_mem, int alias_idx, GrowableArray<PhiNode *>  &orig_phis, PhaseGVN *phase) {
 824   if (orig_mem == NULL)
 825     return orig_mem;
 826   Compile* C = phase->C;
 827   const TypeOopPtr *toop = C->get_adr_type(alias_idx)->isa_oopptr();
 828   bool is_instance = (toop != NULL) && toop->is_known_instance();
 829   Node *start_mem = C->start()->proj_out(TypeFunc::Memory);
 830   Node *prev = NULL;
 831   Node *result = orig_mem;
 832   while (prev != result) {
 833     prev = result;
 834     if (result == start_mem)
 835       break;  // hit one of our sentinels
 836     if (result->is_Mem()) {
 837       const Type *at = phase->type(result->in(MemNode::Address));
 838       if (at == Type::TOP)
 839         break; // Dead
 840       assert (at->isa_ptr() != NULL, "pointer type required.");
 841       int idx = C->get_alias_index(at->is_ptr());
 842       if (idx == alias_idx)
 843         break; // Found
 844       if (!is_instance && (at->isa_oopptr() == NULL ||
 845                            !at->is_oopptr()->is_known_instance())) {
 846         break; // Do not skip store to general memory slice.
 847       }
 848       result = result->in(MemNode::Memory);
 849     }
 850     if (!is_instance)
 851       continue;  // don't search further for non-instance types
 852     // skip over a call which does not affect this memory slice
 853     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
 854       Node *proj_in = result->in(0);
 855       if (proj_in->is_Allocate() && proj_in->_idx == (uint)toop->instance_id()) {
 856         break;  // hit one of our sentinels
 857       } else if (proj_in->is_Call()) {
 858         CallNode *call = proj_in->as_Call();
 859         if (!call->may_modify(toop, phase)) {
 860           result = call->in(TypeFunc::Memory);
 861         }
 862       } else if (proj_in->is_Initialize()) {
 863         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
 864         // Stop if this is the initialization for the object instance which
 865         // which contains this memory slice, otherwise skip over it.
 866         if (alloc == NULL || alloc->_idx != (uint)toop->instance_id()) {
 867           result = proj_in->in(TypeFunc::Memory);
 868         }
 869       } else if (proj_in->is_MemBar()) {
 870         result = proj_in->in(TypeFunc::Memory);
 871       }
 872     } else if (result->is_MergeMem()) {
 873       MergeMemNode *mmem = result->as_MergeMem();
 874       result = step_through_mergemem(mmem, alias_idx, toop);
 875       if (result == mmem->base_memory()) {
 876         // Didn't find instance memory, search through general slice recursively.
 877         result = mmem->memory_at(C->get_general_index(alias_idx));
 878         result = find_inst_mem(result, alias_idx, orig_phis, phase);
 879         if (C->failing()) {
 880           return NULL;
 881         }
 882         mmem->set_memory_at(alias_idx, result);
 883       }
 884     } else if (result->is_Phi() &&
 885                C->get_alias_index(result->as_Phi()->adr_type()) != alias_idx) {
 886       Node *un = result->as_Phi()->unique_input(phase);
 887       if (un != NULL) {
 888         orig_phis.append_if_missing(result->as_Phi());
 889         result = un;
 890       } else {
 891         break;
 892       }
 893     } else if (result->is_ClearArray()) {
 894       if (!ClearArrayNode::step_through(&result, (uint)toop->instance_id(), phase)) {
 895         // Can not bypass initialization of the instance
 896         // we are looking for.
 897         break;
 898       }
 899       // Otherwise skip it (the call updated 'result' value).
 900     } else if (result->Opcode() == Op_SCMemProj) {
 901       assert(result->in(0)->is_LoadStore(), "sanity");
 902       const Type *at = phase->type(result->in(0)->in(MemNode::Address));
 903       if (at != Type::TOP) {
 904         assert (at->isa_ptr() != NULL, "pointer type required.");
 905         int idx = C->get_alias_index(at->is_ptr());
 906         assert(idx != alias_idx, "Object is not scalar replaceable if a LoadStore node access its field");
 907         break;
 908       }
 909       result = result->in(0)->in(MemNode::Memory);
 910     }
 911   }
 912   if (result->is_Phi()) {
 913     PhiNode *mphi = result->as_Phi();
 914     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
 915     const TypePtr *t = mphi->adr_type();
 916     if (!is_instance) {
 917       // Push all non-instance Phis on the orig_phis worklist to update inputs
 918       // during Phase 4 if needed.
 919       orig_phis.append_if_missing(mphi);
 920     } else if (C->get_alias_index(t) != alias_idx) {
 921       // Create a new Phi with the specified alias index type.
 922       result = split_memory_phi(mphi, alias_idx, orig_phis, phase);
 923     }
 924   }
 925   // the result is either MemNode, PhiNode, InitializeNode.
 926   return result;
 927 }
 928 
 929 //
 930 //  Convert the types of unescaped object to instance types where possible,
 931 //  propagate the new type information through the graph, and update memory
 932 //  edges and MergeMem inputs to reflect the new type.
 933 //
 934 //  We start with allocations (and calls which may be allocations)  on alloc_worklist.
 935 //  The processing is done in 4 phases:
 936 //
 937 //  Phase 1:  Process possible allocations from alloc_worklist.  Create instance
 938 //            types for the CheckCastPP for allocations where possible.
 939 //            Propagate the the new types through users as follows:
 940 //               casts and Phi:  push users on alloc_worklist
 941 //               AddP:  cast Base and Address inputs to the instance type
 942 //                      push any AddP users on alloc_worklist and push any memnode
 943 //                      users onto memnode_worklist.
 944 //  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
 945 //            search the Memory chain for a store with the appropriate type
 946 //            address type.  If a Phi is found, create a new version with
 947 //            the appropriate memory slices from each of the Phi inputs.
 948 //            For stores, process the users as follows:
 949 //               MemNode:  push on memnode_worklist
 950 //               MergeMem: push on mergemem_worklist
 951 //  Phase 3:  Process MergeMem nodes from mergemem_worklist.  Walk each memory slice
 952 //            moving the first node encountered of each  instance type to the
 953 //            the input corresponding to its alias index.
 954 //            appropriate memory slice.
 955 //  Phase 4:  Update the inputs of non-instance memory Phis and the Memory input of memnodes.
 956 //
 957 // In the following example, the CheckCastPP nodes are the cast of allocation
 958 // results and the allocation of node 29 is unescaped and eligible to be an
 959 // instance type.
 960 //
 961 // We start with:
 962 //
 963 //     7 Parm #memory
 964 //    10  ConI  "12"
 965 //    19  CheckCastPP   "Foo"
 966 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
 967 //    29  CheckCastPP   "Foo"
 968 //    30  AddP  _ 29 29 10  Foo+12  alias_index=4
 969 //
 970 //    40  StoreP  25   7  20   ... alias_index=4
 971 //    50  StoreP  35  40  30   ... alias_index=4
 972 //    60  StoreP  45  50  20   ... alias_index=4
 973 //    70  LoadP    _  60  30   ... alias_index=4
 974 //    80  Phi     75  50  60   Memory alias_index=4
 975 //    90  LoadP    _  80  30   ... alias_index=4
 976 //   100  LoadP    _  80  20   ... alias_index=4
 977 //
 978 //
 979 // Phase 1 creates an instance type for node 29 assigning it an instance id of 24
 980 // and creating a new alias index for node 30.  This gives:
 981 //
 982 //     7 Parm #memory
 983 //    10  ConI  "12"
 984 //    19  CheckCastPP   "Foo"
 985 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
 986 //    29  CheckCastPP   "Foo"  iid=24
 987 //    30  AddP  _ 29 29 10  Foo+12  alias_index=6  iid=24
 988 //
 989 //    40  StoreP  25   7  20   ... alias_index=4
 990 //    50  StoreP  35  40  30   ... alias_index=6
 991 //    60  StoreP  45  50  20   ... alias_index=4
 992 //    70  LoadP    _  60  30   ... alias_index=6
 993 //    80  Phi     75  50  60   Memory alias_index=4
 994 //    90  LoadP    _  80  30   ... alias_index=6
 995 //   100  LoadP    _  80  20   ... alias_index=4
 996 //
 997 // In phase 2, new memory inputs are computed for the loads and stores,
 998 // And a new version of the phi is created.  In phase 4, the inputs to
 999 // node 80 are updated and then the memory nodes are updated with the
1000 // values computed in phase 2.  This results in:
1001 //
1002 //     7 Parm #memory
1003 //    10  ConI  "12"
1004 //    19  CheckCastPP   "Foo"
1005 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
1006 //    29  CheckCastPP   "Foo"  iid=24
1007 //    30  AddP  _ 29 29 10  Foo+12  alias_index=6  iid=24
1008 //
1009 //    40  StoreP  25  7   20   ... alias_index=4
1010 //    50  StoreP  35  7   30   ... alias_index=6
1011 //    60  StoreP  45  40  20   ... alias_index=4
1012 //    70  LoadP    _  50  30   ... alias_index=6
1013 //    80  Phi     75  40  60   Memory alias_index=4
1014 //   120  Phi     75  50  50   Memory alias_index=6
1015 //    90  LoadP    _ 120  30   ... alias_index=6
1016 //   100  LoadP    _  80  20   ... alias_index=4
1017 //
1018 void ConnectionGraph::split_unique_types(GrowableArray<Node *>  &alloc_worklist) {
1019   GrowableArray<Node *>  memnode_worklist;
1020   GrowableArray<PhiNode *>  orig_phis;
1021 
1022   PhaseIterGVN  *igvn = _igvn;
1023   uint new_index_start = (uint) _compile->num_alias_types();
1024   Arena* arena = Thread::current()->resource_area();
1025   VectorSet visited(arena);
1026 
1027 
1028   //  Phase 1:  Process possible allocations from alloc_worklist.
1029   //  Create instance types for the CheckCastPP for allocations where possible.
1030   //
1031   // (Note: don't forget to change the order of the second AddP node on
1032   //  the alloc_worklist if the order of the worklist processing is changed,
1033   //  see the comment in find_second_addp().)
1034   //
1035   while (alloc_worklist.length() != 0) {
1036     Node *n = alloc_worklist.pop();
1037     uint ni = n->_idx;
1038     const TypeOopPtr* tinst = NULL;
1039     if (n->is_Call()) {
1040       CallNode *alloc = n->as_Call();
1041       // copy escape information to call node
1042       PointsToNode* ptn = ptnode_adr(alloc->_idx);
1043       PointsToNode::EscapeState es = escape_state(alloc);
1044       // We have an allocation or call which returns a Java object,
1045       // see if it is unescaped.
1046       if (es != PointsToNode::NoEscape)
1047         continue;
1048 
1049       // Find CheckCastPP for the allocate or for the return value of a call
1050       n = alloc->result_cast();
1051       if (n == NULL) {            // No uses except Initialize node
1052         if (alloc->is_Allocate()) {
1053           // Set the scalar_replaceable flag for allocation
1054           // so it could be eliminated if it has no uses.
1055           alloc->as_Allocate()->_is_scalar_replaceable = true;
1056         }
1057         continue;
1058       }
1059       if (!n->is_CheckCastPP()) { // not unique CheckCastPP.
1060         assert(!alloc->is_Allocate(), "allocation should have unique type");
1061         continue;
1062       }
1063 
1064       // The inline code for Object.clone() casts the allocation result to
1065       // java.lang.Object and then to the actual type of the allocated
1066       // object. Detect this case and use the second cast.
1067       // Also detect j.l.reflect.Array.newInstance(jobject, jint) case when
1068       // the allocation result is cast to java.lang.Object and then
1069       // to the actual Array type.
1070       if (alloc->is_Allocate() && n->as_Type()->type() == TypeInstPtr::NOTNULL
1071           && (alloc->is_AllocateArray() ||
1072               igvn->type(alloc->in(AllocateNode::KlassNode)) != TypeKlassPtr::OBJECT)) {
1073         Node *cast2 = NULL;
1074         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1075           Node *use = n->fast_out(i);
1076           if (use->is_CheckCastPP()) {
1077             cast2 = use;
1078             break;
1079           }
1080         }
1081         if (cast2 != NULL) {
1082           n = cast2;
1083         } else {
1084           // Non-scalar replaceable if the allocation type is unknown statically
1085           // (reflection allocation), the object can't be restored during
1086           // deoptimization without precise type.
1087           continue;
1088         }
1089       }
1090       if (alloc->is_Allocate()) {
1091         // Set the scalar_replaceable flag for allocation
1092         // so it could be eliminated.
1093         alloc->as_Allocate()->_is_scalar_replaceable = true;
1094       }
1095       set_escape_state(n->_idx, es);
1096       // in order for an object to be scalar-replaceable, it must be:
1097       //   - a direct allocation (not a call returning an object)
1098       //   - non-escaping
1099       //   - eligible to be a unique type
1100       //   - not determined to be ineligible by escape analysis
1101       assert(ptnode_adr(alloc->_idx)->_node != NULL &&
1102              ptnode_adr(n->_idx)->_node != NULL, "should be registered");
1103       set_map(alloc->_idx, n);
1104       set_map(n->_idx, alloc);
1105       const TypeOopPtr *t = igvn->type(n)->isa_oopptr();
1106       if (t == NULL)
1107         continue;  // not a TypeOopPtr
1108       tinst = t->cast_to_exactness(true)->is_oopptr()->cast_to_instance_id(ni);
1109       igvn->hash_delete(n);
1110       igvn->set_type(n,  tinst);
1111       n->raise_bottom_type(tinst);
1112       igvn->hash_insert(n);
1113       record_for_optimizer(n);
1114       if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
1115 
1116         // First, put on the worklist all Field edges from Connection Graph
1117         // which is more accurate then putting immediate users from Ideal Graph.
1118         for (uint e = 0; e < ptn->edge_count(); e++) {
1119           Node *use = ptnode_adr(ptn->edge_target(e))->_node;
1120           assert(ptn->edge_type(e) == PointsToNode::FieldEdge && use->is_AddP(),
1121                  "only AddP nodes are Field edges in CG");
1122           if (use->outcnt() > 0) { // Don't process dead nodes
1123             Node* addp2 = find_second_addp(use, use->in(AddPNode::Base));
1124             if (addp2 != NULL) {
1125               assert(alloc->is_AllocateArray(),"array allocation was expected");
1126               alloc_worklist.append_if_missing(addp2);
1127             }
1128             alloc_worklist.append_if_missing(use);
1129           }
1130         }
1131 
1132         // An allocation may have an Initialize which has raw stores. Scan
1133         // the users of the raw allocation result and push AddP users
1134         // on alloc_worklist.
1135         Node *raw_result = alloc->proj_out(TypeFunc::Parms);
1136         assert (raw_result != NULL, "must have an allocation result");
1137         for (DUIterator_Fast imax, i = raw_result->fast_outs(imax); i < imax; i++) {
1138           Node *use = raw_result->fast_out(i);
1139           if (use->is_AddP() && use->outcnt() > 0) { // Don't process dead nodes
1140             Node* addp2 = find_second_addp(use, raw_result);
1141             if (addp2 != NULL) {
1142               assert(alloc->is_AllocateArray(),"array allocation was expected");
1143               alloc_worklist.append_if_missing(addp2);
1144             }
1145             alloc_worklist.append_if_missing(use);
1146           } else if (use->is_MemBar()) {
1147             memnode_worklist.append_if_missing(use);
1148           }
1149         }
1150       }
1151     } else if (n->is_AddP()) {
1152       VectorSet* ptset = PointsTo(get_addp_base(n));
1153       assert(ptset->Size() == 1, "AddP address is unique");
1154       uint elem = ptset->getelem(); // Allocation node's index
1155       if (elem == _phantom_object) {
1156         assert(false, "escaped allocation");
1157         continue; // Assume the value was set outside this method.
1158       }
1159       Node *base = get_map(elem);  // CheckCastPP node
1160       if (!split_AddP(n, base, igvn)) continue; // wrong type from dead path
1161       tinst = igvn->type(base)->isa_oopptr();
1162     } else if (n->is_Phi() ||
1163                n->is_CheckCastPP() ||
1164                n->is_EncodeP() ||
1165                n->is_DecodeN() ||
1166                (n->is_ConstraintCast() && n->Opcode() == Op_CastPP)) {
1167       if (visited.test_set(n->_idx)) {
1168         assert(n->is_Phi(), "loops only through Phi's");
1169         continue;  // already processed
1170       }
1171       VectorSet* ptset = PointsTo(n);
1172       if (ptset->Size() == 1) {
1173         uint elem = ptset->getelem(); // Allocation node's index
1174         if (elem == _phantom_object) {
1175           assert(false, "escaped allocation");
1176           continue; // Assume the value was set outside this method.
1177         }
1178         Node *val = get_map(elem);   // CheckCastPP node
1179         TypeNode *tn = n->as_Type();
1180         tinst = igvn->type(val)->isa_oopptr();
1181         assert(tinst != NULL && tinst->is_known_instance() &&
1182                (uint)tinst->instance_id() == elem , "instance type expected.");
1183 
1184         const Type *tn_type = igvn->type(tn);
1185         const TypeOopPtr *tn_t;
1186         if (tn_type->isa_narrowoop()) {
1187           tn_t = tn_type->make_ptr()->isa_oopptr();
1188         } else {
1189           tn_t = tn_type->isa_oopptr();
1190         }
1191 
1192         if (tn_t != NULL && tinst->klass()->is_subtype_of(tn_t->klass())) {
1193           if (tn_type->isa_narrowoop()) {
1194             tn_type = tinst->make_narrowoop();
1195           } else {
1196             tn_type = tinst;
1197           }
1198           igvn->hash_delete(tn);
1199           igvn->set_type(tn, tn_type);
1200           tn->set_type(tn_type);
1201           igvn->hash_insert(tn);
1202           record_for_optimizer(n);
1203         } else {
1204           assert(tn_type == TypePtr::NULL_PTR ||
1205                  tn_t != NULL && !tinst->klass()->is_subtype_of(tn_t->klass()),
1206                  "unexpected type");
1207           continue; // Skip dead path with different type
1208         }
1209       }
1210     } else {
1211       debug_only(n->dump();)
1212       assert(false, "EA: unexpected node");
1213       continue;
1214     }
1215     // push allocation's users on appropriate worklist
1216     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1217       Node *use = n->fast_out(i);
1218       if(use->is_Mem() && use->in(MemNode::Address) == n) {
1219         // Load/store to instance's field
1220         memnode_worklist.append_if_missing(use);
1221       } else if (use->is_MemBar()) {
1222         memnode_worklist.append_if_missing(use);
1223       } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
1224         Node* addp2 = find_second_addp(use, n);
1225         if (addp2 != NULL) {
1226           alloc_worklist.append_if_missing(addp2);
1227         }
1228         alloc_worklist.append_if_missing(use);
1229       } else if (use->is_Phi() ||
1230                  use->is_CheckCastPP() ||
1231                  use->is_EncodeP() ||
1232                  use->is_DecodeN() ||
1233                  (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
1234         alloc_worklist.append_if_missing(use);
1235 #ifdef ASSERT
1236       } else if (use->is_Mem()) {
1237         assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
1238       } else if (use->is_MergeMem()) {
1239         assert(_mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
1240       } else if (use->is_SafePoint()) {
1241         // Look for MergeMem nodes for calls which reference unique allocation
1242         // (through CheckCastPP nodes) even for debug info.
1243         Node* m = use->in(TypeFunc::Memory);
1244         if (m->is_MergeMem()) {
1245           assert(_mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
1246         }
1247       } else {
1248         uint op = use->Opcode();
1249         if (!(op == Op_CmpP || op == Op_Conv2B ||
1250               op == Op_CastP2X || op == Op_StoreCM ||
1251               op == Op_FastLock || op == Op_AryEq || op == Op_StrComp ||
1252               op == Op_StrEquals || op == Op_StrIndexOf)) {
1253           n->dump();
1254           use->dump();
1255           assert(false, "EA: missing allocation reference path");
1256         }
1257 #endif
1258       }
1259     }
1260 
1261   }
1262   // New alias types were created in split_AddP().
1263   uint new_index_end = (uint) _compile->num_alias_types();
1264 
1265   //  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
1266   //            compute new values for Memory inputs  (the Memory inputs are not
1267   //            actually updated until phase 4.)
1268   if (memnode_worklist.length() == 0)
1269     return;  // nothing to do
1270 
1271   while (memnode_worklist.length() != 0) {
1272     Node *n = memnode_worklist.pop();
1273     if (visited.test_set(n->_idx))
1274       continue;
1275     if (n->is_Phi() || n->is_ClearArray()) {
1276       // we don't need to do anything, but the users must be pushed
1277     } else if (n->is_MemBar()) { // Initialize, MemBar nodes
1278       // we don't need to do anything, but the users must be pushed
1279       n = n->as_MemBar()->proj_out(TypeFunc::Memory);
1280       if (n == NULL)
1281         continue;
1282     } else {
1283       assert(n->is_Mem(), "memory node required.");
1284       Node *addr = n->in(MemNode::Address);
1285       const Type *addr_t = igvn->type(addr);
1286       if (addr_t == Type::TOP)
1287         continue;
1288       assert (addr_t->isa_ptr() != NULL, "pointer type required.");
1289       int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
1290       assert ((uint)alias_idx < new_index_end, "wrong alias index");
1291       Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis, igvn);
1292       if (_compile->failing()) {
1293         return;
1294       }
1295       if (mem != n->in(MemNode::Memory)) {
1296         // We delay the memory edge update since we need old one in
1297         // MergeMem code below when instances memory slices are separated.
1298         debug_only(Node* pn = ptnode_adr(n->_idx)->_node;)
1299         assert(pn == NULL || pn == n, "wrong node");
1300         set_map(n->_idx, mem);
1301         ptnode_adr(n->_idx)->_node = n;
1302       }
1303       if (n->is_Load()) {
1304         continue;  // don't push users
1305       } else if (n->is_LoadStore()) {
1306         // get the memory projection
1307         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1308           Node *use = n->fast_out(i);
1309           if (use->Opcode() == Op_SCMemProj) {
1310             n = use;
1311             break;
1312           }
1313         }
1314         assert(n->Opcode() == Op_SCMemProj, "memory projection required");
1315       }
1316     }
1317     // push user on appropriate worklist
1318     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1319       Node *use = n->fast_out(i);
1320       if (use->is_Phi() || use->is_ClearArray()) {
1321         memnode_worklist.append_if_missing(use);
1322       } else if(use->is_Mem() && use->in(MemNode::Memory) == n) {
1323         if (use->Opcode() == Op_StoreCM) // Ignore cardmark stores
1324           continue;
1325         memnode_worklist.append_if_missing(use);
1326       } else if (use->is_MemBar()) {
1327         memnode_worklist.append_if_missing(use);
1328 #ifdef ASSERT
1329       } else if(use->is_Mem()) {
1330         assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
1331       } else if (use->is_MergeMem()) {
1332         assert(_mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
1333       } else {
1334         uint op = use->Opcode();
1335         if (!(op == Op_StoreCM ||
1336               (op == Op_CallLeaf && use->as_CallLeaf()->_name != NULL &&
1337                strcmp(use->as_CallLeaf()->_name, "g1_wb_pre") == 0) ||
1338               op == Op_AryEq || op == Op_StrComp ||
1339               op == Op_StrEquals || op == Op_StrIndexOf)) {
1340           n->dump();
1341           use->dump();
1342           assert(false, "EA: missing memory path");
1343         }
1344 #endif
1345       }
1346     }
1347   }
1348 
1349   //  Phase 3:  Process MergeMem nodes from mergemem_worklist.
1350   //            Walk each memory slice moving the first node encountered of each
1351   //            instance type to the the input corresponding to its alias index.
1352   uint length = _mergemem_worklist.length();
1353   for( uint next = 0; next < length; ++next ) {
1354     MergeMemNode* nmm = _mergemem_worklist.at(next);
1355     assert(!visited.test_set(nmm->_idx), "should not be visited before");
1356     // Note: we don't want to use MergeMemStream here because we only want to
1357     // scan inputs which exist at the start, not ones we add during processing.
1358     // Note 2: MergeMem may already contains instance memory slices added
1359     // during find_inst_mem() call when memory nodes were processed above.
1360     igvn->hash_delete(nmm);
1361     uint nslices = nmm->req();
1362     for (uint i = Compile::AliasIdxRaw+1; i < nslices; i++) {
1363       Node* mem = nmm->in(i);
1364       Node* cur = NULL;
1365       if (mem == NULL || mem->is_top())
1366         continue;
1367       // First, update mergemem by moving memory nodes to corresponding slices
1368       // if their type became more precise since this mergemem was created.
1369       while (mem->is_Mem()) {
1370         const Type *at = igvn->type(mem->in(MemNode::Address));
1371         if (at != Type::TOP) {
1372           assert (at->isa_ptr() != NULL, "pointer type required.");
1373           uint idx = (uint)_compile->get_alias_index(at->is_ptr());
1374           if (idx == i) {
1375             if (cur == NULL)
1376               cur = mem;
1377           } else {
1378             if (idx >= nmm->req() || nmm->is_empty_memory(nmm->in(idx))) {
1379               nmm->set_memory_at(idx, mem);
1380             }
1381           }
1382         }
1383         mem = mem->in(MemNode::Memory);
1384       }
1385       nmm->set_memory_at(i, (cur != NULL) ? cur : mem);
1386       // Find any instance of the current type if we haven't encountered
1387       // already a memory slice of the instance along the memory chain.
1388       for (uint ni = new_index_start; ni < new_index_end; ni++) {
1389         if((uint)_compile->get_general_index(ni) == i) {
1390           Node *m = (ni >= nmm->req()) ? nmm->empty_memory() : nmm->in(ni);
1391           if (nmm->is_empty_memory(m)) {
1392             Node* result = find_inst_mem(mem, ni, orig_phis, igvn);
1393             if (_compile->failing()) {
1394               return;
1395             }
1396             nmm->set_memory_at(ni, result);
1397           }
1398         }
1399       }
1400     }
1401     // Find the rest of instances values
1402     for (uint ni = new_index_start; ni < new_index_end; ni++) {
1403       const TypeOopPtr *tinst = _compile->get_adr_type(ni)->isa_oopptr();
1404       Node* result = step_through_mergemem(nmm, ni, tinst);
1405       if (result == nmm->base_memory()) {
1406         // Didn't find instance memory, search through general slice recursively.
1407         result = nmm->memory_at(_compile->get_general_index(ni));
1408         result = find_inst_mem(result, ni, orig_phis, igvn);
1409         if (_compile->failing()) {
1410           return;
1411         }
1412         nmm->set_memory_at(ni, result);
1413       }
1414     }
1415     igvn->hash_insert(nmm);
1416     record_for_optimizer(nmm);
1417   }
1418 
1419   //  Phase 4:  Update the inputs of non-instance memory Phis and
1420   //            the Memory input of memnodes
1421   // First update the inputs of any non-instance Phi's from
1422   // which we split out an instance Phi.  Note we don't have
1423   // to recursively process Phi's encounted on the input memory
1424   // chains as is done in split_memory_phi() since they  will
1425   // also be processed here.
1426   for (int j = 0; j < orig_phis.length(); j++) {
1427     PhiNode *phi = orig_phis.at(j);
1428     int alias_idx = _compile->get_alias_index(phi->adr_type());
1429     igvn->hash_delete(phi);
1430     for (uint i = 1; i < phi->req(); i++) {
1431       Node *mem = phi->in(i);
1432       Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis, igvn);
1433       if (_compile->failing()) {
1434         return;
1435       }
1436       if (mem != new_mem) {
1437         phi->set_req(i, new_mem);
1438       }
1439     }
1440     igvn->hash_insert(phi);
1441     record_for_optimizer(phi);
1442   }
1443 
1444   // Update the memory inputs of MemNodes with the value we computed
1445   // in Phase 2 and move stores memory users to corresponding memory slices.
1446 
1447   // Disable memory split verification code until the fix for 6984348.
1448   // Currently it produces false negative results since it does not cover all cases.
1449 #if 0 // ifdef ASSERT
1450   visited.Reset();
1451   Node_Stack old_mems(arena, _compile->unique() >> 2);
1452 #endif
1453   for (uint i = 0; i < nodes_size(); i++) {
1454     Node *nmem = get_map(i);
1455     if (nmem != NULL) {
1456       Node *n = ptnode_adr(i)->_node;
1457       assert(n != NULL, "sanity");
1458       if (n->is_Mem()) {
1459 #if 0 // ifdef ASSERT
1460         Node* old_mem = n->in(MemNode::Memory);
1461         if (!visited.test_set(old_mem->_idx)) {
1462           old_mems.push(old_mem, old_mem->outcnt());
1463         }
1464 #endif
1465         assert(n->in(MemNode::Memory) != nmem, "sanity");
1466         if (!n->is_Load()) {
1467           // Move memory users of a store first.
1468           move_inst_mem(n, orig_phis, igvn);
1469         }
1470         // Now update memory input
1471         igvn->hash_delete(n);
1472         n->set_req(MemNode::Memory, nmem);
1473         igvn->hash_insert(n);
1474         record_for_optimizer(n);
1475       } else {
1476         assert(n->is_Allocate() || n->is_CheckCastPP() ||
1477                n->is_AddP() || n->is_Phi(), "unknown node used for set_map()");
1478       }
1479     }
1480   }
1481 #if 0 // ifdef ASSERT
1482   // Verify that memory was split correctly
1483   while (old_mems.is_nonempty()) {
1484     Node* old_mem = old_mems.node();
1485     uint  old_cnt = old_mems.index();
1486     old_mems.pop();
1487     assert(old_cnt == old_mem->outcnt(), "old mem could be lost");
1488   }
1489 #endif
1490 }
1491 
1492 bool ConnectionGraph::has_candidates(Compile *C) {
1493   // EA brings benefits only when the code has allocations and/or locks which
1494   // are represented by ideal Macro nodes.
1495   int cnt = C->macro_count();
1496   for( int i=0; i < cnt; i++ ) {
1497     Node *n = C->macro_node(i);
1498     if ( n->is_Allocate() )
1499       return true;
1500     if( n->is_Lock() ) {
1501       Node* obj = n->as_Lock()->obj_node()->uncast();
1502       if( !(obj->is_Parm() || obj->is_Con()) )
1503         return true;
1504     }
1505   }
1506   return false;
1507 }
1508 
1509 void ConnectionGraph::do_analysis(Compile *C, PhaseIterGVN *igvn) {
1510   // Add ConP#NULL and ConN#NULL nodes before ConnectionGraph construction
1511   // to create space for them in ConnectionGraph::_nodes[].
1512   Node* oop_null = igvn->zerocon(T_OBJECT);
1513   Node* noop_null = igvn->zerocon(T_NARROWOOP);
1514 
1515   ConnectionGraph* congraph = new(C->comp_arena()) ConnectionGraph(C, igvn);
1516   // Perform escape analysis
1517   if (congraph->compute_escape()) {
1518     // There are non escaping objects.
1519     C->set_congraph(congraph);
1520   }
1521 
1522   // Cleanup.
1523   if (oop_null->outcnt() == 0)
1524     igvn->hash_delete(oop_null);
1525   if (noop_null->outcnt() == 0)
1526     igvn->hash_delete(noop_null);
1527 }
1528 
1529 bool ConnectionGraph::compute_escape() {
1530   Compile* C = _compile;
1531 
1532   // 1. Populate Connection Graph (CG) with Ideal nodes.
1533 
1534   Unique_Node_List worklist_init;
1535   worklist_init.map(C->unique(), NULL);  // preallocate space
1536 
1537   // Initialize worklist
1538   if (C->root() != NULL) {
1539     worklist_init.push(C->root());
1540   }
1541 
1542   GrowableArray<Node*> alloc_worklist;
1543   GrowableArray<int> cg_worklist;
1544   PhaseGVN* igvn = _igvn;
1545   bool has_allocations = false;
1546 
1547   // Push all useful nodes onto CG list and set their type.
1548   for( uint next = 0; next < worklist_init.size(); ++next ) {
1549     Node* n = worklist_init.at(next);
1550     record_for_escape_analysis(n, igvn);
1551     // Only allocations and java static calls results are checked
1552     // for an escape status. See process_call_result() below.
1553     if (n->is_Allocate() || n->is_CallStaticJava() &&
1554         ptnode_adr(n->_idx)->node_type() == PointsToNode::JavaObject) {
1555       has_allocations = true;
1556       if (n->is_Allocate())
1557         alloc_worklist.append(n);
1558     }
1559     if(n->is_AddP()) {
1560       // Collect address nodes. Use them during stage 3 below
1561       // to build initial connection graph field edges.
1562       cg_worklist.append(n->_idx);
1563     } else if (n->is_MergeMem()) {
1564       // Collect all MergeMem nodes to add memory slices for
1565       // scalar replaceable objects in split_unique_types().
1566       _mergemem_worklist.append(n->as_MergeMem());
1567     }
1568     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1569       Node* m = n->fast_out(i);   // Get user
1570       worklist_init.push(m);
1571     }
1572   }
1573 
1574   if (!has_allocations) {
1575     _collecting = false;
1576     return false; // Nothing to do.
1577   }
1578 
1579   // 2. First pass to create simple CG edges (doesn't require to walk CG).
1580   uint delayed_size = _delayed_worklist.size();
1581   for( uint next = 0; next < delayed_size; ++next ) {
1582     Node* n = _delayed_worklist.at(next);
1583     build_connection_graph(n, igvn);
1584   }
1585 
1586   // 3. Pass to create initial fields edges (JavaObject -F-> AddP)
1587   //    to reduce number of iterations during stage 4 below.
1588   uint cg_length = cg_worklist.length();
1589   for( uint next = 0; next < cg_length; ++next ) {
1590     int ni = cg_worklist.at(next);
1591     Node* n = ptnode_adr(ni)->_node;
1592     Node* base = get_addp_base(n);
1593     if (base->is_Proj())
1594       base = base->in(0);
1595     PointsToNode::NodeType nt = ptnode_adr(base->_idx)->node_type();
1596     if (nt == PointsToNode::JavaObject) {
1597       build_connection_graph(n, igvn);
1598     }
1599   }
1600 
1601   cg_worklist.clear();
1602   cg_worklist.append(_phantom_object);
1603   GrowableArray<uint>  worklist;
1604 
1605   // 4. Build Connection Graph which need
1606   //    to walk the connection graph.
1607   _progress = false;
1608   for (uint ni = 0; ni < nodes_size(); ni++) {
1609     PointsToNode* ptn = ptnode_adr(ni);
1610     Node *n = ptn->_node;
1611     if (n != NULL) { // Call, AddP, LoadP, StoreP
1612       build_connection_graph(n, igvn);
1613       if (ptn->node_type() != PointsToNode::UnknownType)
1614         cg_worklist.append(n->_idx); // Collect CG nodes
1615       if (!_processed.test(n->_idx))
1616         worklist.append(n->_idx); // Collect C/A/L/S nodes
1617     }
1618   }
1619 
1620   // After IGVN user nodes may have smaller _idx than
1621   // their inputs so they will be processed first in
1622   // previous loop. Because of that not all Graph
1623   // edges will be created. Walk over interesting
1624   // nodes again until no new edges are created.
1625   //
1626   // Normally only 1-3 passes needed to build
1627   // Connection Graph depending on graph complexity.
1628   // Observed 8 passes in jvm2008 compiler.compiler.
1629   // Set limit to 20 to catch situation when something
1630   // did go wrong and recompile the method without EA.
1631 
1632 #define CG_BUILD_ITER_LIMIT 20
1633 
1634   uint length = worklist.length();
1635   int iterations = 0;
1636   while(_progress && (iterations++ < CG_BUILD_ITER_LIMIT)) {
1637     _progress = false;
1638     for( uint next = 0; next < length; ++next ) {
1639       int ni = worklist.at(next);
1640       PointsToNode* ptn = ptnode_adr(ni);
1641       Node* n = ptn->_node;
1642       assert(n != NULL, "should be known node");
1643       build_connection_graph(n, igvn);
1644     }
1645   }
1646   if (iterations >= CG_BUILD_ITER_LIMIT) {
1647     assert(iterations < CG_BUILD_ITER_LIMIT,
1648            err_msg("infinite EA connection graph build with %d nodes and worklist size %d",
1649            nodes_size(), length));
1650     // Possible infinite build_connection_graph loop,
1651     // retry compilation without escape analysis.
1652     C->record_failure(C2Compiler::retry_no_escape_analysis());
1653     _collecting = false;
1654     return false;
1655   }
1656 #undef CG_BUILD_ITER_LIMIT
1657 
1658   Arena* arena = Thread::current()->resource_area();
1659   VectorSet visited(arena);
1660 
1661   // 5. Find fields initializing values for not escaped allocations
1662   length = alloc_worklist.length();
1663   for (uint next = 0; next < length; ++next) {
1664     Node* n = alloc_worklist.at(next);
1665     if (ptnode_adr(n->_idx)->escape_state() == PointsToNode::NoEscape) {
1666       find_init_values(n, &visited, igvn);
1667     }
1668   }
1669 
1670   worklist.clear();
1671   worklist_init.clear();
1672   alloc_worklist.clear();
1673 
1674   // 6. Remove deferred edges from the graph.
1675   cg_length = cg_worklist.length();
1676   for (uint next = 0; next < cg_length; ++next) {
1677     int ni = cg_worklist.at(next);
1678     PointsToNode* ptn = ptnode_adr(ni);
1679     PointsToNode::NodeType nt = ptn->node_type();
1680     if (nt == PointsToNode::LocalVar || nt == PointsToNode::Field) {
1681       remove_deferred(ni, &worklist, &visited);
1682       Node *n = ptn->_node;
1683       if (n->is_AddP()) {
1684         alloc_worklist.append(n);
1685       }
1686     }
1687   }
1688 
1689   // 7. Adjust escape state of nonescaping objects.
1690   length = alloc_worklist.length();
1691   for (uint next = 0; next < length; ++next) {
1692     Node* n = alloc_worklist.at(next);
1693     adjust_escape_state(n);
1694   }
1695 
1696   // 8. Propagate escape states.
1697   worklist.clear();
1698   bool has_non_escaping_obj = false;
1699 
1700   // mark all nodes reachable from GlobalEscape nodes
1701   (void)propagate_escape_state(&cg_worklist, &worklist, PointsToNode::GlobalEscape);
1702 
1703   // mark all nodes reachable from ArgEscape nodes
1704   has_non_escaping_obj = propagate_escape_state(&cg_worklist, &worklist, PointsToNode::ArgEscape);
1705 
1706   // mark all nodes reachable from ControlEscape nodes
1707   has_non_escaping_obj = propagate_escape_state(&cg_worklist, &worklist, PointsToNode::ControlEscape);
1708 
1709   alloc_worklist.clear();
1710 
1711   // push all NoEscape nodes on the worklist
1712   for( uint next = 0; next < cg_length; ++next ) {
1713     int nk = cg_worklist.at(next);
1714     if (ptnode_adr(nk)->escape_state() == PointsToNode::NoEscape)
1715       worklist.push(nk);
1716   }
1717   // mark all nodes reachable from NoEscape nodes
1718   while(worklist.length() > 0) {
1719     uint nk = worklist.pop();
1720     PointsToNode* ptn = ptnode_adr(nk);
1721     if (ptn->node_type() == PointsToNode::JavaObject &&
1722         !(nk == _noop_null || nk == _oop_null))
1723       has_non_escaping_obj = true; // Non Escape
1724     Node* n = ptn->_node;
1725     if (n->is_Allocate()) {
1726       // Push scalar replaceable allocations on alloc_worklist
1727       // for processing in split_unique_types().
1728       alloc_worklist.append(n);
1729     }
1730     uint e_cnt = ptn->edge_count();
1731     for (uint ei = 0; ei < e_cnt; ei++) {
1732       uint npi = ptn->edge_target(ei);
1733       PointsToNode *np = ptnode_adr(npi);
1734       if (np->escape_state() < PointsToNode::NoEscape) {
1735         set_escape_state(npi, PointsToNode::NoEscape);
1736         worklist.push(npi);
1737       }
1738     }
1739   }
1740 
1741   _collecting = false;
1742   assert(C->unique() == nodes_size(), "there should be no new ideal nodes during ConnectionGraph build");
1743 
1744   assert(ptnode_adr(_oop_null)->escape_state() == PointsToNode::NoEscape, "sanity");
1745   if (UseCompressedOops) {
1746     assert(ptnode_adr(_noop_null)->escape_state() == PointsToNode::NoEscape, "sanity");
1747   }
1748 
1749   if (EliminateLocks && has_non_escaping_obj) {
1750     // Mark locks before changing ideal graph.
1751     int cnt = C->macro_count();
1752     for( int i=0; i < cnt; i++ ) {
1753       Node *n = C->macro_node(i);
1754       if (n->is_AbstractLock()) { // Lock and Unlock nodes
1755         AbstractLockNode* alock = n->as_AbstractLock();
1756         if (!alock->is_eliminated()) {
1757           PointsToNode::EscapeState es = escape_state(alock->obj_node());
1758           assert(es != PointsToNode::UnknownEscape, "should know");
1759           if (es != PointsToNode::UnknownEscape && es != PointsToNode::GlobalEscape) {
1760             // Mark it eliminated
1761             alock->set_eliminated();
1762           }
1763         }
1764       }
1765     }
1766   }
1767 
1768 #ifndef PRODUCT
1769   if (PrintEscapeAnalysis) {
1770     dump(); // Dump ConnectionGraph
1771   }
1772 #endif
1773 
1774   bool has_scalar_replaceable_candidates = alloc_worklist.length() > 0;
1775   if ( has_scalar_replaceable_candidates &&
1776        C->AliasLevel() >= 3 && EliminateAllocations ) {
1777 
1778     // Now use the escape information to create unique types for
1779     // scalar replaceable objects.
1780     split_unique_types(alloc_worklist);
1781 
1782     if (C->failing())  return false;
1783 
1784     C->print_method("After Escape Analysis", 2);
1785 
1786 #ifdef ASSERT
1787   } else if (Verbose && (PrintEscapeAnalysis || PrintEliminateAllocations)) {
1788     tty->print("=== No allocations eliminated for ");
1789     C->method()->print_short_name();
1790     if(!EliminateAllocations) {
1791       tty->print(" since EliminateAllocations is off ===");
1792     } else if(!has_scalar_replaceable_candidates) {
1793       tty->print(" since there are no scalar replaceable candidates ===");
1794     } else if(C->AliasLevel() < 3) {
1795       tty->print(" since AliasLevel < 3 ===");
1796     }
1797     tty->cr();
1798 #endif
1799   }
1800   return has_non_escaping_obj;
1801 }
1802 
1803 // Find fields initializing values for allocations.
1804 void ConnectionGraph::find_init_values(Node* alloc, VectorSet* visited, PhaseTransform* phase) {
1805   assert(alloc->is_Allocate(), "Should be called for Allocate nodes only");
1806   PointsToNode* pta = ptnode_adr(alloc->_idx);
1807   assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
1808   InitializeNode* ini = alloc->as_Allocate()->initialization();
1809 
1810   Compile* C = _compile;
1811   visited->Reset();
1812   // Check if a oop field's initializing value is recorded and add
1813   // a corresponding NULL field's value if it is not recorded.
1814   // Connection Graph does not record a default initialization by NULL
1815   // captured by Initialize node.
1816   //
1817   uint ae_cnt = pta->edge_count();
1818   for (uint ei = 0; ei < ae_cnt; ei++) {
1819     uint nidx = pta->edge_target(ei); // Field (AddP)
1820     PointsToNode* ptn = ptnode_adr(nidx);
1821     assert(ptn->_node->is_AddP(), "Should be AddP nodes only");
1822     int offset = ptn->offset();
1823     if (offset != Type::OffsetBot &&
1824         offset != oopDesc::klass_offset_in_bytes() &&
1825         !visited->test_set(offset)) {
1826 
1827       // Check only oop fields.
1828       const Type* adr_type = ptn->_node->as_AddP()->bottom_type();
1829       BasicType basic_field_type = T_INT;
1830       if (adr_type->isa_instptr()) {
1831         ciField* field = C->alias_type(adr_type->isa_instptr())->field();
1832         if (field != NULL) {
1833           basic_field_type = field->layout_type();
1834         } else {
1835           // Ignore non field load (for example, klass load)
1836         }
1837       } else if (adr_type->isa_aryptr()) {
1838         if (offset != arrayOopDesc::length_offset_in_bytes()) {
1839           const Type* elemtype = adr_type->isa_aryptr()->elem();
1840           basic_field_type = elemtype->array_element_basic_type();
1841         } else {
1842           // Ignore array length load
1843         }
1844 #ifdef ASSERT
1845       } else {
1846         // Raw pointers are used for initializing stores so skip it
1847         // since it should be recorded already
1848         Node* base = get_addp_base(ptn->_node);
1849         assert(adr_type->isa_rawptr() && base->is_Proj() &&
1850                (base->in(0) == alloc),"unexpected pointer type");
1851 #endif
1852       }
1853       if (basic_field_type == T_OBJECT ||
1854           basic_field_type == T_NARROWOOP ||
1855           basic_field_type == T_ARRAY) {
1856         Node* value = NULL;
1857         if (ini != NULL) {
1858           BasicType ft = UseCompressedOops ? T_NARROWOOP : T_OBJECT;
1859           Node* store = ini->find_captured_store(offset, type2aelembytes(ft), phase);
1860           if (store != NULL && store->is_Store()) {
1861             value = store->in(MemNode::ValueIn);
1862           } else if (ptn->edge_count() > 0) { // Are there oop stores?
1863             // Check for a store which follows allocation without branches.
1864             // For example, a volatile field store is not collected
1865             // by Initialize node. TODO: it would be nice to use idom() here.
1866             //
1867             // Search all references to the same field which use different
1868             // AddP nodes, for example, in the next case:
1869             //
1870             //    Point p[] = new Point[1];
1871             //    if ( x ) { p[0] = new Point(); p[0].x = x; }
1872             //    if ( p[0] != null ) { y = p[0].x; } // has CastPP
1873             //
1874             for (uint next = ei; (next < ae_cnt) && (value == NULL); next++) {
1875               uint fpi = pta->edge_target(next); // Field (AddP)
1876               PointsToNode *ptf = ptnode_adr(fpi);
1877               if (ptf->offset() == offset) {
1878                 Node* nf = ptf->_node;
1879                 for (DUIterator_Fast imax, i = nf->fast_outs(imax); i < imax; i++) {
1880                   store = nf->fast_out(i);
1881                   if (store->is_Store() && store->in(0) != NULL) {
1882                     Node* ctrl = store->in(0);
1883                     while(!(ctrl == ini || ctrl == alloc || ctrl == NULL ||
1884                             ctrl == C->root() || ctrl == C->top() || ctrl->is_Region() ||
1885                             ctrl->is_IfTrue() || ctrl->is_IfFalse())) {
1886                        ctrl = ctrl->in(0);
1887                     }
1888                     if (ctrl == ini || ctrl == alloc) {
1889                       value = store->in(MemNode::ValueIn);
1890                       break;
1891                     }
1892                   }
1893                 }
1894               }
1895             }
1896           }
1897         }
1898         if (value == NULL || value != ptnode_adr(value->_idx)->_node) {
1899           // A field's initializing value was not recorded. Add NULL.
1900           uint null_idx = UseCompressedOops ? _noop_null : _oop_null;
1901           add_edge_from_fields(alloc->_idx, null_idx, offset);
1902         }
1903       }
1904     }
1905   }
1906 }
1907 
1908 // Adjust escape state after Connection Graph is built.
1909 void ConnectionGraph::adjust_escape_state(Node* n) {
1910   PointsToNode* ptn = ptnode_adr(n->_idx);
1911   assert(n->is_AddP(), "Should be called for AddP nodes only");
1912   // Search for objects which are not scalar replaceable.
1913   // Mark their escape state as ControlEscape to propagate the state
1914   // to referenced objects.
1915 
1916   int offset = ptn->offset();
1917   Node* base = get_addp_base(n);
1918   VectorSet* ptset = PointsTo(base);
1919   int ptset_size = ptset->Size();
1920 
1921   // An object is not scalar replaceable if the field which may point
1922   // to it has unknown offset (unknown element of an array of objects).
1923   //
1924 
1925   if (offset == Type::OffsetBot) {
1926     uint e_cnt = ptn->edge_count();
1927     for (uint ei = 0; ei < e_cnt; ei++) {
1928       uint npi = ptn->edge_target(ei);
1929       set_escape_state(npi, PointsToNode::ControlEscape);
1930     }
1931   }
1932 
1933   // Currently an object is not scalar replaceable if a LoadStore node
1934   // access its field since the field value is unknown after it.
1935   //
1936   bool has_LoadStore = false;
1937   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1938     Node *use = n->fast_out(i);
1939     if (use->is_LoadStore()) {
1940       has_LoadStore = true;
1941       break;
1942     }
1943   }
1944   // An object is not scalar replaceable if the address points
1945   // to unknown field (unknown element for arrays, offset is OffsetBot).
1946   //
1947   // Or the address may point to more then one object. This may produce
1948   // the false positive result (set escape to ControlEscape)
1949   // since the flow-insensitive escape analysis can't separate
1950   // the case when stores overwrite the field's value from the case
1951   // when stores happened on different control branches.
1952   //
1953   // Note: it will disable scalar replacement in some cases:
1954   //
1955   //    Point p[] = new Point[1];
1956   //    p[0] = new Point(); // Will be not scalar replaced
1957   //
1958   // but it will save us from incorrect optimizations in next cases:
1959   //
1960   //    Point p[] = new Point[1];
1961   //    if ( x ) p[0] = new Point(); // Will be not scalar replaced
1962   //
1963   if (ptset_size > 1 || ptset_size != 0 &&
1964       (has_LoadStore || offset == Type::OffsetBot)) {
1965     for( VectorSetI j(ptset); j.test(); ++j ) {
1966       set_escape_state(j.elem, PointsToNode::ControlEscape);
1967     }
1968   }
1969 }
1970 
1971 // Propagate escape states to referenced nodes.
1972 bool ConnectionGraph::propagate_escape_state(GrowableArray<int>* cg_worklist,
1973                                              GrowableArray<uint>* worklist,
1974                                              PointsToNode::EscapeState esc_state) {
1975   bool has_java_obj = false;
1976 
1977   // push all nodes with the same escape state on the worklist
1978   uint cg_length = cg_worklist->length();
1979   for (uint next = 0; next < cg_length; ++next) {
1980     int nk = cg_worklist->at(next);
1981     if (ptnode_adr(nk)->escape_state() == esc_state)
1982       worklist->push(nk);
1983   }
1984   // mark all reachable nodes
1985   while (worklist->length() > 0) {
1986     PointsToNode* ptn = ptnode_adr(worklist->pop());
1987     if (ptn->node_type() == PointsToNode::JavaObject) {
1988       has_java_obj = true;
1989     }
1990     uint e_cnt = ptn->edge_count();
1991     for (uint ei = 0; ei < e_cnt; ei++) {
1992       uint npi = ptn->edge_target(ei);
1993       PointsToNode *np = ptnode_adr(npi);
1994       if (np->escape_state() < esc_state) {
1995         set_escape_state(npi, esc_state);
1996         worklist->push(npi);
1997       }
1998     }
1999   }
2000   // Has not escaping java objects
2001   return has_java_obj && (esc_state < PointsToNode::GlobalEscape);
2002 }
2003 
2004 void ConnectionGraph::process_call_arguments(CallNode *call, PhaseTransform *phase) {
2005 
2006     switch (call->Opcode()) {
2007 #ifdef ASSERT
2008     case Op_Allocate:
2009     case Op_AllocateArray:
2010     case Op_Lock:
2011     case Op_Unlock:
2012       assert(false, "should be done already");
2013       break;
2014 #endif
2015     case Op_CallLeaf:
2016     case Op_CallLeafNoFP:
2017     {
2018       // Stub calls, objects do not escape but they are not scale replaceable.
2019       // Adjust escape state for outgoing arguments.
2020       const TypeTuple * d = call->tf()->domain();
2021       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2022         const Type* at = d->field_at(i);
2023         Node *arg = call->in(i)->uncast();
2024         const Type *aat = phase->type(arg);
2025         if (!arg->is_top() && at->isa_ptr() && aat->isa_ptr() &&
2026             ptnode_adr(arg->_idx)->escape_state() < PointsToNode::ArgEscape) {
2027 
2028           assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
2029                  aat->isa_ptr() != NULL, "expecting an Ptr");
2030 #ifdef ASSERT
2031           if (!(call->Opcode() == Op_CallLeafNoFP &&
2032                 call->as_CallLeaf()->_name != NULL &&
2033                 (strstr(call->as_CallLeaf()->_name, "arraycopy")  != 0) ||
2034                 call->as_CallLeaf()->_name != NULL &&
2035                 (strcmp(call->as_CallLeaf()->_name, "g1_wb_pre")  == 0 ||
2036                  strcmp(call->as_CallLeaf()->_name, "g1_wb_post") == 0 ))
2037           ) {
2038             call->dump();
2039             assert(false, "EA: unexpected CallLeaf");
2040           }
2041 #endif
2042           set_escape_state(arg->_idx, PointsToNode::ArgEscape);
2043           if (arg->is_AddP()) {
2044             //
2045             // The inline_native_clone() case when the arraycopy stub is called
2046             // after the allocation before Initialize and CheckCastPP nodes.
2047             //
2048             // Set AddP's base (Allocate) as not scalar replaceable since
2049             // pointer to the base (with offset) is passed as argument.
2050             //
2051             arg = get_addp_base(arg);
2052           }
2053           for( VectorSetI j(PointsTo(arg)); j.test(); ++j ) {
2054             uint pt = j.elem;
2055             set_escape_state(pt, PointsToNode::ArgEscape);
2056           }
2057         }
2058       }
2059       break;
2060     }
2061 
2062     case Op_CallStaticJava:
2063     // For a static call, we know exactly what method is being called.
2064     // Use bytecode estimator to record the call's escape affects
2065     {
2066       ciMethod *meth = call->as_CallJava()->method();
2067       BCEscapeAnalyzer *call_analyzer = (meth !=NULL) ? meth->get_bcea() : NULL;
2068       // fall-through if not a Java method or no analyzer information
2069       if (call_analyzer != NULL) {
2070         const TypeTuple * d = call->tf()->domain();
2071         bool copy_dependencies = false;
2072         for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2073           const Type* at = d->field_at(i);
2074           int k = i - TypeFunc::Parms;
2075           Node *arg = call->in(i)->uncast();
2076 
2077           if (at->isa_oopptr() != NULL &&
2078               ptnode_adr(arg->_idx)->escape_state() < PointsToNode::GlobalEscape) {
2079 
2080             bool global_escapes = false;
2081             bool fields_escapes = false;
2082             if (!call_analyzer->is_arg_stack(k)) {
2083               // The argument global escapes, mark everything it could point to
2084               set_escape_state(arg->_idx, PointsToNode::GlobalEscape);
2085               global_escapes = true;
2086             } else {
2087               if (!call_analyzer->is_arg_local(k)) {
2088                 // The argument itself doesn't escape, but any fields might
2089                 fields_escapes = true;
2090               }
2091               set_escape_state(arg->_idx, PointsToNode::ArgEscape);
2092               copy_dependencies = true;
2093             }
2094 
2095             for( VectorSetI j(PointsTo(arg)); j.test(); ++j ) {
2096               uint pt = j.elem;
2097               if (global_escapes) {
2098                 //The argument global escapes, mark everything it could point to
2099                 set_escape_state(pt, PointsToNode::GlobalEscape);
2100               } else {
2101                 if (fields_escapes) {
2102                   // The argument itself doesn't escape, but any fields might
2103                   add_edge_from_fields(pt, _phantom_object, Type::OffsetBot);
2104                 }
2105                 set_escape_state(pt, PointsToNode::ArgEscape);
2106               }
2107             }
2108           }
2109         }
2110         if (copy_dependencies)
2111           call_analyzer->copy_dependencies(_compile->dependencies());
2112         break;
2113       }
2114     }
2115 
2116     default:
2117     // Fall-through here if not a Java method or no analyzer information
2118     // or some other type of call, assume the worst case: all arguments
2119     // globally escape.
2120     {
2121       // adjust escape state for  outgoing arguments
2122       const TypeTuple * d = call->tf()->domain();
2123       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2124         const Type* at = d->field_at(i);
2125         if (at->isa_oopptr() != NULL) {
2126           Node *arg = call->in(i)->uncast();
2127           set_escape_state(arg->_idx, PointsToNode::GlobalEscape);
2128           for( VectorSetI j(PointsTo(arg)); j.test(); ++j ) {
2129             uint pt = j.elem;
2130             set_escape_state(pt, PointsToNode::GlobalEscape);
2131           }
2132         }
2133       }
2134     }
2135   }
2136 }
2137 void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *phase) {
2138   CallNode   *call = resproj->in(0)->as_Call();
2139   uint    call_idx = call->_idx;
2140   uint resproj_idx = resproj->_idx;
2141 
2142   switch (call->Opcode()) {
2143     case Op_Allocate:
2144     {
2145       Node *k = call->in(AllocateNode::KlassNode);
2146       const TypeKlassPtr *kt = k->bottom_type()->isa_klassptr();
2147       assert(kt != NULL, "TypeKlassPtr  required.");
2148       ciKlass* cik = kt->klass();
2149 
2150       PointsToNode::EscapeState es;
2151       uint edge_to;
2152       if (cik->is_subclass_of(_compile->env()->Thread_klass()) ||
2153          !cik->is_instance_klass() || // StressReflectiveCode
2154           cik->as_instance_klass()->has_finalizer()) {
2155         es = PointsToNode::GlobalEscape;
2156         edge_to = _phantom_object; // Could not be worse
2157       } else {
2158         es = PointsToNode::NoEscape;
2159         edge_to = call_idx;
2160       }
2161       set_escape_state(call_idx, es);
2162       add_pointsto_edge(resproj_idx, edge_to);
2163       _processed.set(resproj_idx);
2164       break;
2165     }
2166 
2167     case Op_AllocateArray:
2168     {
2169 
2170       Node *k = call->in(AllocateNode::KlassNode);
2171       const TypeKlassPtr *kt = k->bottom_type()->isa_klassptr();
2172       assert(kt != NULL, "TypeKlassPtr  required.");
2173       ciKlass* cik = kt->klass();
2174 
2175       PointsToNode::EscapeState es;
2176       uint edge_to;
2177       if (!cik->is_array_klass()) { // StressReflectiveCode
2178         es = PointsToNode::GlobalEscape;
2179         edge_to = _phantom_object;
2180       } else {
2181         es = PointsToNode::NoEscape;
2182         edge_to = call_idx;
2183         int length = call->in(AllocateNode::ALength)->find_int_con(-1);
2184         if (length < 0 || length > EliminateAllocationArraySizeLimit) {
2185           // Not scalar replaceable if the length is not constant or too big.
2186           es = PointsToNode::ControlEscape;
2187         }
2188       }
2189       set_escape_state(call_idx, es);
2190       add_pointsto_edge(resproj_idx, edge_to);
2191       _processed.set(resproj_idx);
2192       break;
2193     }
2194 
2195     case Op_CallStaticJava:
2196     // For a static call, we know exactly what method is being called.
2197     // Use bytecode estimator to record whether the call's return value escapes
2198     {
2199       bool done = true;
2200       const TypeTuple *r = call->tf()->range();
2201       const Type* ret_type = NULL;
2202 
2203       if (r->cnt() > TypeFunc::Parms)
2204         ret_type = r->field_at(TypeFunc::Parms);
2205 
2206       // Note:  we use isa_ptr() instead of isa_oopptr()  here because the
2207       //        _multianewarray functions return a TypeRawPtr.
2208       if (ret_type == NULL || ret_type->isa_ptr() == NULL) {
2209         _processed.set(resproj_idx);
2210         break;  // doesn't return a pointer type
2211       }
2212       ciMethod *meth = call->as_CallJava()->method();
2213       const TypeTuple * d = call->tf()->domain();
2214       if (meth == NULL) {
2215         // not a Java method, assume global escape
2216         set_escape_state(call_idx, PointsToNode::GlobalEscape);
2217         add_pointsto_edge(resproj_idx, _phantom_object);
2218       } else {
2219         BCEscapeAnalyzer *call_analyzer = meth->get_bcea();
2220         bool copy_dependencies = false;
2221 
2222         if (call_analyzer->is_return_allocated()) {
2223           // Returns a newly allocated unescaped object, simply
2224           // update dependency information.
2225           // Mark it as ControlEscape so that objects referenced by
2226           // it's fields will be marked as ControlEscape at least.
2227           set_escape_state(call_idx, PointsToNode::ControlEscape);
2228           add_pointsto_edge(resproj_idx, call_idx);
2229           copy_dependencies = true;
2230         } else if (call_analyzer->is_return_local()) {
2231           // determine whether any arguments are returned
2232           set_escape_state(call_idx, PointsToNode::ArgEscape);
2233           bool ret_arg = false;
2234           for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2235             const Type* at = d->field_at(i);
2236 
2237             if (at->isa_oopptr() != NULL) {
2238               Node *arg = call->in(i)->uncast();
2239 
2240               if (call_analyzer->is_arg_returned(i - TypeFunc::Parms)) {
2241                 ret_arg = true;
2242                 PointsToNode *arg_esp = ptnode_adr(arg->_idx);
2243                 if (arg_esp->node_type() == PointsToNode::UnknownType)
2244                   done = false;
2245                 else if (arg_esp->node_type() == PointsToNode::JavaObject)
2246                   add_pointsto_edge(resproj_idx, arg->_idx);
2247                 else
2248                   add_deferred_edge(resproj_idx, arg->_idx);
2249               }
2250             }
2251           }
2252           if (done && !ret_arg) {
2253             // Returns unknown object.
2254             set_escape_state(call_idx, PointsToNode::GlobalEscape);
2255             add_pointsto_edge(resproj_idx, _phantom_object);
2256           }
2257           if (done) {
2258             copy_dependencies = true;
2259           }
2260         } else {
2261           set_escape_state(call_idx, PointsToNode::GlobalEscape);
2262           add_pointsto_edge(resproj_idx, _phantom_object);
2263         }
2264         if (copy_dependencies)
2265           call_analyzer->copy_dependencies(_compile->dependencies());
2266       }
2267       if (done)
2268         _processed.set(resproj_idx);
2269       break;
2270     }
2271 
2272     default:
2273     // Some other type of call, assume the worst case that the
2274     // returned value, if any, globally escapes.
2275     {
2276       const TypeTuple *r = call->tf()->range();
2277       if (r->cnt() > TypeFunc::Parms) {
2278         const Type* ret_type = r->field_at(TypeFunc::Parms);
2279 
2280         // Note:  we use isa_ptr() instead of isa_oopptr()  here because the
2281         //        _multianewarray functions return a TypeRawPtr.
2282         if (ret_type->isa_ptr() != NULL) {
2283           set_escape_state(call_idx, PointsToNode::GlobalEscape);
2284           add_pointsto_edge(resproj_idx, _phantom_object);
2285         }
2286       }
2287       _processed.set(resproj_idx);
2288     }
2289   }
2290 }
2291 
2292 // Populate Connection Graph with Ideal nodes and create simple
2293 // connection graph edges (do not need to check the node_type of inputs
2294 // or to call PointsTo() to walk the connection graph).
2295 void ConnectionGraph::record_for_escape_analysis(Node *n, PhaseTransform *phase) {
2296   if (_processed.test(n->_idx))
2297     return; // No need to redefine node's state.
2298 
2299   if (n->is_Call()) {
2300     // Arguments to allocation and locking don't escape.
2301     if (n->is_Allocate()) {
2302       add_node(n, PointsToNode::JavaObject, PointsToNode::UnknownEscape, true);
2303       record_for_optimizer(n);
2304     } else if (n->is_Lock() || n->is_Unlock()) {
2305       // Put Lock and Unlock nodes on IGVN worklist to process them during
2306       // the first IGVN optimization when escape information is still available.
2307       record_for_optimizer(n);
2308       _processed.set(n->_idx);
2309     } else {
2310       // Don't mark as processed since call's arguments have to be processed.
2311       PointsToNode::NodeType nt = PointsToNode::UnknownType;
2312       PointsToNode::EscapeState es = PointsToNode::UnknownEscape;
2313 
2314       // Check if a call returns an object.
2315       const TypeTuple *r = n->as_Call()->tf()->range();
2316       if (r->cnt() > TypeFunc::Parms &&
2317           r->field_at(TypeFunc::Parms)->isa_ptr() &&
2318           n->as_Call()->proj_out(TypeFunc::Parms) != NULL) {
2319         nt = PointsToNode::JavaObject;
2320         if (!n->is_CallStaticJava()) {
2321           // Since the called mathod is statically unknown assume
2322           // the worst case that the returned value globally escapes.
2323           es = PointsToNode::GlobalEscape;
2324         }
2325       }
2326       add_node(n, nt, es, false);
2327     }
2328     return;
2329   }
2330 
2331   // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
2332   // ThreadLocal has RawPrt type.
2333   switch (n->Opcode()) {
2334     case Op_AddP:
2335     {
2336       add_node(n, PointsToNode::Field, PointsToNode::UnknownEscape, false);
2337       break;
2338     }
2339     case Op_CastX2P:
2340     { // "Unsafe" memory access.
2341       add_node(n, PointsToNode::JavaObject, PointsToNode::GlobalEscape, true);
2342       break;
2343     }
2344     case Op_CastPP:
2345     case Op_CheckCastPP:
2346     case Op_EncodeP:
2347     case Op_DecodeN:
2348     {
2349       add_node(n, PointsToNode::LocalVar, PointsToNode::UnknownEscape, false);
2350       int ti = n->in(1)->_idx;
2351       PointsToNode::NodeType nt = ptnode_adr(ti)->node_type();
2352       if (nt == PointsToNode::UnknownType) {
2353         _delayed_worklist.push(n); // Process it later.
2354         break;
2355       } else if (nt == PointsToNode::JavaObject) {
2356         add_pointsto_edge(n->_idx, ti);
2357       } else {
2358         add_deferred_edge(n->_idx, ti);
2359       }
2360       _processed.set(n->_idx);
2361       break;
2362     }
2363     case Op_ConP:
2364     {
2365       // assume all pointer constants globally escape except for null
2366       PointsToNode::EscapeState es;
2367       if (phase->type(n) == TypePtr::NULL_PTR)
2368         es = PointsToNode::NoEscape;
2369       else
2370         es = PointsToNode::GlobalEscape;
2371 
2372       add_node(n, PointsToNode::JavaObject, es, true);
2373       break;
2374     }
2375     case Op_ConN:
2376     {
2377       // assume all narrow oop constants globally escape except for null
2378       PointsToNode::EscapeState es;
2379       if (phase->type(n) == TypeNarrowOop::NULL_PTR)
2380         es = PointsToNode::NoEscape;
2381       else
2382         es = PointsToNode::GlobalEscape;
2383 
2384       add_node(n, PointsToNode::JavaObject, es, true);
2385       break;
2386     }
2387     case Op_CreateEx:
2388     {
2389       // assume that all exception objects globally escape
2390       add_node(n, PointsToNode::JavaObject, PointsToNode::GlobalEscape, true);
2391       break;
2392     }
2393     case Op_LoadKlass:
2394     case Op_LoadNKlass:
2395     {
2396       add_node(n, PointsToNode::JavaObject, PointsToNode::GlobalEscape, true);
2397       break;
2398     }
2399     case Op_LoadP:
2400     case Op_LoadN:
2401     {
2402       const Type *t = phase->type(n);
2403       if (t->make_ptr() == NULL) {
2404         _processed.set(n->_idx);
2405         return;
2406       }
2407       add_node(n, PointsToNode::LocalVar, PointsToNode::UnknownEscape, false);
2408       break;
2409     }
2410     case Op_Parm:
2411     {
2412       _processed.set(n->_idx); // No need to redefine it state.
2413       uint con = n->as_Proj()->_con;
2414       if (con < TypeFunc::Parms)
2415         return;
2416       const Type *t = n->in(0)->as_Start()->_domain->field_at(con);
2417       if (t->isa_ptr() == NULL)
2418         return;
2419       // We have to assume all input parameters globally escape
2420       // (Note: passing 'false' since _processed is already set).
2421       add_node(n, PointsToNode::JavaObject, PointsToNode::GlobalEscape, false);
2422       break;
2423     }
2424     case Op_Phi:
2425     {
2426       const Type *t = n->as_Phi()->type();
2427       if (t->make_ptr() == NULL) {
2428         // nothing to do if not an oop or narrow oop
2429         _processed.set(n->_idx);
2430         return;
2431       }
2432       add_node(n, PointsToNode::LocalVar, PointsToNode::UnknownEscape, false);
2433       uint i;
2434       for (i = 1; i < n->req() ; i++) {
2435         Node* in = n->in(i);
2436         if (in == NULL)
2437           continue;  // ignore NULL
2438         in = in->uncast();
2439         if (in->is_top() || in == n)
2440           continue;  // ignore top or inputs which go back this node
2441         int ti = in->_idx;
2442         PointsToNode::NodeType nt = ptnode_adr(ti)->node_type();
2443         if (nt == PointsToNode::UnknownType) {
2444           break;
2445         } else if (nt == PointsToNode::JavaObject) {
2446           add_pointsto_edge(n->_idx, ti);
2447         } else {
2448           add_deferred_edge(n->_idx, ti);
2449         }
2450       }
2451       if (i >= n->req())
2452         _processed.set(n->_idx);
2453       else
2454         _delayed_worklist.push(n);
2455       break;
2456     }
2457     case Op_Proj:
2458     {
2459       // we are only interested in the oop result projection from a call
2460       if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() ) {
2461         const TypeTuple *r = n->in(0)->as_Call()->tf()->range();
2462         assert(r->cnt() > TypeFunc::Parms, "sanity");
2463         if (r->field_at(TypeFunc::Parms)->isa_ptr() != NULL) {
2464           add_node(n, PointsToNode::LocalVar, PointsToNode::UnknownEscape, false);
2465           int ti = n->in(0)->_idx;
2466           // The call may not be registered yet (since not all its inputs are registered)
2467           // if this is the projection from backbranch edge of Phi.
2468           if (ptnode_adr(ti)->node_type() != PointsToNode::UnknownType) {
2469             process_call_result(n->as_Proj(), phase);
2470           }
2471           if (!_processed.test(n->_idx)) {
2472             // The call's result may need to be processed later if the call
2473             // returns it's argument and the argument is not processed yet.
2474             _delayed_worklist.push(n);
2475           }
2476           break;
2477         }
2478       }
2479       _processed.set(n->_idx);
2480       break;
2481     }
2482     case Op_Return:
2483     {
2484       if( n->req() > TypeFunc::Parms &&
2485           phase->type(n->in(TypeFunc::Parms))->isa_oopptr() ) {
2486         // Treat Return value as LocalVar with GlobalEscape escape state.
2487         add_node(n, PointsToNode::LocalVar, PointsToNode::GlobalEscape, false);
2488         int ti = n->in(TypeFunc::Parms)->_idx;
2489         PointsToNode::NodeType nt = ptnode_adr(ti)->node_type();
2490         if (nt == PointsToNode::UnknownType) {
2491           _delayed_worklist.push(n); // Process it later.
2492           break;
2493         } else if (nt == PointsToNode::JavaObject) {
2494           add_pointsto_edge(n->_idx, ti);
2495         } else {
2496           add_deferred_edge(n->_idx, ti);
2497         }
2498       }
2499       _processed.set(n->_idx);
2500       break;
2501     }
2502     case Op_StoreP:
2503     case Op_StoreN:
2504     {
2505       const Type *adr_type = phase->type(n->in(MemNode::Address));
2506       adr_type = adr_type->make_ptr();
2507       if (adr_type->isa_oopptr()) {
2508         add_node(n, PointsToNode::UnknownType, PointsToNode::UnknownEscape, false);
2509       } else {
2510         Node* adr = n->in(MemNode::Address);
2511         if (adr->is_AddP() && phase->type(adr) == TypeRawPtr::NOTNULL &&
2512             adr->in(AddPNode::Address)->is_Proj() &&
2513             adr->in(AddPNode::Address)->in(0)->is_Allocate()) {
2514           add_node(n, PointsToNode::UnknownType, PointsToNode::UnknownEscape, false);
2515           // We are computing a raw address for a store captured
2516           // by an Initialize compute an appropriate address type.
2517           int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
2518           assert(offs != Type::OffsetBot, "offset must be a constant");
2519         } else {
2520           _processed.set(n->_idx);
2521           return;
2522         }
2523       }
2524       break;
2525     }
2526     case Op_StorePConditional:
2527     case Op_CompareAndSwapP:
2528     case Op_CompareAndSwapN:
2529     {
2530       const Type *adr_type = phase->type(n->in(MemNode::Address));
2531       adr_type = adr_type->make_ptr();
2532       if (adr_type->isa_oopptr()) {
2533         add_node(n, PointsToNode::UnknownType, PointsToNode::UnknownEscape, false);
2534       } else {
2535         _processed.set(n->_idx);
2536         return;
2537       }
2538       break;
2539     }
2540     case Op_AryEq:
2541     case Op_StrComp:
2542     case Op_StrEquals:
2543     case Op_StrIndexOf:
2544     {
2545       // char[] arrays passed to string intrinsics are not scalar replaceable.
2546       add_node(n, PointsToNode::UnknownType, PointsToNode::UnknownEscape, false);
2547       break;
2548     }
2549     case Op_ThreadLocal:
2550     {
2551       add_node(n, PointsToNode::JavaObject, PointsToNode::ArgEscape, true);
2552       break;
2553     }
2554     default:
2555       ;
2556       // nothing to do
2557   }
2558   return;
2559 }
2560 
2561 void ConnectionGraph::build_connection_graph(Node *n, PhaseTransform *phase) {
2562   uint n_idx = n->_idx;
2563   assert(ptnode_adr(n_idx)->_node != NULL, "node should be registered");
2564 
2565   // Don't set processed bit for AddP, LoadP, StoreP since
2566   // they may need more then one pass to process.
2567   // Also don't mark as processed Call nodes since their
2568   // arguments may need more then one pass to process.
2569   if (_processed.test(n_idx))
2570     return; // No need to redefine node's state.
2571 
2572   if (n->is_Call()) {
2573     CallNode *call = n->as_Call();
2574     process_call_arguments(call, phase);
2575     return;
2576   }
2577 
2578   switch (n->Opcode()) {
2579     case Op_AddP:
2580     {
2581       Node *base = get_addp_base(n);
2582       // Create a field edge to this node from everything base could point to.
2583       for( VectorSetI i(PointsTo(base)); i.test(); ++i ) {
2584         uint pt = i.elem;
2585         add_field_edge(pt, n_idx, address_offset(n, phase));
2586       }
2587       break;
2588     }
2589     case Op_CastX2P:
2590     {
2591       assert(false, "Op_CastX2P");
2592       break;
2593     }
2594     case Op_CastPP:
2595     case Op_CheckCastPP:
2596     case Op_EncodeP:
2597     case Op_DecodeN:
2598     {
2599       int ti = n->in(1)->_idx;
2600       assert(ptnode_adr(ti)->node_type() != PointsToNode::UnknownType, "all nodes should be registered");
2601       if (ptnode_adr(ti)->node_type() == PointsToNode::JavaObject) {
2602         add_pointsto_edge(n_idx, ti);
2603       } else {
2604         add_deferred_edge(n_idx, ti);
2605       }
2606       _processed.set(n_idx);
2607       break;
2608     }
2609     case Op_ConP:
2610     {
2611       assert(false, "Op_ConP");
2612       break;
2613     }
2614     case Op_ConN:
2615     {
2616       assert(false, "Op_ConN");
2617       break;
2618     }
2619     case Op_CreateEx:
2620     {
2621       assert(false, "Op_CreateEx");
2622       break;
2623     }
2624     case Op_LoadKlass:
2625     case Op_LoadNKlass:
2626     {
2627       assert(false, "Op_LoadKlass");
2628       break;
2629     }
2630     case Op_LoadP:
2631     case Op_LoadN:
2632     {
2633       const Type *t = phase->type(n);
2634 #ifdef ASSERT
2635       if (t->make_ptr() == NULL)
2636         assert(false, "Op_LoadP");
2637 #endif
2638 
2639       Node* adr = n->in(MemNode::Address)->uncast();
2640       Node* adr_base;
2641       if (adr->is_AddP()) {
2642         adr_base = get_addp_base(adr);
2643       } else {
2644         adr_base = adr;
2645       }
2646 
2647       // For everything "adr_base" could point to, create a deferred edge from
2648       // this node to each field with the same offset.
2649       int offset = address_offset(adr, phase);
2650       for( VectorSetI i(PointsTo(adr_base)); i.test(); ++i ) {
2651         uint pt = i.elem;
2652         add_deferred_edge_to_fields(n_idx, pt, offset);
2653       }
2654       break;
2655     }
2656     case Op_Parm:
2657     {
2658       assert(false, "Op_Parm");
2659       break;
2660     }
2661     case Op_Phi:
2662     {
2663 #ifdef ASSERT
2664       const Type *t = n->as_Phi()->type();
2665       if (t->make_ptr() == NULL)
2666         assert(false, "Op_Phi");
2667 #endif
2668       for (uint i = 1; i < n->req() ; i++) {
2669         Node* in = n->in(i);
2670         if (in == NULL)
2671           continue;  // ignore NULL
2672         in = in->uncast();
2673         if (in->is_top() || in == n)
2674           continue;  // ignore top or inputs which go back this node
2675         int ti = in->_idx;
2676         PointsToNode::NodeType nt = ptnode_adr(ti)->node_type();
2677         assert(nt != PointsToNode::UnknownType, "all nodes should be known");
2678         if (nt == PointsToNode::JavaObject) {
2679           add_pointsto_edge(n_idx, ti);
2680         } else {
2681           add_deferred_edge(n_idx, ti);
2682         }
2683       }
2684       _processed.set(n_idx);
2685       break;
2686     }
2687     case Op_Proj:
2688     {
2689       // we are only interested in the oop result projection from a call
2690       if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() ) {
2691         assert(ptnode_adr(n->in(0)->_idx)->node_type() != PointsToNode::UnknownType,
2692                "all nodes should be registered");
2693         const TypeTuple *r = n->in(0)->as_Call()->tf()->range();
2694         assert(r->cnt() > TypeFunc::Parms, "sanity");
2695         if (r->field_at(TypeFunc::Parms)->isa_ptr() != NULL) {
2696           process_call_result(n->as_Proj(), phase);
2697           assert(_processed.test(n_idx), "all call results should be processed");
2698           break;
2699         }
2700       }
2701       assert(false, "Op_Proj");
2702       break;
2703     }
2704     case Op_Return:
2705     {
2706 #ifdef ASSERT
2707       if( n->req() <= TypeFunc::Parms ||
2708           !phase->type(n->in(TypeFunc::Parms))->isa_oopptr() ) {
2709         assert(false, "Op_Return");
2710       }
2711 #endif
2712       int ti = n->in(TypeFunc::Parms)->_idx;
2713       assert(ptnode_adr(ti)->node_type() != PointsToNode::UnknownType, "node should be registered");
2714       if (ptnode_adr(ti)->node_type() == PointsToNode::JavaObject) {
2715         add_pointsto_edge(n_idx, ti);
2716       } else {
2717         add_deferred_edge(n_idx, ti);
2718       }
2719       _processed.set(n_idx);
2720       break;
2721     }
2722     case Op_StoreP:
2723     case Op_StoreN:
2724     case Op_StorePConditional:
2725     case Op_CompareAndSwapP:
2726     case Op_CompareAndSwapN:
2727     {
2728       Node *adr = n->in(MemNode::Address);
2729       const Type *adr_type = phase->type(adr)->make_ptr();
2730 #ifdef ASSERT
2731       if (!adr_type->isa_oopptr())
2732         assert(phase->type(adr) == TypeRawPtr::NOTNULL, "Op_StoreP");
2733 #endif
2734 
2735       assert(adr->is_AddP(), "expecting an AddP");
2736       Node *adr_base = get_addp_base(adr);
2737       Node *val = n->in(MemNode::ValueIn)->uncast();
2738       // For everything "adr_base" could point to, create a deferred edge
2739       // to "val" from each field with the same offset.
2740       for( VectorSetI i(PointsTo(adr_base)); i.test(); ++i ) {
2741         uint pt = i.elem;
2742         add_edge_from_fields(pt, val->_idx, address_offset(adr, phase));
2743       }
2744       break;
2745     }
2746     case Op_AryEq:
2747     case Op_StrComp:
2748     case Op_StrEquals:
2749     case Op_StrIndexOf:
2750     {
2751       // char[] arrays passed to string intrinsic do not escape but
2752       // they are not scalar replaceable. Adjust escape state for them.
2753       // Start from in(2) edge since in(1) is memory edge.
2754       for (uint i = 2; i < n->req(); i++) {
2755         Node* adr = n->in(i)->uncast();
2756         const Type *at = phase->type(adr);
2757         if (!adr->is_top() && at->isa_ptr()) {
2758           assert(at == Type::TOP || at == TypePtr::NULL_PTR ||
2759                  at->isa_ptr() != NULL, "expecting an Ptr");
2760           if (adr->is_AddP()) {
2761             adr = get_addp_base(adr);
2762           }
2763           // Mark as ArgEscape everything "adr" could point to.
2764           set_escape_state(adr->_idx, PointsToNode::ArgEscape);
2765         }
2766       }
2767       _processed.set(n_idx);
2768       break;
2769     }
2770     case Op_ThreadLocal:
2771     {
2772       assert(false, "Op_ThreadLocal");
2773       break;
2774     }
2775     default:
2776       // This method should be called only for EA specific nodes.
2777       ShouldNotReachHere();
2778   }
2779 }
2780 
2781 #ifndef PRODUCT
2782 void ConnectionGraph::dump() {
2783   bool first = true;
2784 
2785   uint size = nodes_size();
2786   for (uint ni = 0; ni < size; ni++) {
2787     PointsToNode *ptn = ptnode_adr(ni);
2788     PointsToNode::NodeType ptn_type = ptn->node_type();
2789 
2790     if (ptn_type != PointsToNode::JavaObject || ptn->_node == NULL)
2791       continue;
2792     PointsToNode::EscapeState es = escape_state(ptn->_node);
2793     if (ptn->_node->is_Allocate() && (es == PointsToNode::NoEscape || Verbose)) {
2794       if (first) {
2795         tty->cr();
2796         tty->print("======== Connection graph for ");
2797         _compile->method()->print_short_name();
2798         tty->cr();
2799         first = false;
2800       }
2801       tty->print("%6d ", ni);
2802       ptn->dump();
2803       // Print all locals which reference this allocation
2804       for (uint li = ni; li < size; li++) {
2805         PointsToNode *ptn_loc = ptnode_adr(li);
2806         PointsToNode::NodeType ptn_loc_type = ptn_loc->node_type();
2807         if ( ptn_loc_type == PointsToNode::LocalVar && ptn_loc->_node != NULL &&
2808              ptn_loc->edge_count() == 1 && ptn_loc->edge_target(0) == ni ) {
2809           ptnode_adr(li)->dump(false);
2810         }
2811       }
2812       if (Verbose) {
2813         // Print all fields which reference this allocation
2814         for (uint i = 0; i < ptn->edge_count(); i++) {
2815           uint ei = ptn->edge_target(i);
2816           ptnode_adr(ei)->dump(false);
2817         }
2818       }
2819       tty->cr();
2820     }
2821   }
2822 }
2823 #endif