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