1 /*
   2  * Copyright (c) 1997, 2015, 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 "compiler/compileLog.hpp"
  27 #include "ci/bcEscapeAnalyzer.hpp"
  28 #include "compiler/oopMap.hpp"
  29 #include "opto/callGenerator.hpp"
  30 #include "opto/callnode.hpp"
  31 #include "opto/castnode.hpp"
  32 #include "opto/convertnode.hpp"
  33 #include "opto/escape.hpp"
  34 #include "opto/locknode.hpp"
  35 #include "opto/machnode.hpp"
  36 #include "opto/matcher.hpp"
  37 #include "opto/parse.hpp"
  38 #include "opto/regalloc.hpp"
  39 #include "opto/regmask.hpp"
  40 #include "opto/rootnode.hpp"
  41 #include "opto/runtime.hpp"
  42 #include "opto/valuetypenode.hpp"
  43 #include "runtime/sharedRuntime.hpp"
  44 
  45 // Portions of code courtesy of Clifford Click
  46 
  47 // Optimization - Graph Style
  48 
  49 //=============================================================================
  50 uint StartNode::size_of() const { return sizeof(*this); }
  51 uint StartNode::cmp( const Node &n ) const
  52 { return _domain == ((StartNode&)n)._domain; }
  53 const Type *StartNode::bottom_type() const { return _domain; }
  54 const Type* StartNode::Value(PhaseGVN* phase) const { return _domain; }
  55 #ifndef PRODUCT
  56 void StartNode::dump_spec(outputStream *st) const { st->print(" #"); _domain->dump_on(st);}
  57 void StartNode::dump_compact_spec(outputStream *st) const { /* empty */ }
  58 #endif
  59 
  60 //------------------------------Ideal------------------------------------------
  61 Node *StartNode::Ideal(PhaseGVN *phase, bool can_reshape){
  62   return remove_dead_region(phase, can_reshape) ? this : NULL;
  63 }
  64 
  65 //------------------------------calling_convention-----------------------------
  66 void StartNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
  67   Matcher::calling_convention( sig_bt, parm_regs, argcnt, false );
  68 }
  69 
  70 //------------------------------Registers--------------------------------------
  71 const RegMask &StartNode::in_RegMask(uint) const {
  72   return RegMask::Empty;
  73 }
  74 
  75 //------------------------------match------------------------------------------
  76 // Construct projections for incoming parameters, and their RegMask info
  77 Node *StartNode::match(const ProjNode *proj, const Matcher *match, const RegMask* mask) {
  78   switch (proj->_con) {
  79   case TypeFunc::Control:
  80   case TypeFunc::I_O:
  81   case TypeFunc::Memory:
  82     return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
  83   case TypeFunc::FramePtr:
  84     return new MachProjNode(this,proj->_con,Matcher::c_frame_ptr_mask, Op_RegP);
  85   case TypeFunc::ReturnAdr:
  86     return new MachProjNode(this,proj->_con,match->_return_addr_mask,Op_RegP);
  87   case TypeFunc::Parms:
  88   default: {
  89       uint parm_num = proj->_con - TypeFunc::Parms;
  90       const Type *t = _domain->field_at(proj->_con);
  91       if (t->base() == Type::Half)  // 2nd half of Longs and Doubles
  92         return new ConNode(Type::TOP);
  93       uint ideal_reg = t->ideal_reg();
  94       RegMask &rm = match->_calling_convention_mask[parm_num];
  95       return new MachProjNode(this,proj->_con,rm,ideal_reg);
  96     }
  97   }
  98   return NULL;
  99 }
 100 
 101 //------------------------------StartOSRNode----------------------------------
 102 // The method start node for an on stack replacement adapter
 103 
 104 //------------------------------osr_domain-----------------------------
 105 const TypeTuple *StartOSRNode::osr_domain() {
 106   const Type **fields = TypeTuple::fields(2);
 107   fields[TypeFunc::Parms+0] = TypeRawPtr::BOTTOM;  // address of osr buffer
 108 
 109   return TypeTuple::make(TypeFunc::Parms+1, fields);
 110 }
 111 
 112 //=============================================================================
 113 const char * const ParmNode::names[TypeFunc::Parms+1] = {
 114   "Control", "I_O", "Memory", "FramePtr", "ReturnAdr", "Parms"
 115 };
 116 
 117 #ifndef PRODUCT
 118 void ParmNode::dump_spec(outputStream *st) const {
 119   if( _con < TypeFunc::Parms ) {
 120     st->print("%s", names[_con]);
 121   } else {
 122     st->print("Parm%d: ",_con-TypeFunc::Parms);
 123     // Verbose and WizardMode dump bottom_type for all nodes
 124     if( !Verbose && !WizardMode )   bottom_type()->dump_on(st);
 125   }
 126 }
 127 
 128 void ParmNode::dump_compact_spec(outputStream *st) const {
 129   if (_con < TypeFunc::Parms) {
 130     st->print("%s", names[_con]);
 131   } else {
 132     st->print("%d:", _con-TypeFunc::Parms);
 133     // unconditionally dump bottom_type
 134     bottom_type()->dump_on(st);
 135   }
 136 }
 137 
 138 // For a ParmNode, all immediate inputs and outputs are considered relevant
 139 // both in compact and standard representation.
 140 void ParmNode::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
 141   this->collect_nodes(in_rel, 1, false, false);
 142   this->collect_nodes(out_rel, -1, false, false);
 143 }
 144 #endif
 145 
 146 uint ParmNode::ideal_reg() const {
 147   switch( _con ) {
 148   case TypeFunc::Control  : // fall through
 149   case TypeFunc::I_O      : // fall through
 150   case TypeFunc::Memory   : return 0;
 151   case TypeFunc::FramePtr : // fall through
 152   case TypeFunc::ReturnAdr: return Op_RegP;
 153   default                 : assert( _con > TypeFunc::Parms, "" );
 154     // fall through
 155   case TypeFunc::Parms    : {
 156     // Type of argument being passed
 157     const Type *t = in(0)->as_Start()->_domain->field_at(_con);
 158     return t->ideal_reg();
 159   }
 160   }
 161   ShouldNotReachHere();
 162   return 0;
 163 }
 164 
 165 //=============================================================================
 166 ReturnNode::ReturnNode(uint edges, Node *cntrl, Node *i_o, Node *memory, Node *frameptr, Node *retadr ) : Node(edges) {
 167   init_req(TypeFunc::Control,cntrl);
 168   init_req(TypeFunc::I_O,i_o);
 169   init_req(TypeFunc::Memory,memory);
 170   init_req(TypeFunc::FramePtr,frameptr);
 171   init_req(TypeFunc::ReturnAdr,retadr);
 172 }
 173 
 174 Node *ReturnNode::Ideal(PhaseGVN *phase, bool can_reshape){
 175   return remove_dead_region(phase, can_reshape) ? this : NULL;
 176 }
 177 
 178 const Type* ReturnNode::Value(PhaseGVN* phase) const {
 179   return ( phase->type(in(TypeFunc::Control)) == Type::TOP)
 180     ? Type::TOP
 181     : Type::BOTTOM;
 182 }
 183 
 184 // Do we Match on this edge index or not?  No edges on return nodes
 185 uint ReturnNode::match_edge(uint idx) const {
 186   return 0;
 187 }
 188 
 189 
 190 #ifndef PRODUCT
 191 void ReturnNode::dump_req(outputStream *st) const {
 192   // Dump the required inputs, enclosed in '(' and ')'
 193   uint i;                       // Exit value of loop
 194   for (i = 0; i < req(); i++) {    // For all required inputs
 195     if (i == TypeFunc::Parms) st->print("returns");
 196     if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
 197     else st->print("_ ");
 198   }
 199 }
 200 #endif
 201 
 202 //=============================================================================
 203 RethrowNode::RethrowNode(
 204   Node* cntrl,
 205   Node* i_o,
 206   Node* memory,
 207   Node* frameptr,
 208   Node* ret_adr,
 209   Node* exception
 210 ) : Node(TypeFunc::Parms + 1) {
 211   init_req(TypeFunc::Control  , cntrl    );
 212   init_req(TypeFunc::I_O      , i_o      );
 213   init_req(TypeFunc::Memory   , memory   );
 214   init_req(TypeFunc::FramePtr , frameptr );
 215   init_req(TypeFunc::ReturnAdr, ret_adr);
 216   init_req(TypeFunc::Parms    , exception);
 217 }
 218 
 219 Node *RethrowNode::Ideal(PhaseGVN *phase, bool can_reshape){
 220   return remove_dead_region(phase, can_reshape) ? this : NULL;
 221 }
 222 
 223 const Type* RethrowNode::Value(PhaseGVN* phase) const {
 224   return (phase->type(in(TypeFunc::Control)) == Type::TOP)
 225     ? Type::TOP
 226     : Type::BOTTOM;
 227 }
 228 
 229 uint RethrowNode::match_edge(uint idx) const {
 230   return 0;
 231 }
 232 
 233 #ifndef PRODUCT
 234 void RethrowNode::dump_req(outputStream *st) const {
 235   // Dump the required inputs, enclosed in '(' and ')'
 236   uint i;                       // Exit value of loop
 237   for (i = 0; i < req(); i++) {    // For all required inputs
 238     if (i == TypeFunc::Parms) st->print("exception");
 239     if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
 240     else st->print("_ ");
 241   }
 242 }
 243 #endif
 244 
 245 //=============================================================================
 246 // Do we Match on this edge index or not?  Match only target address & method
 247 uint TailCallNode::match_edge(uint idx) const {
 248   return TypeFunc::Parms <= idx  &&  idx <= TypeFunc::Parms+1;
 249 }
 250 
 251 //=============================================================================
 252 // Do we Match on this edge index or not?  Match only target address & oop
 253 uint TailJumpNode::match_edge(uint idx) const {
 254   return TypeFunc::Parms <= idx  &&  idx <= TypeFunc::Parms+1;
 255 }
 256 
 257 //=============================================================================
 258 JVMState::JVMState(ciMethod* method, JVMState* caller) :
 259   _method(method) {
 260   assert(method != NULL, "must be valid call site");
 261   _bci = InvocationEntryBci;
 262   _reexecute = Reexecute_Undefined;
 263   debug_only(_bci = -99);  // random garbage value
 264   debug_only(_map = (SafePointNode*)-1);
 265   _caller = caller;
 266   _depth  = 1 + (caller == NULL ? 0 : caller->depth());
 267   _locoff = TypeFunc::Parms;
 268   _stkoff = _locoff + _method->max_locals();
 269   _monoff = _stkoff + _method->max_stack();
 270   _scloff = _monoff;
 271   _endoff = _monoff;
 272   _sp = 0;
 273 }
 274 JVMState::JVMState(int stack_size) :
 275   _method(NULL) {
 276   _bci = InvocationEntryBci;
 277   _reexecute = Reexecute_Undefined;
 278   debug_only(_map = (SafePointNode*)-1);
 279   _caller = NULL;
 280   _depth  = 1;
 281   _locoff = TypeFunc::Parms;
 282   _stkoff = _locoff;
 283   _monoff = _stkoff + stack_size;
 284   _scloff = _monoff;
 285   _endoff = _monoff;
 286   _sp = 0;
 287 }
 288 
 289 //--------------------------------of_depth-------------------------------------
 290 JVMState* JVMState::of_depth(int d) const {
 291   const JVMState* jvmp = this;
 292   assert(0 < d && (uint)d <= depth(), "oob");
 293   for (int skip = depth() - d; skip > 0; skip--) {
 294     jvmp = jvmp->caller();
 295   }
 296   assert(jvmp->depth() == (uint)d, "found the right one");
 297   return (JVMState*)jvmp;
 298 }
 299 
 300 //-----------------------------same_calls_as-----------------------------------
 301 bool JVMState::same_calls_as(const JVMState* that) const {
 302   if (this == that)                    return true;
 303   if (this->depth() != that->depth())  return false;
 304   const JVMState* p = this;
 305   const JVMState* q = that;
 306   for (;;) {
 307     if (p->_method != q->_method)    return false;
 308     if (p->_method == NULL)          return true;   // bci is irrelevant
 309     if (p->_bci    != q->_bci)       return false;
 310     if (p->_reexecute != q->_reexecute)  return false;
 311     p = p->caller();
 312     q = q->caller();
 313     if (p == q)                      return true;
 314     assert(p != NULL && q != NULL, "depth check ensures we don't run off end");
 315   }
 316 }
 317 
 318 //------------------------------debug_start------------------------------------
 319 uint JVMState::debug_start()  const {
 320   debug_only(JVMState* jvmroot = of_depth(1));
 321   assert(jvmroot->locoff() <= this->locoff(), "youngest JVMState must be last");
 322   return of_depth(1)->locoff();
 323 }
 324 
 325 //-------------------------------debug_end-------------------------------------
 326 uint JVMState::debug_end() const {
 327   debug_only(JVMState* jvmroot = of_depth(1));
 328   assert(jvmroot->endoff() <= this->endoff(), "youngest JVMState must be last");
 329   return endoff();
 330 }
 331 
 332 //------------------------------debug_depth------------------------------------
 333 uint JVMState::debug_depth() const {
 334   uint total = 0;
 335   for (const JVMState* jvmp = this; jvmp != NULL; jvmp = jvmp->caller()) {
 336     total += jvmp->debug_size();
 337   }
 338   return total;
 339 }
 340 
 341 #ifndef PRODUCT
 342 
 343 //------------------------------format_helper----------------------------------
 344 // Given an allocation (a Chaitin object) and a Node decide if the Node carries
 345 // any defined value or not.  If it does, print out the register or constant.
 346 static void format_helper( PhaseRegAlloc *regalloc, outputStream* st, Node *n, const char *msg, uint i, GrowableArray<SafePointScalarObjectNode*> *scobjs ) {
 347   if (n == NULL) { st->print(" NULL"); return; }
 348   if (n->is_SafePointScalarObject()) {
 349     // Scalar replacement.
 350     SafePointScalarObjectNode* spobj = n->as_SafePointScalarObject();
 351     scobjs->append_if_missing(spobj);
 352     int sco_n = scobjs->find(spobj);
 353     assert(sco_n >= 0, "");
 354     st->print(" %s%d]=#ScObj" INT32_FORMAT, msg, i, sco_n);
 355     return;
 356   }
 357   if (regalloc->node_regs_max_index() > 0 &&
 358       OptoReg::is_valid(regalloc->get_reg_first(n))) { // Check for undefined
 359     char buf[50];
 360     regalloc->dump_register(n,buf);
 361     st->print(" %s%d]=%s",msg,i,buf);
 362   } else {                      // No register, but might be constant
 363     const Type *t = n->bottom_type();
 364     switch (t->base()) {
 365     case Type::Int:
 366       st->print(" %s%d]=#" INT32_FORMAT,msg,i,t->is_int()->get_con());
 367       break;
 368     case Type::AnyPtr:
 369       assert( t == TypePtr::NULL_PTR || n->in_dump(), "" );
 370       st->print(" %s%d]=#NULL",msg,i);
 371       break;
 372     case Type::AryPtr:
 373     case Type::ValueTypePtr:
 374     case Type::InstPtr:
 375       st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->isa_oopptr()->const_oop()));
 376       break;
 377     case Type::KlassPtr:
 378       st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_klassptr()->klass()));
 379       break;
 380     case Type::MetadataPtr:
 381       st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_metadataptr()->metadata()));
 382       break;
 383     case Type::NarrowOop:
 384       st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_oopptr()->const_oop()));
 385       break;
 386     case Type::RawPtr:
 387       st->print(" %s%d]=#Raw" INTPTR_FORMAT,msg,i,p2i(t->is_rawptr()));
 388       break;
 389     case Type::DoubleCon:
 390       st->print(" %s%d]=#%fD",msg,i,t->is_double_constant()->_d);
 391       break;
 392     case Type::FloatCon:
 393       st->print(" %s%d]=#%fF",msg,i,t->is_float_constant()->_f);
 394       break;
 395     case Type::Long:
 396       st->print(" %s%d]=#" INT64_FORMAT,msg,i,(int64_t)(t->is_long()->get_con()));
 397       break;
 398     case Type::Half:
 399     case Type::Top:
 400       st->print(" %s%d]=_",msg,i);
 401       break;
 402     default: ShouldNotReachHere();
 403     }
 404   }
 405 }
 406 
 407 //------------------------------format-----------------------------------------
 408 void JVMState::format(PhaseRegAlloc *regalloc, const Node *n, outputStream* st) const {
 409   st->print("        #");
 410   if (_method) {
 411     _method->print_short_name(st);
 412     st->print(" @ bci:%d ",_bci);
 413   } else {
 414     st->print_cr(" runtime stub ");
 415     return;
 416   }
 417   if (n->is_MachSafePoint()) {
 418     GrowableArray<SafePointScalarObjectNode*> scobjs;
 419     MachSafePointNode *mcall = n->as_MachSafePoint();
 420     uint i;
 421     // Print locals
 422     for (i = 0; i < (uint)loc_size(); i++)
 423       format_helper(regalloc, st, mcall->local(this, i), "L[", i, &scobjs);
 424     // Print stack
 425     for (i = 0; i < (uint)stk_size(); i++) {
 426       if ((uint)(_stkoff + i) >= mcall->len())
 427         st->print(" oob ");
 428       else
 429        format_helper(regalloc, st, mcall->stack(this, i), "STK[", i, &scobjs);
 430     }
 431     for (i = 0; (int)i < nof_monitors(); i++) {
 432       Node *box = mcall->monitor_box(this, i);
 433       Node *obj = mcall->monitor_obj(this, i);
 434       if (regalloc->node_regs_max_index() > 0 &&
 435           OptoReg::is_valid(regalloc->get_reg_first(box))) {
 436         box = BoxLockNode::box_node(box);
 437         format_helper(regalloc, st, box, "MON-BOX[", i, &scobjs);
 438       } else {
 439         OptoReg::Name box_reg = BoxLockNode::reg(box);
 440         st->print(" MON-BOX%d=%s+%d",
 441                    i,
 442                    OptoReg::regname(OptoReg::c_frame_pointer),
 443                    regalloc->reg2offset(box_reg));
 444       }
 445       const char* obj_msg = "MON-OBJ[";
 446       if (EliminateLocks) {
 447         if (BoxLockNode::box_node(box)->is_eliminated())
 448           obj_msg = "MON-OBJ(LOCK ELIMINATED)[";
 449       }
 450       format_helper(regalloc, st, obj, obj_msg, i, &scobjs);
 451     }
 452 
 453     for (i = 0; i < (uint)scobjs.length(); i++) {
 454       // Scalar replaced objects.
 455       st->cr();
 456       st->print("        # ScObj" INT32_FORMAT " ", i);
 457       SafePointScalarObjectNode* spobj = scobjs.at(i);
 458       ciKlass* cik = spobj->bottom_type()->is_oopptr()->klass();
 459       assert(cik->is_instance_klass() ||
 460              cik->is_array_klass(), "Not supported allocation.");
 461       ciInstanceKlass *iklass = NULL;
 462       if (cik->is_instance_klass()) {
 463         cik->print_name_on(st);
 464         iklass = cik->as_instance_klass();
 465       } else if (cik->is_type_array_klass()) {
 466         cik->as_array_klass()->base_element_type()->print_name_on(st);
 467         st->print("[%d]", spobj->n_fields());
 468       } else if (cik->is_obj_array_klass()) {
 469         ciKlass* cie = cik->as_obj_array_klass()->base_element_klass();
 470         if (cie->is_instance_klass()) {
 471           cie->print_name_on(st);
 472         } else if (cie->is_type_array_klass()) {
 473           cie->as_array_klass()->base_element_type()->print_name_on(st);
 474         } else {
 475           ShouldNotReachHere();
 476         }
 477         st->print("[%d]", spobj->n_fields());
 478         int ndim = cik->as_array_klass()->dimension() - 1;
 479         while (ndim-- > 0) {
 480           st->print("[]");
 481         }
 482       }
 483       st->print("={");
 484       uint nf = spobj->n_fields();
 485       if (nf > 0) {
 486         uint first_ind = spobj->first_index(mcall->jvms());
 487         Node* fld_node = mcall->in(first_ind);
 488         ciField* cifield;
 489         if (iklass != NULL) {
 490           st->print(" [");
 491           cifield = iklass->nonstatic_field_at(0);
 492           cifield->print_name_on(st);
 493           format_helper(regalloc, st, fld_node, ":", 0, &scobjs);
 494         } else {
 495           format_helper(regalloc, st, fld_node, "[", 0, &scobjs);
 496         }
 497         for (uint j = 1; j < nf; j++) {
 498           fld_node = mcall->in(first_ind+j);
 499           if (iklass != NULL) {
 500             st->print(", [");
 501             cifield = iklass->nonstatic_field_at(j);
 502             cifield->print_name_on(st);
 503             format_helper(regalloc, st, fld_node, ":", j, &scobjs);
 504           } else {
 505             format_helper(regalloc, st, fld_node, ", [", j, &scobjs);
 506           }
 507         }
 508       }
 509       st->print(" }");
 510     }
 511   }
 512   st->cr();
 513   if (caller() != NULL) caller()->format(regalloc, n, st);
 514 }
 515 
 516 
 517 void JVMState::dump_spec(outputStream *st) const {
 518   if (_method != NULL) {
 519     bool printed = false;
 520     if (!Verbose) {
 521       // The JVMS dumps make really, really long lines.
 522       // Take out the most boring parts, which are the package prefixes.
 523       char buf[500];
 524       stringStream namest(buf, sizeof(buf));
 525       _method->print_short_name(&namest);
 526       if (namest.count() < sizeof(buf)) {
 527         const char* name = namest.base();
 528         if (name[0] == ' ')  ++name;
 529         const char* endcn = strchr(name, ':');  // end of class name
 530         if (endcn == NULL)  endcn = strchr(name, '(');
 531         if (endcn == NULL)  endcn = name + strlen(name);
 532         while (endcn > name && endcn[-1] != '.' && endcn[-1] != '/')
 533           --endcn;
 534         st->print(" %s", endcn);
 535         printed = true;
 536       }
 537     }
 538     if (!printed)
 539       _method->print_short_name(st);
 540     st->print(" @ bci:%d",_bci);
 541     if(_reexecute == Reexecute_True)
 542       st->print(" reexecute");
 543   } else {
 544     st->print(" runtime stub");
 545   }
 546   if (caller() != NULL)  caller()->dump_spec(st);
 547 }
 548 
 549 
 550 void JVMState::dump_on(outputStream* st) const {
 551   bool print_map = _map && !((uintptr_t)_map & 1) &&
 552                   ((caller() == NULL) || (caller()->map() != _map));
 553   if (print_map) {
 554     if (_map->len() > _map->req()) {  // _map->has_exceptions()
 555       Node* ex = _map->in(_map->req());  // _map->next_exception()
 556       // skip the first one; it's already being printed
 557       while (ex != NULL && ex->len() > ex->req()) {
 558         ex = ex->in(ex->req());  // ex->next_exception()
 559         ex->dump(1);
 560       }
 561     }
 562     _map->dump(Verbose ? 2 : 1);
 563   }
 564   if (caller() != NULL) {
 565     caller()->dump_on(st);
 566   }
 567   st->print("JVMS depth=%d loc=%d stk=%d arg=%d mon=%d scalar=%d end=%d mondepth=%d sp=%d bci=%d reexecute=%s method=",
 568              depth(), locoff(), stkoff(), argoff(), monoff(), scloff(), endoff(), monitor_depth(), sp(), bci(), should_reexecute()?"true":"false");
 569   if (_method == NULL) {
 570     st->print_cr("(none)");
 571   } else {
 572     _method->print_name(st);
 573     st->cr();
 574     if (bci() >= 0 && bci() < _method->code_size()) {
 575       st->print("    bc: ");
 576       _method->print_codes_on(bci(), bci()+1, st);
 577     }
 578   }
 579 }
 580 
 581 // Extra way to dump a jvms from the debugger,
 582 // to avoid a bug with C++ member function calls.
 583 void dump_jvms(JVMState* jvms) {
 584   jvms->dump();
 585 }
 586 #endif
 587 
 588 //--------------------------clone_shallow--------------------------------------
 589 JVMState* JVMState::clone_shallow(Compile* C) const {
 590   JVMState* n = has_method() ? new (C) JVMState(_method, _caller) : new (C) JVMState(0);
 591   n->set_bci(_bci);
 592   n->_reexecute = _reexecute;
 593   n->set_locoff(_locoff);
 594   n->set_stkoff(_stkoff);
 595   n->set_monoff(_monoff);
 596   n->set_scloff(_scloff);
 597   n->set_endoff(_endoff);
 598   n->set_sp(_sp);
 599   n->set_map(_map);
 600   return n;
 601 }
 602 
 603 //---------------------------clone_deep----------------------------------------
 604 JVMState* JVMState::clone_deep(Compile* C) const {
 605   JVMState* n = clone_shallow(C);
 606   for (JVMState* p = n; p->_caller != NULL; p = p->_caller) {
 607     p->_caller = p->_caller->clone_shallow(C);
 608   }
 609   assert(n->depth() == depth(), "sanity");
 610   assert(n->debug_depth() == debug_depth(), "sanity");
 611   return n;
 612 }
 613 
 614 /**
 615  * Reset map for all callers
 616  */
 617 void JVMState::set_map_deep(SafePointNode* map) {
 618   for (JVMState* p = this; p->_caller != NULL; p = p->_caller) {
 619     p->set_map(map);
 620   }
 621 }
 622 
 623 // Adapt offsets in in-array after adding or removing an edge.
 624 // Prerequisite is that the JVMState is used by only one node.
 625 void JVMState::adapt_position(int delta) {
 626   for (JVMState* jvms = this; jvms != NULL; jvms = jvms->caller()) {
 627     jvms->set_locoff(jvms->locoff() + delta);
 628     jvms->set_stkoff(jvms->stkoff() + delta);
 629     jvms->set_monoff(jvms->monoff() + delta);
 630     jvms->set_scloff(jvms->scloff() + delta);
 631     jvms->set_endoff(jvms->endoff() + delta);
 632   }
 633 }
 634 
 635 // Mirror the stack size calculation in the deopt code
 636 // How much stack space would we need at this point in the program in
 637 // case of deoptimization?
 638 int JVMState::interpreter_frame_size() const {
 639   const JVMState* jvms = this;
 640   int size = 0;
 641   int callee_parameters = 0;
 642   int callee_locals = 0;
 643   int extra_args = method()->max_stack() - stk_size();
 644 
 645   while (jvms != NULL) {
 646     int locks = jvms->nof_monitors();
 647     int temps = jvms->stk_size();
 648     bool is_top_frame = (jvms == this);
 649     ciMethod* method = jvms->method();
 650 
 651     int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),
 652                                                                  temps + callee_parameters,
 653                                                                  extra_args,
 654                                                                  locks,
 655                                                                  callee_parameters,
 656                                                                  callee_locals,
 657                                                                  is_top_frame);
 658     size += frame_size;
 659 
 660     callee_parameters = method->size_of_parameters();
 661     callee_locals = method->max_locals();
 662     extra_args = 0;
 663     jvms = jvms->caller();
 664   }
 665   return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;
 666 }
 667 
 668 //=============================================================================
 669 uint CallNode::cmp( const Node &n ) const
 670 { return _tf == ((CallNode&)n)._tf && _jvms == ((CallNode&)n)._jvms; }
 671 #ifndef PRODUCT
 672 void CallNode::dump_req(outputStream *st) const {
 673   // Dump the required inputs, enclosed in '(' and ')'
 674   uint i;                       // Exit value of loop
 675   for (i = 0; i < req(); i++) {    // For all required inputs
 676     if (i == TypeFunc::Parms) st->print("(");
 677     if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
 678     else st->print("_ ");
 679   }
 680   st->print(")");
 681 }
 682 
 683 void CallNode::dump_spec(outputStream *st) const {
 684   st->print(" ");
 685   if (tf() != NULL)  tf()->dump_on(st);
 686   if (_cnt != COUNT_UNKNOWN)  st->print(" C=%f",_cnt);
 687   if (jvms() != NULL)  jvms()->dump_spec(st);
 688 }
 689 #endif
 690 
 691 const Type *CallNode::bottom_type() const { return tf()->range_cc(); }
 692 const Type* CallNode::Value(PhaseGVN* phase) const {
 693   if (phase->type(in(0)) == Type::TOP)  return Type::TOP;
 694   return tf()->range_cc();
 695 }
 696 
 697 //------------------------------calling_convention-----------------------------
 698 void CallNode::calling_convention(BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt) const {
 699   if (_entry_point == StubRoutines::store_value_type_fields_to_buf()) {
 700     // The call to that stub is a special case: its inputs are
 701     // multiple values returned from a call and so it should follow
 702     // the return convention.
 703     SharedRuntime::java_return_convention(sig_bt, parm_regs, argcnt);
 704     return;
 705   }
 706   // Use the standard compiler calling convention
 707   Matcher::calling_convention( sig_bt, parm_regs, argcnt, true );
 708 }
 709 
 710 
 711 //------------------------------match------------------------------------------
 712 // Construct projections for control, I/O, memory-fields, ..., and
 713 // return result(s) along with their RegMask info
 714 Node *CallNode::match(const ProjNode *proj, const Matcher *match, const RegMask* mask) {
 715   uint con = proj->_con;
 716   const TypeTuple *range_cc = tf()->range_cc();
 717   if (con >= TypeFunc::Parms) {
 718     if (is_CallRuntime()) {
 719       if (con == TypeFunc::Parms) {
 720         uint ideal_reg = range_cc->field_at(TypeFunc::Parms)->ideal_reg();
 721         OptoRegPair regs = match->c_return_value(ideal_reg,true);
 722         RegMask rm = RegMask(regs.first());
 723         if (OptoReg::is_valid(regs.second())) {
 724           rm.Insert(regs.second());
 725         }
 726         return new MachProjNode(this,con,rm,ideal_reg);
 727       } else {
 728         assert(con == TypeFunc::Parms+1, "only one return value");
 729         assert(range_cc->field_at(TypeFunc::Parms+1) == Type::HALF, "");
 730         return new MachProjNode(this,con, RegMask::Empty, (uint)OptoReg::Bad);
 731       }
 732     } else {
 733       // The Call may return multiple values (value type fields): we
 734       // create one projection per returned values.
 735       assert(con <= TypeFunc::Parms+1 || ValueTypeReturnedAsFields, "only for multi value return");
 736       uint ideal_reg = range_cc->field_at(con)->ideal_reg();
 737       return new MachProjNode(this, con, mask[con-TypeFunc::Parms], ideal_reg);
 738     }
 739   }
 740 
 741   switch (con) {
 742   case TypeFunc::Control:
 743   case TypeFunc::I_O:
 744   case TypeFunc::Memory:
 745     return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
 746 
 747   case TypeFunc::ReturnAdr:
 748   case TypeFunc::FramePtr:
 749   default:
 750     ShouldNotReachHere();
 751   }
 752   return NULL;
 753 }
 754 
 755 // Do we Match on this edge index or not?  Match no edges
 756 uint CallNode::match_edge(uint idx) const {
 757   return 0;
 758 }
 759 
 760 //
 761 // Determine whether the call could modify the field of the specified
 762 // instance at the specified offset.
 763 //
 764 bool CallNode::may_modify(const TypeOopPtr *t_oop, PhaseTransform *phase) {
 765   assert((t_oop != NULL), "sanity");
 766   if (is_call_to_arraycopystub() && strcmp(_name, "unsafe_arraycopy") != 0) {
 767     const TypeTuple* args = _tf->domain_sig();
 768     Node* dest = NULL;
 769     // Stubs that can be called once an ArrayCopyNode is expanded have
 770     // different signatures. Look for the second pointer argument,
 771     // that is the destination of the copy.
 772     for (uint i = TypeFunc::Parms, j = 0; i < args->cnt(); i++) {
 773       if (args->field_at(i)->isa_ptr()) {
 774         j++;
 775         if (j == 2) {
 776           dest = in(i);
 777           break;
 778         }
 779       }
 780     }
 781     if (!dest->is_top() && may_modify_arraycopy_helper(phase->type(dest)->is_oopptr(), t_oop, phase)) {
 782       return true;
 783     }
 784     return false;
 785   }
 786   if (t_oop->is_known_instance()) {
 787     // The instance_id is set only for scalar-replaceable allocations which
 788     // are not passed as arguments according to Escape Analysis.
 789     return false;
 790   }
 791   if (t_oop->is_ptr_to_boxed_value()) {
 792     ciKlass* boxing_klass = t_oop->klass();
 793     if (is_CallStaticJava() && as_CallStaticJava()->is_boxing_method()) {
 794       // Skip unrelated boxing methods.
 795       Node* proj = proj_out(TypeFunc::Parms);
 796       if ((proj == NULL) || (phase->type(proj)->is_instptr()->klass() != boxing_klass)) {
 797         return false;
 798       }
 799     }
 800     if (is_CallJava() && as_CallJava()->method() != NULL) {
 801       ciMethod* meth = as_CallJava()->method();
 802       if (meth->is_getter()) {
 803         return false;
 804       }
 805       // May modify (by reflection) if an boxing object is passed
 806       // as argument or returned.
 807       Node* proj = returns_pointer() ? proj_out(TypeFunc::Parms) : NULL;
 808       if (proj != NULL) {
 809         const TypeInstPtr* inst_t = phase->type(proj)->isa_instptr();
 810         if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||
 811                                  (inst_t->klass() == boxing_klass))) {
 812           return true;
 813         }
 814       }
 815       const TypeTuple* d = tf()->domain_cc();
 816       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
 817         const TypeInstPtr* inst_t = d->field_at(i)->isa_instptr();
 818         if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||
 819                                  (inst_t->klass() == boxing_klass))) {
 820           return true;
 821         }
 822       }
 823       return false;
 824     }
 825   }
 826   return true;
 827 }
 828 
 829 // Does this call have a direct reference to n other than debug information?
 830 bool CallNode::has_non_debug_use(Node *n) {
 831   const TypeTuple * d = tf()->domain_cc();
 832   for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
 833     Node *arg = in(i);
 834     if (arg == n) {
 835       return true;
 836     }
 837   }
 838   return false;
 839 }
 840 
 841 bool CallNode::has_debug_use(Node *n) {
 842   for (uint i = jvms()->debug_start(); i < jvms()->debug_end(); i++) {
 843     Node *arg = in(i);
 844     if (arg == n) {
 845       return true;
 846     }
 847   }
 848   return false;
 849 }
 850 
 851 // Returns the unique CheckCastPP of a call
 852 // or 'this' if there are several CheckCastPP or unexpected uses
 853 // or returns NULL if there is no one.
 854 Node *CallNode::result_cast() {
 855   Node *cast = NULL;
 856 
 857   Node *p = proj_out(TypeFunc::Parms);
 858   if (p == NULL)
 859     return NULL;
 860 
 861   for (DUIterator_Fast imax, i = p->fast_outs(imax); i < imax; i++) {
 862     Node *use = p->fast_out(i);
 863     if (use->is_CheckCastPP()) {
 864       if (cast != NULL) {
 865         return this;  // more than 1 CheckCastPP
 866       }
 867       cast = use;
 868     } else if (!use->is_Initialize() &&
 869                !use->is_AddP() &&
 870                use->Opcode() != Op_MemBarStoreStore) {
 871       // Expected uses are restricted to a CheckCastPP, an Initialize
 872       // node, a MemBarStoreStore (clone) and AddP nodes. If we
 873       // encounter any other use (a Phi node can be seen in rare
 874       // cases) return this to prevent incorrect optimizations.
 875       return this;
 876     }
 877   }
 878   return cast;
 879 }
 880 
 881 
 882 void CallNode::extract_projections(CallProjections* projs, bool separate_io_proj, bool do_asserts) {
 883   projs->fallthrough_proj      = NULL;
 884   projs->fallthrough_catchproj = NULL;
 885   projs->fallthrough_ioproj    = NULL;
 886   projs->catchall_ioproj       = NULL;
 887   projs->catchall_catchproj    = NULL;
 888   projs->fallthrough_memproj   = NULL;
 889   projs->catchall_memproj      = NULL;
 890   projs->resproj               = NULL;
 891   projs->exobj                 = NULL;
 892 
 893   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
 894     ProjNode *pn = fast_out(i)->as_Proj();
 895     if (pn->outcnt() == 0) continue;
 896     switch (pn->_con) {
 897     case TypeFunc::Control:
 898       {
 899         // For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj
 900         projs->fallthrough_proj = pn;
 901         DUIterator_Fast jmax, j = pn->fast_outs(jmax);
 902         const Node *cn = pn->fast_out(j);
 903         if (cn->is_Catch()) {
 904           ProjNode *cpn = NULL;
 905           for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) {
 906             cpn = cn->fast_out(k)->as_Proj();
 907             assert(cpn->is_CatchProj(), "must be a CatchProjNode");
 908             if (cpn->_con == CatchProjNode::fall_through_index)
 909               projs->fallthrough_catchproj = cpn;
 910             else {
 911               assert(cpn->_con == CatchProjNode::catch_all_index, "must be correct index.");
 912               projs->catchall_catchproj = cpn;
 913             }
 914           }
 915         }
 916         break;
 917       }
 918     case TypeFunc::I_O:
 919       if (pn->_is_io_use)
 920         projs->catchall_ioproj = pn;
 921       else
 922         projs->fallthrough_ioproj = pn;
 923       for (DUIterator j = pn->outs(); pn->has_out(j); j++) {
 924         Node* e = pn->out(j);
 925         if (e->Opcode() == Op_CreateEx && e->in(0)->is_CatchProj() && e->outcnt() > 0) {
 926           assert(projs->exobj == NULL, "only one");
 927           projs->exobj = e;
 928         }
 929       }
 930       break;
 931     case TypeFunc::Memory:
 932       if (pn->_is_io_use)
 933         projs->catchall_memproj = pn;
 934       else
 935         projs->fallthrough_memproj = pn;
 936       break;
 937     case TypeFunc::Parms:
 938       projs->resproj = pn;
 939       break;
 940     default:
 941       assert(false, "unexpected projection from allocation node.");
 942     }
 943   }
 944 
 945   // The resproj may not exist because the result could be ignored
 946   // and the exception object may not exist if an exception handler
 947   // swallows the exception but all the other must exist and be found.
 948   assert(projs->fallthrough_proj      != NULL, "must be found");
 949   do_asserts = do_asserts && !Compile::current()->inlining_incrementally();
 950   assert(!do_asserts || projs->fallthrough_catchproj != NULL, "must be found");
 951   assert(!do_asserts || projs->fallthrough_memproj   != NULL, "must be found");
 952   assert(!do_asserts || projs->fallthrough_ioproj    != NULL, "must be found");
 953   assert(!do_asserts || projs->catchall_catchproj    != NULL, "must be found");
 954   if (separate_io_proj) {
 955     assert(!do_asserts || projs->catchall_memproj    != NULL, "must be found");
 956     assert(!do_asserts || projs->catchall_ioproj     != NULL, "must be found");
 957   }
 958 }
 959 
 960 Node *CallNode::Ideal(PhaseGVN *phase, bool can_reshape) {
 961   CallGenerator* cg = generator();
 962   if (can_reshape && cg != NULL && cg->is_mh_late_inline() && !cg->already_attempted()) {
 963     // Check whether this MH handle call becomes a candidate for inlining
 964     ciMethod* callee = cg->method();
 965     vmIntrinsics::ID iid = callee->intrinsic_id();
 966     if (iid == vmIntrinsics::_invokeBasic) {
 967       if (in(TypeFunc::Parms)->Opcode() == Op_ConP) {
 968         phase->C->prepend_late_inline(cg);
 969         set_generator(NULL);
 970       }
 971     } else {
 972       assert(callee->has_member_arg(), "wrong type of call?");
 973       if (in(TypeFunc::Parms + callee->arg_size() - 1)->Opcode() == Op_ConP) {
 974         phase->C->prepend_late_inline(cg);
 975         set_generator(NULL);
 976       }
 977     }
 978   }
 979   return SafePointNode::Ideal(phase, can_reshape);
 980 }
 981 
 982 bool CallNode::is_call_to_arraycopystub() const {
 983   if (_name != NULL && strstr(_name, "arraycopy") != 0) {
 984     return true;
 985   }
 986   return false;
 987 }
 988 
 989 //=============================================================================
 990 uint CallJavaNode::size_of() const { return sizeof(*this); }
 991 uint CallJavaNode::cmp( const Node &n ) const {
 992   CallJavaNode &call = (CallJavaNode&)n;
 993   return CallNode::cmp(call) && _method == call._method &&
 994          _override_symbolic_info == call._override_symbolic_info;
 995 }
 996 #ifndef PRODUCT
 997 void CallJavaNode::dump_spec(outputStream *st) const {
 998   if( _method ) _method->print_short_name(st);
 999   CallNode::dump_spec(st);
1000 }
1001 
1002 void CallJavaNode::dump_compact_spec(outputStream* st) const {
1003   if (_method) {
1004     _method->print_short_name(st);
1005   } else {
1006     st->print("<?>");
1007   }
1008 }
1009 #endif
1010 
1011 //=============================================================================
1012 uint CallStaticJavaNode::size_of() const { return sizeof(*this); }
1013 uint CallStaticJavaNode::cmp( const Node &n ) const {
1014   CallStaticJavaNode &call = (CallStaticJavaNode&)n;
1015   return CallJavaNode::cmp(call);
1016 }
1017 
1018 //----------------------------uncommon_trap_request----------------------------
1019 // If this is an uncommon trap, return the request code, else zero.
1020 int CallStaticJavaNode::uncommon_trap_request() const {
1021   if (_name != NULL && !strcmp(_name, "uncommon_trap")) {
1022     return extract_uncommon_trap_request(this);
1023   }
1024   return 0;
1025 }
1026 int CallStaticJavaNode::extract_uncommon_trap_request(const Node* call) {
1027 #ifndef PRODUCT
1028   if (!(call->req() > TypeFunc::Parms &&
1029         call->in(TypeFunc::Parms) != NULL &&
1030         call->in(TypeFunc::Parms)->is_Con() &&
1031         call->in(TypeFunc::Parms)->bottom_type()->isa_int())) {
1032     assert(in_dump() != 0, "OK if dumping");
1033     tty->print("[bad uncommon trap]");
1034     return 0;
1035   }
1036 #endif
1037   return call->in(TypeFunc::Parms)->bottom_type()->is_int()->get_con();
1038 }
1039 
1040 #ifndef PRODUCT
1041 void CallStaticJavaNode::dump_spec(outputStream *st) const {
1042   st->print("# Static ");
1043   if (_name != NULL) {
1044     st->print("%s", _name);
1045     int trap_req = uncommon_trap_request();
1046     if (trap_req != 0) {
1047       char buf[100];
1048       st->print("(%s)",
1049                  Deoptimization::format_trap_request(buf, sizeof(buf),
1050                                                      trap_req));
1051     }
1052     st->print(" ");
1053   }
1054   CallJavaNode::dump_spec(st);
1055 }
1056 
1057 void CallStaticJavaNode::dump_compact_spec(outputStream* st) const {
1058   if (_method) {
1059     _method->print_short_name(st);
1060   } else if (_name) {
1061     st->print("%s", _name);
1062   } else {
1063     st->print("<?>");
1064   }
1065 }
1066 #endif
1067 
1068 //=============================================================================
1069 uint CallDynamicJavaNode::size_of() const { return sizeof(*this); }
1070 uint CallDynamicJavaNode::cmp( const Node &n ) const {
1071   CallDynamicJavaNode &call = (CallDynamicJavaNode&)n;
1072   return CallJavaNode::cmp(call);
1073 }
1074 #ifndef PRODUCT
1075 void CallDynamicJavaNode::dump_spec(outputStream *st) const {
1076   st->print("# Dynamic ");
1077   CallJavaNode::dump_spec(st);
1078 }
1079 #endif
1080 
1081 //=============================================================================
1082 uint CallRuntimeNode::size_of() const { return sizeof(*this); }
1083 uint CallRuntimeNode::cmp( const Node &n ) const {
1084   CallRuntimeNode &call = (CallRuntimeNode&)n;
1085   return CallNode::cmp(call) && !strcmp(_name,call._name);
1086 }
1087 #ifndef PRODUCT
1088 void CallRuntimeNode::dump_spec(outputStream *st) const {
1089   st->print("# ");
1090   st->print("%s", _name);
1091   CallNode::dump_spec(st);
1092 }
1093 #endif
1094 
1095 //------------------------------calling_convention-----------------------------
1096 void CallRuntimeNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
1097   if (_entry_point == NULL) {
1098     // The call to that stub is a special case: its inputs are
1099     // multiple values returned from a call and so it should follow
1100     // the return convention.
1101     SharedRuntime::java_return_convention(sig_bt, parm_regs, argcnt);
1102     return;
1103   }
1104   Matcher::c_calling_convention( sig_bt, parm_regs, argcnt );
1105 }
1106 
1107 //=============================================================================
1108 //------------------------------calling_convention-----------------------------
1109 
1110 
1111 //=============================================================================
1112 #ifndef PRODUCT
1113 void CallLeafNode::dump_spec(outputStream *st) const {
1114   st->print("# ");
1115   st->print("%s", _name);
1116   CallNode::dump_spec(st);
1117 }
1118 #endif
1119 
1120 uint CallLeafNoFPNode::match_edge(uint idx) const {
1121   // Null entry point is a special case for which the target is in a
1122   // register. Need to match that edge.
1123   return entry_point() == NULL && idx == TypeFunc::Parms;
1124 }
1125 
1126 //=============================================================================
1127 
1128 void SafePointNode::set_local(JVMState* jvms, uint idx, Node *c) {
1129   assert(verify_jvms(jvms), "jvms must match");
1130   int loc = jvms->locoff() + idx;
1131   if (in(loc)->is_top() && idx > 0 && !c->is_top() ) {
1132     // If current local idx is top then local idx - 1 could
1133     // be a long/double that needs to be killed since top could
1134     // represent the 2nd half ofthe long/double.
1135     uint ideal = in(loc -1)->ideal_reg();
1136     if (ideal == Op_RegD || ideal == Op_RegL) {
1137       // set other (low index) half to top
1138       set_req(loc - 1, in(loc));
1139     }
1140   }
1141   set_req(loc, c);
1142 }
1143 
1144 uint SafePointNode::size_of() const { return sizeof(*this); }
1145 uint SafePointNode::cmp( const Node &n ) const {
1146   return (&n == this);          // Always fail except on self
1147 }
1148 
1149 //-------------------------set_next_exception----------------------------------
1150 void SafePointNode::set_next_exception(SafePointNode* n) {
1151   assert(n == NULL || n->Opcode() == Op_SafePoint, "correct value for next_exception");
1152   if (len() == req()) {
1153     if (n != NULL)  add_prec(n);
1154   } else {
1155     set_prec(req(), n);
1156   }
1157 }
1158 
1159 
1160 //----------------------------next_exception-----------------------------------
1161 SafePointNode* SafePointNode::next_exception() const {
1162   if (len() == req()) {
1163     return NULL;
1164   } else {
1165     Node* n = in(req());
1166     assert(n == NULL || n->Opcode() == Op_SafePoint, "no other uses of prec edges");
1167     return (SafePointNode*) n;
1168   }
1169 }
1170 
1171 
1172 //------------------------------Ideal------------------------------------------
1173 // Skip over any collapsed Regions
1174 Node *SafePointNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1175   if (remove_dead_region(phase, can_reshape)) {
1176     return this;
1177   }
1178   if (jvms() != NULL) {
1179     bool progress = false;
1180     // A ValueTypeNode that was already heap allocated in the debug
1181     // info?  Reference the object directly. Helps removal of useless
1182     // value type allocations with incremental inlining.
1183     for (uint i = jvms()->debug_start(); i < jvms()->debug_end(); i++) {
1184       Node *arg = in(i);
1185       if (arg->is_ValueType()) {
1186         ValueTypeNode* vt = arg->as_ValueType();
1187         Node* in_oop = vt->get_oop();
1188         const Type* oop_type = phase->type(in_oop);
1189         if (!TypePtr::NULL_PTR->higher_equal(oop_type)) {
1190           set_req(i, in_oop);
1191           progress = true;
1192         }
1193       }
1194     }
1195     if (progress) {
1196       return this;
1197     }
1198   }
1199   return NULL;
1200 }
1201 
1202 //------------------------------Identity---------------------------------------
1203 // Remove obviously duplicate safepoints
1204 Node* SafePointNode::Identity(PhaseGVN* phase) {
1205 
1206   // If you have back to back safepoints, remove one
1207   if( in(TypeFunc::Control)->is_SafePoint() )
1208     return in(TypeFunc::Control);
1209 
1210   if( in(0)->is_Proj() ) {
1211     Node *n0 = in(0)->in(0);
1212     // Check if he is a call projection (except Leaf Call)
1213     if( n0->is_Catch() ) {
1214       n0 = n0->in(0)->in(0);
1215       assert( n0->is_Call(), "expect a call here" );
1216     }
1217     if( n0->is_Call() && n0->as_Call()->guaranteed_safepoint() ) {
1218       // Useless Safepoint, so remove it
1219       return in(TypeFunc::Control);
1220     }
1221   }
1222 
1223   return this;
1224 }
1225 
1226 //------------------------------Value------------------------------------------
1227 const Type* SafePointNode::Value(PhaseGVN* phase) const {
1228   if( phase->type(in(0)) == Type::TOP ) return Type::TOP;
1229   if( phase->eqv( in(0), this ) ) return Type::TOP; // Dead infinite loop
1230   return Type::CONTROL;
1231 }
1232 
1233 #ifndef PRODUCT
1234 void SafePointNode::dump_spec(outputStream *st) const {
1235   st->print(" SafePoint ");
1236   _replaced_nodes.dump(st);
1237 }
1238 
1239 // The related nodes of a SafepointNode are all data inputs, excluding the
1240 // control boundary, as well as all outputs till level 2 (to include projection
1241 // nodes and targets). In compact mode, just include inputs till level 1 and
1242 // outputs as before.
1243 void SafePointNode::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
1244   if (compact) {
1245     this->collect_nodes(in_rel, 1, false, false);
1246   } else {
1247     this->collect_nodes_in_all_data(in_rel, false);
1248   }
1249   this->collect_nodes(out_rel, -2, false, false);
1250 }
1251 #endif
1252 
1253 const RegMask &SafePointNode::in_RegMask(uint idx) const {
1254   if( idx < TypeFunc::Parms ) return RegMask::Empty;
1255   // Values outside the domain represent debug info
1256   return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
1257 }
1258 const RegMask &SafePointNode::out_RegMask() const {
1259   return RegMask::Empty;
1260 }
1261 
1262 
1263 void SafePointNode::grow_stack(JVMState* jvms, uint grow_by) {
1264   assert((int)grow_by > 0, "sanity");
1265   int monoff = jvms->monoff();
1266   int scloff = jvms->scloff();
1267   int endoff = jvms->endoff();
1268   assert(endoff == (int)req(), "no other states or debug info after me");
1269   Node* top = Compile::current()->top();
1270   for (uint i = 0; i < grow_by; i++) {
1271     ins_req(monoff, top);
1272   }
1273   jvms->set_monoff(monoff + grow_by);
1274   jvms->set_scloff(scloff + grow_by);
1275   jvms->set_endoff(endoff + grow_by);
1276 }
1277 
1278 void SafePointNode::push_monitor(const FastLockNode *lock) {
1279   // Add a LockNode, which points to both the original BoxLockNode (the
1280   // stack space for the monitor) and the Object being locked.
1281   const int MonitorEdges = 2;
1282   assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
1283   assert(req() == jvms()->endoff(), "correct sizing");
1284   int nextmon = jvms()->scloff();
1285   if (GenerateSynchronizationCode) {
1286     ins_req(nextmon,   lock->box_node());
1287     ins_req(nextmon+1, lock->obj_node());
1288   } else {
1289     Node* top = Compile::current()->top();
1290     ins_req(nextmon, top);
1291     ins_req(nextmon, top);
1292   }
1293   jvms()->set_scloff(nextmon + MonitorEdges);
1294   jvms()->set_endoff(req());
1295 }
1296 
1297 void SafePointNode::pop_monitor() {
1298   // Delete last monitor from debug info
1299   debug_only(int num_before_pop = jvms()->nof_monitors());
1300   const int MonitorEdges = 2;
1301   assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
1302   int scloff = jvms()->scloff();
1303   int endoff = jvms()->endoff();
1304   int new_scloff = scloff - MonitorEdges;
1305   int new_endoff = endoff - MonitorEdges;
1306   jvms()->set_scloff(new_scloff);
1307   jvms()->set_endoff(new_endoff);
1308   while (scloff > new_scloff)  del_req_ordered(--scloff);
1309   assert(jvms()->nof_monitors() == num_before_pop-1, "");
1310 }
1311 
1312 Node *SafePointNode::peek_monitor_box() const {
1313   int mon = jvms()->nof_monitors() - 1;
1314   assert(mon >= 0, "must have a monitor");
1315   return monitor_box(jvms(), mon);
1316 }
1317 
1318 Node *SafePointNode::peek_monitor_obj() const {
1319   int mon = jvms()->nof_monitors() - 1;
1320   assert(mon >= 0, "must have a monitor");
1321   return monitor_obj(jvms(), mon);
1322 }
1323 
1324 // Do we Match on this edge index or not?  Match no edges
1325 uint SafePointNode::match_edge(uint idx) const {
1326   if( !needs_polling_address_input() )
1327     return 0;
1328 
1329   return (TypeFunc::Parms == idx);
1330 }
1331 
1332 //==============  SafePointScalarObjectNode  ==============
1333 
1334 SafePointScalarObjectNode::SafePointScalarObjectNode(const TypeOopPtr* tp,
1335 #ifdef ASSERT
1336                                                      AllocateNode* alloc,
1337 #endif
1338                                                      uint first_index,
1339                                                      uint n_fields) :
1340   TypeNode(tp, 1), // 1 control input -- seems required.  Get from root.
1341 #ifdef ASSERT
1342   _alloc(alloc),
1343 #endif
1344   _first_index(first_index),
1345   _n_fields(n_fields)
1346 {
1347   init_class_id(Class_SafePointScalarObject);
1348 }
1349 
1350 // Do not allow value-numbering for SafePointScalarObject node.
1351 uint SafePointScalarObjectNode::hash() const { return NO_HASH; }
1352 uint SafePointScalarObjectNode::cmp( const Node &n ) const {
1353   return (&n == this); // Always fail except on self
1354 }
1355 
1356 uint SafePointScalarObjectNode::ideal_reg() const {
1357   return 0; // No matching to machine instruction
1358 }
1359 
1360 const RegMask &SafePointScalarObjectNode::in_RegMask(uint idx) const {
1361   return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
1362 }
1363 
1364 const RegMask &SafePointScalarObjectNode::out_RegMask() const {
1365   return RegMask::Empty;
1366 }
1367 
1368 uint SafePointScalarObjectNode::match_edge(uint idx) const {
1369   return 0;
1370 }
1371 
1372 SafePointScalarObjectNode*
1373 SafePointScalarObjectNode::clone(Dict* sosn_map) const {
1374   void* cached = (*sosn_map)[(void*)this];
1375   if (cached != NULL) {
1376     return (SafePointScalarObjectNode*)cached;
1377   }
1378   SafePointScalarObjectNode* res = (SafePointScalarObjectNode*)Node::clone();
1379   sosn_map->Insert((void*)this, (void*)res);
1380   return res;
1381 }
1382 
1383 
1384 #ifndef PRODUCT
1385 void SafePointScalarObjectNode::dump_spec(outputStream *st) const {
1386   st->print(" # fields@[%d..%d]", first_index(),
1387              first_index() + n_fields() - 1);
1388 }
1389 
1390 #endif
1391 
1392 //=============================================================================
1393 uint AllocateNode::size_of() const { return sizeof(*this); }
1394 
1395 AllocateNode::AllocateNode(Compile* C, const TypeFunc *atype,
1396                            Node *ctrl, Node *mem, Node *abio,
1397                            Node *size, Node *klass_node,
1398                            Node* initial_test, ValueTypeNode* value_node)
1399   : CallNode(atype, NULL, TypeRawPtr::BOTTOM)
1400 {
1401   init_class_id(Class_Allocate);
1402   init_flags(Flag_is_macro);
1403   _is_scalar_replaceable = false;
1404   _is_non_escaping = false;
1405   _is_allocation_MemBar_redundant = false;
1406   Node *topnode = C->top();
1407 
1408   init_req( TypeFunc::Control  , ctrl );
1409   init_req( TypeFunc::I_O      , abio );
1410   init_req( TypeFunc::Memory   , mem );
1411   init_req( TypeFunc::ReturnAdr, topnode );
1412   init_req( TypeFunc::FramePtr , topnode );
1413   init_req( AllocSize          , size);
1414   init_req( KlassNode          , klass_node);
1415   init_req( InitialTest        , initial_test);
1416   init_req( ALength            , topnode);
1417   init_req( ValueNode          , value_node);
1418   C->add_macro_node(this);
1419 }
1420 
1421 void AllocateNode::compute_MemBar_redundancy(ciMethod* initializer)
1422 {
1423   assert(initializer != NULL &&
1424          initializer->is_initializer() &&
1425          !initializer->is_static(),
1426              "unexpected initializer method");
1427   BCEscapeAnalyzer* analyzer = initializer->get_bcea();
1428   if (analyzer == NULL) {
1429     return;
1430   }
1431 
1432   // Allocation node is first parameter in its initializer
1433   if (analyzer->is_arg_stack(0) || analyzer->is_arg_local(0)) {
1434     _is_allocation_MemBar_redundant = true;
1435   }
1436 }
1437 
1438 //=============================================================================
1439 Node* AllocateArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1440   Node* res = SafePointNode::Ideal(phase, can_reshape);
1441   if (res != NULL) {
1442     return res;
1443   }
1444   // Don't bother trying to transform a dead node
1445   if (in(0) && in(0)->is_top())  return NULL;
1446 
1447   const Type* type = phase->type(Ideal_length());
1448   if (type->isa_int() && type->is_int()->_hi < 0) {
1449     if (can_reshape) {
1450       PhaseIterGVN *igvn = phase->is_IterGVN();
1451       // Unreachable fall through path (negative array length),
1452       // the allocation can only throw so disconnect it.
1453       Node* proj = proj_out(TypeFunc::Control);
1454       Node* catchproj = NULL;
1455       if (proj != NULL) {
1456         for (DUIterator_Fast imax, i = proj->fast_outs(imax); i < imax; i++) {
1457           Node *cn = proj->fast_out(i);
1458           if (cn->is_Catch()) {
1459             catchproj = cn->as_Multi()->proj_out(CatchProjNode::fall_through_index);
1460             break;
1461           }
1462         }
1463       }
1464       if (catchproj != NULL && catchproj->outcnt() > 0 &&
1465           (catchproj->outcnt() > 1 ||
1466            catchproj->unique_out()->Opcode() != Op_Halt)) {
1467         assert(catchproj->is_CatchProj(), "must be a CatchProjNode");
1468         Node* nproj = catchproj->clone();
1469         igvn->register_new_node_with_optimizer(nproj);
1470 
1471         Node *frame = new ParmNode( phase->C->start(), TypeFunc::FramePtr );
1472         frame = phase->transform(frame);
1473         // Halt & Catch Fire
1474         Node *halt = new HaltNode( nproj, frame );
1475         phase->C->root()->add_req(halt);
1476         phase->transform(halt);
1477 
1478         igvn->replace_node(catchproj, phase->C->top());
1479         return this;
1480       }
1481     } else {
1482       // Can't correct it during regular GVN so register for IGVN
1483       phase->C->record_for_igvn(this);
1484     }
1485   }
1486   return NULL;
1487 }
1488 
1489 // Retrieve the length from the AllocateArrayNode. Narrow the type with a
1490 // CastII, if appropriate.  If we are not allowed to create new nodes, and
1491 // a CastII is appropriate, return NULL.
1492 Node *AllocateArrayNode::make_ideal_length(const TypeOopPtr* oop_type, PhaseTransform *phase, bool allow_new_nodes) {
1493   Node *length = in(AllocateNode::ALength);
1494   assert(length != NULL, "length is not null");
1495 
1496   const TypeInt* length_type = phase->find_int_type(length);
1497   const TypeAryPtr* ary_type = oop_type->isa_aryptr();
1498 
1499   if (ary_type != NULL && length_type != NULL) {
1500     const TypeInt* narrow_length_type = ary_type->narrow_size_type(length_type);
1501     if (narrow_length_type != length_type) {
1502       // Assert one of:
1503       //   - the narrow_length is 0
1504       //   - the narrow_length is not wider than length
1505       assert(narrow_length_type == TypeInt::ZERO ||
1506              length_type->is_con() && narrow_length_type->is_con() &&
1507                 (narrow_length_type->_hi <= length_type->_lo) ||
1508              (narrow_length_type->_hi <= length_type->_hi &&
1509               narrow_length_type->_lo >= length_type->_lo),
1510              "narrow type must be narrower than length type");
1511 
1512       // Return NULL if new nodes are not allowed
1513       if (!allow_new_nodes) return NULL;
1514       // Create a cast which is control dependent on the initialization to
1515       // propagate the fact that the array length must be positive.
1516       length = new CastIINode(length, narrow_length_type);
1517       length->set_req(0, initialization()->proj_out(0));
1518     }
1519   }
1520 
1521   return length;
1522 }
1523 
1524 //=============================================================================
1525 uint LockNode::size_of() const { return sizeof(*this); }
1526 
1527 // Redundant lock elimination
1528 //
1529 // There are various patterns of locking where we release and
1530 // immediately reacquire a lock in a piece of code where no operations
1531 // occur in between that would be observable.  In those cases we can
1532 // skip releasing and reacquiring the lock without violating any
1533 // fairness requirements.  Doing this around a loop could cause a lock
1534 // to be held for a very long time so we concentrate on non-looping
1535 // control flow.  We also require that the operations are fully
1536 // redundant meaning that we don't introduce new lock operations on
1537 // some paths so to be able to eliminate it on others ala PRE.  This
1538 // would probably require some more extensive graph manipulation to
1539 // guarantee that the memory edges were all handled correctly.
1540 //
1541 // Assuming p is a simple predicate which can't trap in any way and s
1542 // is a synchronized method consider this code:
1543 //
1544 //   s();
1545 //   if (p)
1546 //     s();
1547 //   else
1548 //     s();
1549 //   s();
1550 //
1551 // 1. The unlocks of the first call to s can be eliminated if the
1552 // locks inside the then and else branches are eliminated.
1553 //
1554 // 2. The unlocks of the then and else branches can be eliminated if
1555 // the lock of the final call to s is eliminated.
1556 //
1557 // Either of these cases subsumes the simple case of sequential control flow
1558 //
1559 // Addtionally we can eliminate versions without the else case:
1560 //
1561 //   s();
1562 //   if (p)
1563 //     s();
1564 //   s();
1565 //
1566 // 3. In this case we eliminate the unlock of the first s, the lock
1567 // and unlock in the then case and the lock in the final s.
1568 //
1569 // Note also that in all these cases the then/else pieces don't have
1570 // to be trivial as long as they begin and end with synchronization
1571 // operations.
1572 //
1573 //   s();
1574 //   if (p)
1575 //     s();
1576 //     f();
1577 //     s();
1578 //   s();
1579 //
1580 // The code will work properly for this case, leaving in the unlock
1581 // before the call to f and the relock after it.
1582 //
1583 // A potentially interesting case which isn't handled here is when the
1584 // locking is partially redundant.
1585 //
1586 //   s();
1587 //   if (p)
1588 //     s();
1589 //
1590 // This could be eliminated putting unlocking on the else case and
1591 // eliminating the first unlock and the lock in the then side.
1592 // Alternatively the unlock could be moved out of the then side so it
1593 // was after the merge and the first unlock and second lock
1594 // eliminated.  This might require less manipulation of the memory
1595 // state to get correct.
1596 //
1597 // Additionally we might allow work between a unlock and lock before
1598 // giving up eliminating the locks.  The current code disallows any
1599 // conditional control flow between these operations.  A formulation
1600 // similar to partial redundancy elimination computing the
1601 // availability of unlocking and the anticipatability of locking at a
1602 // program point would allow detection of fully redundant locking with
1603 // some amount of work in between.  I'm not sure how often I really
1604 // think that would occur though.  Most of the cases I've seen
1605 // indicate it's likely non-trivial work would occur in between.
1606 // There may be other more complicated constructs where we could
1607 // eliminate locking but I haven't seen any others appear as hot or
1608 // interesting.
1609 //
1610 // Locking and unlocking have a canonical form in ideal that looks
1611 // roughly like this:
1612 //
1613 //              <obj>
1614 //                | \\------+
1615 //                |  \       \
1616 //                | BoxLock   \
1617 //                |  |   |     \
1618 //                |  |    \     \
1619 //                |  |   FastLock
1620 //                |  |   /
1621 //                |  |  /
1622 //                |  |  |
1623 //
1624 //               Lock
1625 //                |
1626 //            Proj #0
1627 //                |
1628 //            MembarAcquire
1629 //                |
1630 //            Proj #0
1631 //
1632 //            MembarRelease
1633 //                |
1634 //            Proj #0
1635 //                |
1636 //              Unlock
1637 //                |
1638 //            Proj #0
1639 //
1640 //
1641 // This code proceeds by processing Lock nodes during PhaseIterGVN
1642 // and searching back through its control for the proper code
1643 // patterns.  Once it finds a set of lock and unlock operations to
1644 // eliminate they are marked as eliminatable which causes the
1645 // expansion of the Lock and Unlock macro nodes to make the operation a NOP
1646 //
1647 //=============================================================================
1648 
1649 //
1650 // Utility function to skip over uninteresting control nodes.  Nodes skipped are:
1651 //   - copy regions.  (These may not have been optimized away yet.)
1652 //   - eliminated locking nodes
1653 //
1654 static Node *next_control(Node *ctrl) {
1655   if (ctrl == NULL)
1656     return NULL;
1657   while (1) {
1658     if (ctrl->is_Region()) {
1659       RegionNode *r = ctrl->as_Region();
1660       Node *n = r->is_copy();
1661       if (n == NULL)
1662         break;  // hit a region, return it
1663       else
1664         ctrl = n;
1665     } else if (ctrl->is_Proj()) {
1666       Node *in0 = ctrl->in(0);
1667       if (in0->is_AbstractLock() && in0->as_AbstractLock()->is_eliminated()) {
1668         ctrl = in0->in(0);
1669       } else {
1670         break;
1671       }
1672     } else {
1673       break; // found an interesting control
1674     }
1675   }
1676   return ctrl;
1677 }
1678 //
1679 // Given a control, see if it's the control projection of an Unlock which
1680 // operating on the same object as lock.
1681 //
1682 bool AbstractLockNode::find_matching_unlock(const Node* ctrl, LockNode* lock,
1683                                             GrowableArray<AbstractLockNode*> &lock_ops) {
1684   ProjNode *ctrl_proj = (ctrl->is_Proj()) ? ctrl->as_Proj() : NULL;
1685   if (ctrl_proj != NULL && ctrl_proj->_con == TypeFunc::Control) {
1686     Node *n = ctrl_proj->in(0);
1687     if (n != NULL && n->is_Unlock()) {
1688       UnlockNode *unlock = n->as_Unlock();
1689       if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&
1690           BoxLockNode::same_slot(lock->box_node(), unlock->box_node()) &&
1691           !unlock->is_eliminated()) {
1692         lock_ops.append(unlock);
1693         return true;
1694       }
1695     }
1696   }
1697   return false;
1698 }
1699 
1700 //
1701 // Find the lock matching an unlock.  Returns null if a safepoint
1702 // or complicated control is encountered first.
1703 LockNode *AbstractLockNode::find_matching_lock(UnlockNode* unlock) {
1704   LockNode *lock_result = NULL;
1705   // find the matching lock, or an intervening safepoint
1706   Node *ctrl = next_control(unlock->in(0));
1707   while (1) {
1708     assert(ctrl != NULL, "invalid control graph");
1709     assert(!ctrl->is_Start(), "missing lock for unlock");
1710     if (ctrl->is_top()) break;  // dead control path
1711     if (ctrl->is_Proj()) ctrl = ctrl->in(0);
1712     if (ctrl->is_SafePoint()) {
1713         break;  // found a safepoint (may be the lock we are searching for)
1714     } else if (ctrl->is_Region()) {
1715       // Check for a simple diamond pattern.  Punt on anything more complicated
1716       if (ctrl->req() == 3 && ctrl->in(1) != NULL && ctrl->in(2) != NULL) {
1717         Node *in1 = next_control(ctrl->in(1));
1718         Node *in2 = next_control(ctrl->in(2));
1719         if (((in1->is_IfTrue() && in2->is_IfFalse()) ||
1720              (in2->is_IfTrue() && in1->is_IfFalse())) && (in1->in(0) == in2->in(0))) {
1721           ctrl = next_control(in1->in(0)->in(0));
1722         } else {
1723           break;
1724         }
1725       } else {
1726         break;
1727       }
1728     } else {
1729       ctrl = next_control(ctrl->in(0));  // keep searching
1730     }
1731   }
1732   if (ctrl->is_Lock()) {
1733     LockNode *lock = ctrl->as_Lock();
1734     if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&
1735         BoxLockNode::same_slot(lock->box_node(), unlock->box_node())) {
1736       lock_result = lock;
1737     }
1738   }
1739   return lock_result;
1740 }
1741 
1742 // This code corresponds to case 3 above.
1743 
1744 bool AbstractLockNode::find_lock_and_unlock_through_if(Node* node, LockNode* lock,
1745                                                        GrowableArray<AbstractLockNode*> &lock_ops) {
1746   Node* if_node = node->in(0);
1747   bool  if_true = node->is_IfTrue();
1748 
1749   if (if_node->is_If() && if_node->outcnt() == 2 && (if_true || node->is_IfFalse())) {
1750     Node *lock_ctrl = next_control(if_node->in(0));
1751     if (find_matching_unlock(lock_ctrl, lock, lock_ops)) {
1752       Node* lock1_node = NULL;
1753       ProjNode* proj = if_node->as_If()->proj_out(!if_true);
1754       if (if_true) {
1755         if (proj->is_IfFalse() && proj->outcnt() == 1) {
1756           lock1_node = proj->unique_out();
1757         }
1758       } else {
1759         if (proj->is_IfTrue() && proj->outcnt() == 1) {
1760           lock1_node = proj->unique_out();
1761         }
1762       }
1763       if (lock1_node != NULL && lock1_node->is_Lock()) {
1764         LockNode *lock1 = lock1_node->as_Lock();
1765         if (lock->obj_node()->eqv_uncast(lock1->obj_node()) &&
1766             BoxLockNode::same_slot(lock->box_node(), lock1->box_node()) &&
1767             !lock1->is_eliminated()) {
1768           lock_ops.append(lock1);
1769           return true;
1770         }
1771       }
1772     }
1773   }
1774 
1775   lock_ops.trunc_to(0);
1776   return false;
1777 }
1778 
1779 bool AbstractLockNode::find_unlocks_for_region(const RegionNode* region, LockNode* lock,
1780                                GrowableArray<AbstractLockNode*> &lock_ops) {
1781   // check each control merging at this point for a matching unlock.
1782   // in(0) should be self edge so skip it.
1783   for (int i = 1; i < (int)region->req(); i++) {
1784     Node *in_node = next_control(region->in(i));
1785     if (in_node != NULL) {
1786       if (find_matching_unlock(in_node, lock, lock_ops)) {
1787         // found a match so keep on checking.
1788         continue;
1789       } else if (find_lock_and_unlock_through_if(in_node, lock, lock_ops)) {
1790         continue;
1791       }
1792 
1793       // If we fall through to here then it was some kind of node we
1794       // don't understand or there wasn't a matching unlock, so give
1795       // up trying to merge locks.
1796       lock_ops.trunc_to(0);
1797       return false;
1798     }
1799   }
1800   return true;
1801 
1802 }
1803 
1804 #ifndef PRODUCT
1805 //
1806 // Create a counter which counts the number of times this lock is acquired
1807 //
1808 void AbstractLockNode::create_lock_counter(JVMState* state) {
1809   _counter = OptoRuntime::new_named_counter(state, NamedCounter::LockCounter);
1810 }
1811 
1812 void AbstractLockNode::set_eliminated_lock_counter() {
1813   if (_counter) {
1814     // Update the counter to indicate that this lock was eliminated.
1815     // The counter update code will stay around even though the
1816     // optimizer will eliminate the lock operation itself.
1817     _counter->set_tag(NamedCounter::EliminatedLockCounter);
1818   }
1819 }
1820 
1821 const char* AbstractLockNode::_kind_names[] = {"Regular", "NonEscObj", "Coarsened", "Nested"};
1822 
1823 void AbstractLockNode::dump_spec(outputStream* st) const {
1824   st->print("%s ", _kind_names[_kind]);
1825   CallNode::dump_spec(st);
1826 }
1827 
1828 void AbstractLockNode::dump_compact_spec(outputStream* st) const {
1829   st->print("%s", _kind_names[_kind]);
1830 }
1831 
1832 // The related set of lock nodes includes the control boundary.
1833 void AbstractLockNode::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
1834   if (compact) {
1835       this->collect_nodes(in_rel, 1, false, false);
1836     } else {
1837       this->collect_nodes_in_all_data(in_rel, true);
1838     }
1839     this->collect_nodes(out_rel, -2, false, false);
1840 }
1841 #endif
1842 
1843 //=============================================================================
1844 Node *LockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1845 
1846   // perform any generic optimizations first (returns 'this' or NULL)
1847   Node *result = SafePointNode::Ideal(phase, can_reshape);
1848   if (result != NULL)  return result;
1849   // Don't bother trying to transform a dead node
1850   if (in(0) && in(0)->is_top())  return NULL;
1851 
1852   // Now see if we can optimize away this lock.  We don't actually
1853   // remove the locking here, we simply set the _eliminate flag which
1854   // prevents macro expansion from expanding the lock.  Since we don't
1855   // modify the graph, the value returned from this function is the
1856   // one computed above.
1857   if (can_reshape && EliminateLocks && !is_non_esc_obj()) {
1858     //
1859     // If we are locking an unescaped object, the lock/unlock is unnecessary
1860     //
1861     ConnectionGraph *cgr = phase->C->congraph();
1862     if (cgr != NULL && cgr->not_global_escape(obj_node())) {
1863       assert(!is_eliminated() || is_coarsened(), "sanity");
1864       // The lock could be marked eliminated by lock coarsening
1865       // code during first IGVN before EA. Replace coarsened flag
1866       // to eliminate all associated locks/unlocks.
1867 #ifdef ASSERT
1868       this->log_lock_optimization(phase->C,"eliminate_lock_set_non_esc1");
1869 #endif
1870       this->set_non_esc_obj();
1871       return result;
1872     }
1873 
1874     //
1875     // Try lock coarsening
1876     //
1877     PhaseIterGVN* iter = phase->is_IterGVN();
1878     if (iter != NULL && !is_eliminated()) {
1879 
1880       GrowableArray<AbstractLockNode*>   lock_ops;
1881 
1882       Node *ctrl = next_control(in(0));
1883 
1884       // now search back for a matching Unlock
1885       if (find_matching_unlock(ctrl, this, lock_ops)) {
1886         // found an unlock directly preceding this lock.  This is the
1887         // case of single unlock directly control dependent on a
1888         // single lock which is the trivial version of case 1 or 2.
1889       } else if (ctrl->is_Region() ) {
1890         if (find_unlocks_for_region(ctrl->as_Region(), this, lock_ops)) {
1891         // found lock preceded by multiple unlocks along all paths
1892         // joining at this point which is case 3 in description above.
1893         }
1894       } else {
1895         // see if this lock comes from either half of an if and the
1896         // predecessors merges unlocks and the other half of the if
1897         // performs a lock.
1898         if (find_lock_and_unlock_through_if(ctrl, this, lock_ops)) {
1899           // found unlock splitting to an if with locks on both branches.
1900         }
1901       }
1902 
1903       if (lock_ops.length() > 0) {
1904         // add ourselves to the list of locks to be eliminated.
1905         lock_ops.append(this);
1906 
1907   #ifndef PRODUCT
1908         if (PrintEliminateLocks) {
1909           int locks = 0;
1910           int unlocks = 0;
1911           for (int i = 0; i < lock_ops.length(); i++) {
1912             AbstractLockNode* lock = lock_ops.at(i);
1913             if (lock->Opcode() == Op_Lock)
1914               locks++;
1915             else
1916               unlocks++;
1917             if (Verbose) {
1918               lock->dump(1);
1919             }
1920           }
1921           tty->print_cr("***Eliminated %d unlocks and %d locks", unlocks, locks);
1922         }
1923   #endif
1924 
1925         // for each of the identified locks, mark them
1926         // as eliminatable
1927         for (int i = 0; i < lock_ops.length(); i++) {
1928           AbstractLockNode* lock = lock_ops.at(i);
1929 
1930           // Mark it eliminated by coarsening and update any counters
1931 #ifdef ASSERT
1932           lock->log_lock_optimization(phase->C, "eliminate_lock_set_coarsened");
1933 #endif
1934           lock->set_coarsened();
1935         }
1936       } else if (ctrl->is_Region() &&
1937                  iter->_worklist.member(ctrl)) {
1938         // We weren't able to find any opportunities but the region this
1939         // lock is control dependent on hasn't been processed yet so put
1940         // this lock back on the worklist so we can check again once any
1941         // region simplification has occurred.
1942         iter->_worklist.push(this);
1943       }
1944     }
1945   }
1946 
1947   return result;
1948 }
1949 
1950 //=============================================================================
1951 bool LockNode::is_nested_lock_region() {
1952   return is_nested_lock_region(NULL);
1953 }
1954 
1955 // p is used for access to compilation log; no logging if NULL
1956 bool LockNode::is_nested_lock_region(Compile * c) {
1957   BoxLockNode* box = box_node()->as_BoxLock();
1958   int stk_slot = box->stack_slot();
1959   if (stk_slot <= 0) {
1960 #ifdef ASSERT
1961     this->log_lock_optimization(c, "eliminate_lock_INLR_1");
1962 #endif
1963     return false; // External lock or it is not Box (Phi node).
1964   }
1965 
1966   // Ignore complex cases: merged locks or multiple locks.
1967   Node* obj = obj_node();
1968   LockNode* unique_lock = NULL;
1969   if (!box->is_simple_lock_region(&unique_lock, obj)) {
1970 #ifdef ASSERT
1971     this->log_lock_optimization(c, "eliminate_lock_INLR_2a");
1972 #endif
1973     return false;
1974   }
1975   if (unique_lock != this) {
1976 #ifdef ASSERT
1977     this->log_lock_optimization(c, "eliminate_lock_INLR_2b");
1978 #endif
1979     return false;
1980   }
1981 
1982   // Look for external lock for the same object.
1983   SafePointNode* sfn = this->as_SafePoint();
1984   JVMState* youngest_jvms = sfn->jvms();
1985   int max_depth = youngest_jvms->depth();
1986   for (int depth = 1; depth <= max_depth; depth++) {
1987     JVMState* jvms = youngest_jvms->of_depth(depth);
1988     int num_mon  = jvms->nof_monitors();
1989     // Loop over monitors
1990     for (int idx = 0; idx < num_mon; idx++) {
1991       Node* obj_node = sfn->monitor_obj(jvms, idx);
1992       BoxLockNode* box_node = sfn->monitor_box(jvms, idx)->as_BoxLock();
1993       if ((box_node->stack_slot() < stk_slot) && obj_node->eqv_uncast(obj)) {
1994         return true;
1995       }
1996     }
1997   }
1998 #ifdef ASSERT
1999   this->log_lock_optimization(c, "eliminate_lock_INLR_3");
2000 #endif
2001   return false;
2002 }
2003 
2004 //=============================================================================
2005 uint UnlockNode::size_of() const { return sizeof(*this); }
2006 
2007 //=============================================================================
2008 Node *UnlockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2009 
2010   // perform any generic optimizations first (returns 'this' or NULL)
2011   Node *result = SafePointNode::Ideal(phase, can_reshape);
2012   if (result != NULL)  return result;
2013   // Don't bother trying to transform a dead node
2014   if (in(0) && in(0)->is_top())  return NULL;
2015 
2016   // Now see if we can optimize away this unlock.  We don't actually
2017   // remove the unlocking here, we simply set the _eliminate flag which
2018   // prevents macro expansion from expanding the unlock.  Since we don't
2019   // modify the graph, the value returned from this function is the
2020   // one computed above.
2021   // Escape state is defined after Parse phase.
2022   if (can_reshape && EliminateLocks && !is_non_esc_obj()) {
2023     //
2024     // If we are unlocking an unescaped object, the lock/unlock is unnecessary.
2025     //
2026     ConnectionGraph *cgr = phase->C->congraph();
2027     if (cgr != NULL && cgr->not_global_escape(obj_node())) {
2028       assert(!is_eliminated() || is_coarsened(), "sanity");
2029       // The lock could be marked eliminated by lock coarsening
2030       // code during first IGVN before EA. Replace coarsened flag
2031       // to eliminate all associated locks/unlocks.
2032 #ifdef ASSERT
2033       this->log_lock_optimization(phase->C, "eliminate_lock_set_non_esc2");
2034 #endif
2035       this->set_non_esc_obj();
2036     }
2037   }
2038   return result;
2039 }
2040 
2041 const char * AbstractLockNode::kind_as_string() const {
2042   return is_coarsened()   ? "coarsened" :
2043          is_nested()      ? "nested" :
2044          is_non_esc_obj() ? "non_escaping" :
2045          "?";
2046 }
2047 
2048 void AbstractLockNode::log_lock_optimization(Compile *C, const char * tag)  const {
2049   if (C == NULL) {
2050     return;
2051   }
2052   CompileLog* log = C->log();
2053   if (log != NULL) {
2054     log->begin_head("%s lock='%d' compile_id='%d' class_id='%s' kind='%s'",
2055           tag, is_Lock(), C->compile_id(),
2056           is_Unlock() ? "unlock" : is_Lock() ? "lock" : "?",
2057           kind_as_string());
2058     log->stamp();
2059     log->end_head();
2060     JVMState* p = is_Unlock() ? (as_Unlock()->dbg_jvms()) : jvms();
2061     while (p != NULL) {
2062       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
2063       p = p->caller();
2064     }
2065     log->tail(tag);
2066   }
2067 }
2068 
2069 bool CallNode::may_modify_arraycopy_helper(const TypeOopPtr* dest_t, const TypeOopPtr *t_oop, PhaseTransform *phase) {
2070   if (dest_t->is_known_instance() && t_oop->is_known_instance()) {
2071     return dest_t->instance_id() == t_oop->instance_id();
2072   }
2073 
2074   if (dest_t->isa_instptr() && !dest_t->klass()->equals(phase->C->env()->Object_klass())) {
2075     // clone
2076     if (t_oop->isa_aryptr()) {
2077       return false;
2078     }
2079     if (!t_oop->isa_instptr()) {
2080       return true;
2081     }
2082     if (dest_t->klass()->is_subtype_of(t_oop->klass()) || t_oop->klass()->is_subtype_of(dest_t->klass())) {
2083       return true;
2084     }
2085     // unrelated
2086     return false;
2087   }
2088 
2089   if (dest_t->isa_aryptr()) {
2090     // arraycopy or array clone
2091     if (t_oop->isa_instptr()) {
2092       return false;
2093     }
2094     if (!t_oop->isa_aryptr()) {
2095       return true;
2096     }
2097 
2098     const Type* elem = dest_t->is_aryptr()->elem();
2099     if (elem == Type::BOTTOM) {
2100       // An array but we don't know what elements are
2101       return true;
2102     }
2103 
2104     dest_t = dest_t->add_offset(Type::OffsetBot)->is_oopptr();
2105     uint dest_alias = phase->C->get_alias_index(dest_t);
2106     uint t_oop_alias = phase->C->get_alias_index(t_oop);
2107 
2108     return dest_alias == t_oop_alias;
2109   }
2110 
2111   return true;
2112 }
2113