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 (!in(0) || phase->type(in(0)) == Type::TOP) {
 694     return Type::TOP;
 695   }
 696   return tf()->range_cc();
 697 }
 698 
 699 //------------------------------calling_convention-----------------------------
 700 void CallNode::calling_convention(BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt) const {
 701   if (_entry_point == StubRoutines::store_value_type_fields_to_buf()) {
 702     // The call to that stub is a special case: its inputs are
 703     // multiple values returned from a call and so it should follow
 704     // the return convention.
 705     SharedRuntime::java_return_convention(sig_bt, parm_regs, argcnt);
 706     return;
 707   }
 708   // Use the standard compiler calling convention
 709   Matcher::calling_convention( sig_bt, parm_regs, argcnt, true );
 710 }
 711 
 712 
 713 //------------------------------match------------------------------------------
 714 // Construct projections for control, I/O, memory-fields, ..., and
 715 // return result(s) along with their RegMask info
 716 Node *CallNode::match(const ProjNode *proj, const Matcher *match, const RegMask* mask) {
 717   uint con = proj->_con;
 718   const TypeTuple *range_cc = tf()->range_cc();
 719   if (con >= TypeFunc::Parms) {
 720     if (is_CallRuntime()) {
 721       if (con == TypeFunc::Parms) {
 722         uint ideal_reg = range_cc->field_at(TypeFunc::Parms)->ideal_reg();
 723         OptoRegPair regs = match->c_return_value(ideal_reg,true);
 724         RegMask rm = RegMask(regs.first());
 725         if (OptoReg::is_valid(regs.second())) {
 726           rm.Insert(regs.second());
 727         }
 728         return new MachProjNode(this,con,rm,ideal_reg);
 729       } else {
 730         assert(con == TypeFunc::Parms+1, "only one return value");
 731         assert(range_cc->field_at(TypeFunc::Parms+1) == Type::HALF, "");
 732         return new MachProjNode(this,con, RegMask::Empty, (uint)OptoReg::Bad);
 733       }
 734     } else {
 735       // The Call may return multiple values (value type fields): we
 736       // create one projection per returned values.
 737       assert(con <= TypeFunc::Parms+1 || ValueTypeReturnedAsFields, "only for multi value return");
 738       uint ideal_reg = range_cc->field_at(con)->ideal_reg();
 739       return new MachProjNode(this, con, mask[con-TypeFunc::Parms], ideal_reg);
 740     }
 741   }
 742 
 743   switch (con) {
 744   case TypeFunc::Control:
 745   case TypeFunc::I_O:
 746   case TypeFunc::Memory:
 747     return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
 748 
 749   case TypeFunc::ReturnAdr:
 750   case TypeFunc::FramePtr:
 751   default:
 752     ShouldNotReachHere();
 753   }
 754   return NULL;
 755 }
 756 
 757 // Do we Match on this edge index or not?  Match no edges
 758 uint CallNode::match_edge(uint idx) const {
 759   return 0;
 760 }
 761 
 762 //
 763 // Determine whether the call could modify the field of the specified
 764 // instance at the specified offset.
 765 //
 766 bool CallNode::may_modify(const TypeOopPtr *t_oop, PhaseTransform *phase) {
 767   assert((t_oop != NULL), "sanity");
 768   if (is_call_to_arraycopystub() && strcmp(_name, "unsafe_arraycopy") != 0) {
 769     const TypeTuple* args = _tf->domain_sig();
 770     Node* dest = NULL;
 771     // Stubs that can be called once an ArrayCopyNode is expanded have
 772     // different signatures. Look for the second pointer argument,
 773     // that is the destination of the copy.
 774     for (uint i = TypeFunc::Parms, j = 0; i < args->cnt(); i++) {
 775       if (args->field_at(i)->isa_ptr()) {
 776         j++;
 777         if (j == 2) {
 778           dest = in(i);
 779           break;
 780         }
 781       }
 782     }
 783     if (!dest->is_top() && may_modify_arraycopy_helper(phase->type(dest)->is_oopptr(), t_oop, phase)) {
 784       return true;
 785     }
 786     return false;
 787   }
 788   if (t_oop->is_known_instance()) {
 789     // The instance_id is set only for scalar-replaceable allocations which
 790     // are not passed as arguments according to Escape Analysis.
 791     return false;
 792   }
 793   if (t_oop->is_ptr_to_boxed_value()) {
 794     ciKlass* boxing_klass = t_oop->klass();
 795     if (is_CallStaticJava() && as_CallStaticJava()->is_boxing_method()) {
 796       // Skip unrelated boxing methods.
 797       Node* proj = proj_out(TypeFunc::Parms);
 798       if ((proj == NULL) || (phase->type(proj)->is_instptr()->klass() != boxing_klass)) {
 799         return false;
 800       }
 801     }
 802     if (is_CallJava() && as_CallJava()->method() != NULL) {
 803       ciMethod* meth = as_CallJava()->method();
 804       if (meth->is_getter()) {
 805         return false;
 806       }
 807       // May modify (by reflection) if an boxing object is passed
 808       // as argument or returned.
 809       Node* proj = returns_pointer() ? proj_out(TypeFunc::Parms) : NULL;
 810       if (proj != NULL) {
 811         const TypeInstPtr* inst_t = phase->type(proj)->isa_instptr();
 812         if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||
 813                                  (inst_t->klass() == boxing_klass))) {
 814           return true;
 815         }
 816       }
 817       const TypeTuple* d = tf()->domain_cc();
 818       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
 819         const TypeInstPtr* inst_t = d->field_at(i)->isa_instptr();
 820         if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||
 821                                  (inst_t->klass() == boxing_klass))) {
 822           return true;
 823         }
 824       }
 825       return false;
 826     }
 827   }
 828   return true;
 829 }
 830 
 831 // Does this call have a direct reference to n other than debug information?
 832 bool CallNode::has_non_debug_use(Node *n) {
 833   const TypeTuple * d = tf()->domain_cc();
 834   for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
 835     Node *arg = in(i);
 836     if (arg == n) {
 837       return true;
 838     }
 839   }
 840   return false;
 841 }
 842 
 843 bool CallNode::has_debug_use(Node *n) {
 844   for (uint i = jvms()->debug_start(); i < jvms()->debug_end(); i++) {
 845     Node *arg = in(i);
 846     if (arg == n) {
 847       return true;
 848     }
 849   }
 850   return false;
 851 }
 852 
 853 // Returns the unique CheckCastPP of a call
 854 // or 'this' if there are several CheckCastPP or unexpected uses
 855 // or returns NULL if there is no one.
 856 Node *CallNode::result_cast() {
 857   Node *cast = NULL;
 858 
 859   Node *p = proj_out(TypeFunc::Parms);
 860   if (p == NULL)
 861     return NULL;
 862 
 863   for (DUIterator_Fast imax, i = p->fast_outs(imax); i < imax; i++) {
 864     Node *use = p->fast_out(i);
 865     if (use->is_CheckCastPP()) {
 866       if (cast != NULL) {
 867         return this;  // more than 1 CheckCastPP
 868       }
 869       cast = use;
 870     } else if (!use->is_Initialize() &&
 871                !use->is_AddP() &&
 872                use->Opcode() != Op_MemBarStoreStore) {
 873       // Expected uses are restricted to a CheckCastPP, an Initialize
 874       // node, a MemBarStoreStore (clone) and AddP nodes. If we
 875       // encounter any other use (a Phi node can be seen in rare
 876       // cases) return this to prevent incorrect optimizations.
 877       return this;
 878     }
 879   }
 880   return cast;
 881 }
 882 
 883 
 884 void CallNode::extract_projections(CallProjections* projs, bool separate_io_proj, bool do_asserts) {
 885   projs->fallthrough_proj      = NULL;
 886   projs->fallthrough_catchproj = NULL;
 887   projs->fallthrough_ioproj    = NULL;
 888   projs->catchall_ioproj       = NULL;
 889   projs->catchall_catchproj    = NULL;
 890   projs->fallthrough_memproj   = NULL;
 891   projs->catchall_memproj      = NULL;
 892   projs->resproj               = NULL;
 893   projs->exobj                 = NULL;
 894 
 895   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
 896     ProjNode *pn = fast_out(i)->as_Proj();
 897     if (pn->outcnt() == 0) continue;
 898     switch (pn->_con) {
 899     case TypeFunc::Control:
 900       {
 901         // For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj
 902         projs->fallthrough_proj = pn;
 903         DUIterator_Fast jmax, j = pn->fast_outs(jmax);
 904         const Node *cn = pn->fast_out(j);
 905         if (cn->is_Catch()) {
 906           ProjNode *cpn = NULL;
 907           for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) {
 908             cpn = cn->fast_out(k)->as_Proj();
 909             assert(cpn->is_CatchProj(), "must be a CatchProjNode");
 910             if (cpn->_con == CatchProjNode::fall_through_index)
 911               projs->fallthrough_catchproj = cpn;
 912             else {
 913               assert(cpn->_con == CatchProjNode::catch_all_index, "must be correct index.");
 914               projs->catchall_catchproj = cpn;
 915             }
 916           }
 917         }
 918         break;
 919       }
 920     case TypeFunc::I_O:
 921       if (pn->_is_io_use)
 922         projs->catchall_ioproj = pn;
 923       else
 924         projs->fallthrough_ioproj = pn;
 925       for (DUIterator j = pn->outs(); pn->has_out(j); j++) {
 926         Node* e = pn->out(j);
 927         if (e->Opcode() == Op_CreateEx && e->in(0)->is_CatchProj() && e->outcnt() > 0) {
 928           assert(projs->exobj == NULL, "only one");
 929           projs->exobj = e;
 930         }
 931       }
 932       break;
 933     case TypeFunc::Memory:
 934       if (pn->_is_io_use)
 935         projs->catchall_memproj = pn;
 936       else
 937         projs->fallthrough_memproj = pn;
 938       break;
 939     case TypeFunc::Parms:
 940       projs->resproj = pn;
 941       break;
 942     default:
 943       assert(false, "unexpected projection from allocation node.");
 944     }
 945   }
 946 
 947   // The resproj may not exist because the result could be ignored
 948   // and the exception object may not exist if an exception handler
 949   // swallows the exception but all the other must exist and be found.
 950   assert(projs->fallthrough_proj      != NULL, "must be found");
 951   do_asserts = do_asserts && !Compile::current()->inlining_incrementally();
 952   assert(!do_asserts || projs->fallthrough_catchproj != NULL, "must be found");
 953   assert(!do_asserts || projs->fallthrough_memproj   != NULL, "must be found");
 954   assert(!do_asserts || projs->fallthrough_ioproj    != NULL, "must be found");
 955   assert(!do_asserts || projs->catchall_catchproj    != NULL, "must be found");
 956   if (separate_io_proj) {
 957     assert(!do_asserts || projs->catchall_memproj    != NULL, "must be found");
 958     assert(!do_asserts || projs->catchall_ioproj     != NULL, "must be found");
 959   }
 960 }
 961 
 962 Node *CallNode::Ideal(PhaseGVN *phase, bool can_reshape) {
 963   CallGenerator* cg = generator();
 964   if (can_reshape && cg != NULL && cg->is_mh_late_inline() && !cg->already_attempted()) {
 965     // Check whether this MH handle call becomes a candidate for inlining
 966     ciMethod* callee = cg->method();
 967     vmIntrinsics::ID iid = callee->intrinsic_id();
 968     if (iid == vmIntrinsics::_invokeBasic) {
 969       if (in(TypeFunc::Parms)->Opcode() == Op_ConP) {
 970         phase->C->prepend_late_inline(cg);
 971         set_generator(NULL);
 972       }
 973     } else {
 974       assert(callee->has_member_arg(), "wrong type of call?");
 975       if (in(TypeFunc::Parms + callee->arg_size() - 1)->Opcode() == Op_ConP) {
 976         phase->C->prepend_late_inline(cg);
 977         set_generator(NULL);
 978       }
 979     }
 980   }
 981   return SafePointNode::Ideal(phase, can_reshape);
 982 }
 983 
 984 bool CallNode::is_call_to_arraycopystub() const {
 985   if (_name != NULL && strstr(_name, "arraycopy") != 0) {
 986     return true;
 987   }
 988   return false;
 989 }
 990 
 991 //=============================================================================
 992 uint CallJavaNode::size_of() const { return sizeof(*this); }
 993 uint CallJavaNode::cmp( const Node &n ) const {
 994   CallJavaNode &call = (CallJavaNode&)n;
 995   return CallNode::cmp(call) && _method == call._method &&
 996          _override_symbolic_info == call._override_symbolic_info;
 997 }
 998 #ifndef PRODUCT
 999 void CallJavaNode::dump_spec(outputStream *st) const {
1000   if( _method ) _method->print_short_name(st);
1001   CallNode::dump_spec(st);
1002 }
1003 
1004 void CallJavaNode::dump_compact_spec(outputStream* st) const {
1005   if (_method) {
1006     _method->print_short_name(st);
1007   } else {
1008     st->print("<?>");
1009   }
1010 }
1011 #endif
1012 
1013 //=============================================================================
1014 uint CallStaticJavaNode::size_of() const { return sizeof(*this); }
1015 uint CallStaticJavaNode::cmp( const Node &n ) const {
1016   CallStaticJavaNode &call = (CallStaticJavaNode&)n;
1017   return CallJavaNode::cmp(call);
1018 }
1019 
1020 //----------------------------uncommon_trap_request----------------------------
1021 // If this is an uncommon trap, return the request code, else zero.
1022 int CallStaticJavaNode::uncommon_trap_request() const {
1023   if (_name != NULL && !strcmp(_name, "uncommon_trap")) {
1024     return extract_uncommon_trap_request(this);
1025   }
1026   return 0;
1027 }
1028 int CallStaticJavaNode::extract_uncommon_trap_request(const Node* call) {
1029 #ifndef PRODUCT
1030   if (!(call->req() > TypeFunc::Parms &&
1031         call->in(TypeFunc::Parms) != NULL &&
1032         call->in(TypeFunc::Parms)->is_Con() &&
1033         call->in(TypeFunc::Parms)->bottom_type()->isa_int())) {
1034     assert(in_dump() != 0, "OK if dumping");
1035     tty->print("[bad uncommon trap]");
1036     return 0;
1037   }
1038 #endif
1039   return call->in(TypeFunc::Parms)->bottom_type()->is_int()->get_con();
1040 }
1041 
1042 #ifndef PRODUCT
1043 void CallStaticJavaNode::dump_spec(outputStream *st) const {
1044   st->print("# Static ");
1045   if (_name != NULL) {
1046     st->print("%s", _name);
1047     int trap_req = uncommon_trap_request();
1048     if (trap_req != 0) {
1049       char buf[100];
1050       st->print("(%s)",
1051                  Deoptimization::format_trap_request(buf, sizeof(buf),
1052                                                      trap_req));
1053     }
1054     st->print(" ");
1055   }
1056   CallJavaNode::dump_spec(st);
1057 }
1058 
1059 void CallStaticJavaNode::dump_compact_spec(outputStream* st) const {
1060   if (_method) {
1061     _method->print_short_name(st);
1062   } else if (_name) {
1063     st->print("%s", _name);
1064   } else {
1065     st->print("<?>");
1066   }
1067 }
1068 #endif
1069 
1070 //=============================================================================
1071 uint CallDynamicJavaNode::size_of() const { return sizeof(*this); }
1072 uint CallDynamicJavaNode::cmp( const Node &n ) const {
1073   CallDynamicJavaNode &call = (CallDynamicJavaNode&)n;
1074   return CallJavaNode::cmp(call);
1075 }
1076 #ifndef PRODUCT
1077 void CallDynamicJavaNode::dump_spec(outputStream *st) const {
1078   st->print("# Dynamic ");
1079   CallJavaNode::dump_spec(st);
1080 }
1081 #endif
1082 
1083 //=============================================================================
1084 uint CallRuntimeNode::size_of() const { return sizeof(*this); }
1085 uint CallRuntimeNode::cmp( const Node &n ) const {
1086   CallRuntimeNode &call = (CallRuntimeNode&)n;
1087   return CallNode::cmp(call) && !strcmp(_name,call._name);
1088 }
1089 #ifndef PRODUCT
1090 void CallRuntimeNode::dump_spec(outputStream *st) const {
1091   st->print("# ");
1092   st->print("%s", _name);
1093   CallNode::dump_spec(st);
1094 }
1095 #endif
1096 
1097 //------------------------------calling_convention-----------------------------
1098 void CallRuntimeNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
1099   if (_entry_point == NULL) {
1100     // The call to that stub is a special case: its inputs are
1101     // multiple values returned from a call and so it should follow
1102     // the return convention.
1103     SharedRuntime::java_return_convention(sig_bt, parm_regs, argcnt);
1104     return;
1105   }
1106   Matcher::c_calling_convention( sig_bt, parm_regs, argcnt );
1107 }
1108 
1109 //=============================================================================
1110 //------------------------------calling_convention-----------------------------
1111 
1112 
1113 //=============================================================================
1114 #ifndef PRODUCT
1115 void CallLeafNode::dump_spec(outputStream *st) const {
1116   st->print("# ");
1117   st->print("%s", _name);
1118   CallNode::dump_spec(st);
1119 }
1120 #endif
1121 
1122 uint CallLeafNoFPNode::match_edge(uint idx) const {
1123   // Null entry point is a special case for which the target is in a
1124   // register. Need to match that edge.
1125   return entry_point() == NULL && idx == TypeFunc::Parms;
1126 }
1127 
1128 //=============================================================================
1129 
1130 void SafePointNode::set_local(JVMState* jvms, uint idx, Node *c) {
1131   assert(verify_jvms(jvms), "jvms must match");
1132   int loc = jvms->locoff() + idx;
1133   if (in(loc)->is_top() && idx > 0 && !c->is_top() ) {
1134     // If current local idx is top then local idx - 1 could
1135     // be a long/double that needs to be killed since top could
1136     // represent the 2nd half ofthe long/double.
1137     uint ideal = in(loc -1)->ideal_reg();
1138     if (ideal == Op_RegD || ideal == Op_RegL) {
1139       // set other (low index) half to top
1140       set_req(loc - 1, in(loc));
1141     }
1142   }
1143   set_req(loc, c);
1144 }
1145 
1146 uint SafePointNode::size_of() const { return sizeof(*this); }
1147 uint SafePointNode::cmp( const Node &n ) const {
1148   return (&n == this);          // Always fail except on self
1149 }
1150 
1151 //-------------------------set_next_exception----------------------------------
1152 void SafePointNode::set_next_exception(SafePointNode* n) {
1153   assert(n == NULL || n->Opcode() == Op_SafePoint, "correct value for next_exception");
1154   if (len() == req()) {
1155     if (n != NULL)  add_prec(n);
1156   } else {
1157     set_prec(req(), n);
1158   }
1159 }
1160 
1161 
1162 //----------------------------next_exception-----------------------------------
1163 SafePointNode* SafePointNode::next_exception() const {
1164   if (len() == req()) {
1165     return NULL;
1166   } else {
1167     Node* n = in(req());
1168     assert(n == NULL || n->Opcode() == Op_SafePoint, "no other uses of prec edges");
1169     return (SafePointNode*) n;
1170   }
1171 }
1172 
1173 
1174 //------------------------------Ideal------------------------------------------
1175 // Skip over any collapsed Regions
1176 Node *SafePointNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1177   if (remove_dead_region(phase, can_reshape)) {
1178     return this;
1179   }
1180   if (jvms() != NULL) {
1181     bool progress = false;
1182     // A ValueTypeNode that was already heap allocated in the debug
1183     // info?  Reference the object directly. Helps removal of useless
1184     // value type allocations with incremental inlining.
1185     for (uint i = jvms()->debug_start(); i < jvms()->debug_end(); i++) {
1186       Node *arg = in(i);
1187       if (arg->is_ValueType()) {
1188         ValueTypeNode* vt = arg->as_ValueType();
1189         Node* in_oop = vt->get_oop();
1190         const Type* oop_type = phase->type(in_oop);
1191         if (!TypePtr::NULL_PTR->higher_equal(oop_type)) {
1192           set_req(i, in_oop);
1193           progress = true;
1194         }
1195       }
1196     }
1197     if (progress) {
1198       return this;
1199     }
1200   }
1201   return NULL;
1202 }
1203 
1204 //------------------------------Identity---------------------------------------
1205 // Remove obviously duplicate safepoints
1206 Node* SafePointNode::Identity(PhaseGVN* phase) {
1207 
1208   // If you have back to back safepoints, remove one
1209   if( in(TypeFunc::Control)->is_SafePoint() )
1210     return in(TypeFunc::Control);
1211 
1212   if( in(0)->is_Proj() ) {
1213     Node *n0 = in(0)->in(0);
1214     // Check if he is a call projection (except Leaf Call)
1215     if( n0->is_Catch() ) {
1216       n0 = n0->in(0)->in(0);
1217       assert( n0->is_Call(), "expect a call here" );
1218     }
1219     if( n0->is_Call() && n0->as_Call()->guaranteed_safepoint() ) {
1220       // Useless Safepoint, so remove it
1221       return in(TypeFunc::Control);
1222     }
1223   }
1224 
1225   return this;
1226 }
1227 
1228 //------------------------------Value------------------------------------------
1229 const Type* SafePointNode::Value(PhaseGVN* phase) const {
1230   if( phase->type(in(0)) == Type::TOP ) return Type::TOP;
1231   if( phase->eqv( in(0), this ) ) return Type::TOP; // Dead infinite loop
1232   return Type::CONTROL;
1233 }
1234 
1235 #ifndef PRODUCT
1236 void SafePointNode::dump_spec(outputStream *st) const {
1237   st->print(" SafePoint ");
1238   _replaced_nodes.dump(st);
1239 }
1240 
1241 // The related nodes of a SafepointNode are all data inputs, excluding the
1242 // control boundary, as well as all outputs till level 2 (to include projection
1243 // nodes and targets). In compact mode, just include inputs till level 1 and
1244 // outputs as before.
1245 void SafePointNode::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
1246   if (compact) {
1247     this->collect_nodes(in_rel, 1, false, false);
1248   } else {
1249     this->collect_nodes_in_all_data(in_rel, false);
1250   }
1251   this->collect_nodes(out_rel, -2, false, false);
1252 }
1253 #endif
1254 
1255 const RegMask &SafePointNode::in_RegMask(uint idx) const {
1256   if( idx < TypeFunc::Parms ) return RegMask::Empty;
1257   // Values outside the domain represent debug info
1258   return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
1259 }
1260 const RegMask &SafePointNode::out_RegMask() const {
1261   return RegMask::Empty;
1262 }
1263 
1264 
1265 void SafePointNode::grow_stack(JVMState* jvms, uint grow_by) {
1266   assert((int)grow_by > 0, "sanity");
1267   int monoff = jvms->monoff();
1268   int scloff = jvms->scloff();
1269   int endoff = jvms->endoff();
1270   assert(endoff == (int)req(), "no other states or debug info after me");
1271   Node* top = Compile::current()->top();
1272   for (uint i = 0; i < grow_by; i++) {
1273     ins_req(monoff, top);
1274   }
1275   jvms->set_monoff(monoff + grow_by);
1276   jvms->set_scloff(scloff + grow_by);
1277   jvms->set_endoff(endoff + grow_by);
1278 }
1279 
1280 void SafePointNode::push_monitor(const FastLockNode *lock) {
1281   // Add a LockNode, which points to both the original BoxLockNode (the
1282   // stack space for the monitor) and the Object being locked.
1283   const int MonitorEdges = 2;
1284   assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
1285   assert(req() == jvms()->endoff(), "correct sizing");
1286   int nextmon = jvms()->scloff();
1287   if (GenerateSynchronizationCode) {
1288     ins_req(nextmon,   lock->box_node());
1289     ins_req(nextmon+1, lock->obj_node());
1290   } else {
1291     Node* top = Compile::current()->top();
1292     ins_req(nextmon, top);
1293     ins_req(nextmon, top);
1294   }
1295   jvms()->set_scloff(nextmon + MonitorEdges);
1296   jvms()->set_endoff(req());
1297 }
1298 
1299 void SafePointNode::pop_monitor() {
1300   // Delete last monitor from debug info
1301   debug_only(int num_before_pop = jvms()->nof_monitors());
1302   const int MonitorEdges = 2;
1303   assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
1304   int scloff = jvms()->scloff();
1305   int endoff = jvms()->endoff();
1306   int new_scloff = scloff - MonitorEdges;
1307   int new_endoff = endoff - MonitorEdges;
1308   jvms()->set_scloff(new_scloff);
1309   jvms()->set_endoff(new_endoff);
1310   while (scloff > new_scloff)  del_req_ordered(--scloff);
1311   assert(jvms()->nof_monitors() == num_before_pop-1, "");
1312 }
1313 
1314 Node *SafePointNode::peek_monitor_box() const {
1315   int mon = jvms()->nof_monitors() - 1;
1316   assert(mon >= 0, "must have a monitor");
1317   return monitor_box(jvms(), mon);
1318 }
1319 
1320 Node *SafePointNode::peek_monitor_obj() const {
1321   int mon = jvms()->nof_monitors() - 1;
1322   assert(mon >= 0, "must have a monitor");
1323   return monitor_obj(jvms(), mon);
1324 }
1325 
1326 // Do we Match on this edge index or not?  Match no edges
1327 uint SafePointNode::match_edge(uint idx) const {
1328   if( !needs_polling_address_input() )
1329     return 0;
1330 
1331   return (TypeFunc::Parms == idx);
1332 }
1333 
1334 //==============  SafePointScalarObjectNode  ==============
1335 
1336 SafePointScalarObjectNode::SafePointScalarObjectNode(const TypeOopPtr* tp,
1337 #ifdef ASSERT
1338                                                      AllocateNode* alloc,
1339 #endif
1340                                                      uint first_index,
1341                                                      uint n_fields) :
1342   TypeNode(tp, 1), // 1 control input -- seems required.  Get from root.
1343 #ifdef ASSERT
1344   _alloc(alloc),
1345 #endif
1346   _first_index(first_index),
1347   _n_fields(n_fields)
1348 {
1349   init_class_id(Class_SafePointScalarObject);
1350 }
1351 
1352 // Do not allow value-numbering for SafePointScalarObject node.
1353 uint SafePointScalarObjectNode::hash() const { return NO_HASH; }
1354 uint SafePointScalarObjectNode::cmp( const Node &n ) const {
1355   return (&n == this); // Always fail except on self
1356 }
1357 
1358 uint SafePointScalarObjectNode::ideal_reg() const {
1359   return 0; // No matching to machine instruction
1360 }
1361 
1362 const RegMask &SafePointScalarObjectNode::in_RegMask(uint idx) const {
1363   return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
1364 }
1365 
1366 const RegMask &SafePointScalarObjectNode::out_RegMask() const {
1367   return RegMask::Empty;
1368 }
1369 
1370 uint SafePointScalarObjectNode::match_edge(uint idx) const {
1371   return 0;
1372 }
1373 
1374 SafePointScalarObjectNode*
1375 SafePointScalarObjectNode::clone(Dict* sosn_map) const {
1376   void* cached = (*sosn_map)[(void*)this];
1377   if (cached != NULL) {
1378     return (SafePointScalarObjectNode*)cached;
1379   }
1380   SafePointScalarObjectNode* res = (SafePointScalarObjectNode*)Node::clone();
1381   sosn_map->Insert((void*)this, (void*)res);
1382   return res;
1383 }
1384 
1385 
1386 #ifndef PRODUCT
1387 void SafePointScalarObjectNode::dump_spec(outputStream *st) const {
1388   st->print(" # fields@[%d..%d]", first_index(),
1389              first_index() + n_fields() - 1);
1390 }
1391 
1392 #endif
1393 
1394 //=============================================================================
1395 uint AllocateNode::size_of() const { return sizeof(*this); }
1396 
1397 AllocateNode::AllocateNode(Compile* C, const TypeFunc *atype,
1398                            Node *ctrl, Node *mem, Node *abio,
1399                            Node *size, Node *klass_node,
1400                            Node* initial_test, ValueTypeBaseNode* value_node)
1401   : CallNode(atype, NULL, TypeRawPtr::BOTTOM)
1402 {
1403   init_class_id(Class_Allocate);
1404   init_flags(Flag_is_macro);
1405   _is_scalar_replaceable = false;
1406   _is_non_escaping = false;
1407   _is_allocation_MemBar_redundant = false;
1408   Node *topnode = C->top();
1409 
1410   init_req( TypeFunc::Control  , ctrl );
1411   init_req( TypeFunc::I_O      , abio );
1412   init_req( TypeFunc::Memory   , mem );
1413   init_req( TypeFunc::ReturnAdr, topnode );
1414   init_req( TypeFunc::FramePtr , topnode );
1415   init_req( AllocSize          , size);
1416   init_req( KlassNode          , klass_node);
1417   init_req( InitialTest        , initial_test);
1418   init_req( ALength            , topnode);
1419   init_req( ValueNode          , value_node);
1420   C->add_macro_node(this);
1421 }
1422 
1423 void AllocateNode::compute_MemBar_redundancy(ciMethod* initializer)
1424 {
1425   assert(initializer != NULL &&
1426          initializer->is_initializer() &&
1427          !initializer->is_static(),
1428              "unexpected initializer method");
1429   BCEscapeAnalyzer* analyzer = initializer->get_bcea();
1430   if (analyzer == NULL) {
1431     return;
1432   }
1433 
1434   // Allocation node is first parameter in its initializer
1435   if (analyzer->is_arg_stack(0) || analyzer->is_arg_local(0)) {
1436     _is_allocation_MemBar_redundant = true;
1437   }
1438 }
1439 
1440 Node* AllocateNode::Ideal(PhaseGVN* phase, bool can_reshape) {
1441   // Check for unused value type allocation
1442   if (can_reshape && in(AllocateNode::ValueNode) != NULL &&
1443       outcnt() != 0 && result_cast() == NULL) {
1444     // Remove allocation by replacing the projection nodes with its inputs
1445     PhaseIterGVN* igvn = phase->is_IterGVN();
1446     CallProjections projs;
1447     extract_projections(&projs, true);
1448     igvn->replace_node(projs.fallthrough_catchproj, in(TypeFunc::Control));
1449     igvn->replace_node(projs.fallthrough_memproj, in(TypeFunc::Memory));
1450     igvn->replace_node(projs.catchall_memproj, phase->C->top());
1451     igvn->replace_node(projs.fallthrough_ioproj, in(TypeFunc::I_O));
1452     igvn->replace_node(projs.catchall_ioproj, phase->C->top());
1453     igvn->replace_node(projs.catchall_catchproj, phase->C->top());
1454     igvn->replace_node(projs.resproj, phase->C->top());
1455     igvn->remove_dead_node(this);
1456     return NULL;
1457   }
1458 
1459   return CallNode::Ideal(phase, can_reshape);
1460 }
1461 
1462 //=============================================================================
1463 Node* AllocateArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1464   Node* res = SafePointNode::Ideal(phase, can_reshape);
1465   if (res != NULL) {
1466     return res;
1467   }
1468   // Don't bother trying to transform a dead node
1469   if (in(0) && in(0)->is_top())  return NULL;
1470 
1471   const Type* type = phase->type(Ideal_length());
1472   if (type->isa_int() && type->is_int()->_hi < 0) {
1473     if (can_reshape) {
1474       PhaseIterGVN *igvn = phase->is_IterGVN();
1475       // Unreachable fall through path (negative array length),
1476       // the allocation can only throw so disconnect it.
1477       Node* proj = proj_out(TypeFunc::Control);
1478       Node* catchproj = NULL;
1479       if (proj != NULL) {
1480         for (DUIterator_Fast imax, i = proj->fast_outs(imax); i < imax; i++) {
1481           Node *cn = proj->fast_out(i);
1482           if (cn->is_Catch()) {
1483             catchproj = cn->as_Multi()->proj_out(CatchProjNode::fall_through_index);
1484             break;
1485           }
1486         }
1487       }
1488       if (catchproj != NULL && catchproj->outcnt() > 0 &&
1489           (catchproj->outcnt() > 1 ||
1490            catchproj->unique_out()->Opcode() != Op_Halt)) {
1491         assert(catchproj->is_CatchProj(), "must be a CatchProjNode");
1492         Node* nproj = catchproj->clone();
1493         igvn->register_new_node_with_optimizer(nproj);
1494 
1495         Node *frame = new ParmNode( phase->C->start(), TypeFunc::FramePtr );
1496         frame = phase->transform(frame);
1497         // Halt & Catch Fire
1498         Node *halt = new HaltNode( nproj, frame );
1499         phase->C->root()->add_req(halt);
1500         phase->transform(halt);
1501 
1502         igvn->replace_node(catchproj, phase->C->top());
1503         return this;
1504       }
1505     } else {
1506       // Can't correct it during regular GVN so register for IGVN
1507       phase->C->record_for_igvn(this);
1508     }
1509   }
1510   return NULL;
1511 }
1512 
1513 // Retrieve the length from the AllocateArrayNode. Narrow the type with a
1514 // CastII, if appropriate.  If we are not allowed to create new nodes, and
1515 // a CastII is appropriate, return NULL.
1516 Node *AllocateArrayNode::make_ideal_length(const TypeOopPtr* oop_type, PhaseTransform *phase, bool allow_new_nodes) {
1517   Node *length = in(AllocateNode::ALength);
1518   assert(length != NULL, "length is not null");
1519 
1520   const TypeInt* length_type = phase->find_int_type(length);
1521   const TypeAryPtr* ary_type = oop_type->isa_aryptr();
1522 
1523   if (ary_type != NULL && length_type != NULL) {
1524     const TypeInt* narrow_length_type = ary_type->narrow_size_type(length_type);
1525     if (narrow_length_type != length_type) {
1526       // Assert one of:
1527       //   - the narrow_length is 0
1528       //   - the narrow_length is not wider than length
1529       assert(narrow_length_type == TypeInt::ZERO ||
1530              length_type->is_con() && narrow_length_type->is_con() &&
1531                 (narrow_length_type->_hi <= length_type->_lo) ||
1532              (narrow_length_type->_hi <= length_type->_hi &&
1533               narrow_length_type->_lo >= length_type->_lo),
1534              "narrow type must be narrower than length type");
1535 
1536       // Return NULL if new nodes are not allowed
1537       if (!allow_new_nodes) return NULL;
1538       // Create a cast which is control dependent on the initialization to
1539       // propagate the fact that the array length must be positive.
1540       length = new CastIINode(length, narrow_length_type);
1541       length->set_req(0, initialization()->proj_out(0));
1542     }
1543   }
1544 
1545   return length;
1546 }
1547 
1548 //=============================================================================
1549 uint LockNode::size_of() const { return sizeof(*this); }
1550 
1551 // Redundant lock elimination
1552 //
1553 // There are various patterns of locking where we release and
1554 // immediately reacquire a lock in a piece of code where no operations
1555 // occur in between that would be observable.  In those cases we can
1556 // skip releasing and reacquiring the lock without violating any
1557 // fairness requirements.  Doing this around a loop could cause a lock
1558 // to be held for a very long time so we concentrate on non-looping
1559 // control flow.  We also require that the operations are fully
1560 // redundant meaning that we don't introduce new lock operations on
1561 // some paths so to be able to eliminate it on others ala PRE.  This
1562 // would probably require some more extensive graph manipulation to
1563 // guarantee that the memory edges were all handled correctly.
1564 //
1565 // Assuming p is a simple predicate which can't trap in any way and s
1566 // is a synchronized method consider this code:
1567 //
1568 //   s();
1569 //   if (p)
1570 //     s();
1571 //   else
1572 //     s();
1573 //   s();
1574 //
1575 // 1. The unlocks of the first call to s can be eliminated if the
1576 // locks inside the then and else branches are eliminated.
1577 //
1578 // 2. The unlocks of the then and else branches can be eliminated if
1579 // the lock of the final call to s is eliminated.
1580 //
1581 // Either of these cases subsumes the simple case of sequential control flow
1582 //
1583 // Addtionally we can eliminate versions without the else case:
1584 //
1585 //   s();
1586 //   if (p)
1587 //     s();
1588 //   s();
1589 //
1590 // 3. In this case we eliminate the unlock of the first s, the lock
1591 // and unlock in the then case and the lock in the final s.
1592 //
1593 // Note also that in all these cases the then/else pieces don't have
1594 // to be trivial as long as they begin and end with synchronization
1595 // operations.
1596 //
1597 //   s();
1598 //   if (p)
1599 //     s();
1600 //     f();
1601 //     s();
1602 //   s();
1603 //
1604 // The code will work properly for this case, leaving in the unlock
1605 // before the call to f and the relock after it.
1606 //
1607 // A potentially interesting case which isn't handled here is when the
1608 // locking is partially redundant.
1609 //
1610 //   s();
1611 //   if (p)
1612 //     s();
1613 //
1614 // This could be eliminated putting unlocking on the else case and
1615 // eliminating the first unlock and the lock in the then side.
1616 // Alternatively the unlock could be moved out of the then side so it
1617 // was after the merge and the first unlock and second lock
1618 // eliminated.  This might require less manipulation of the memory
1619 // state to get correct.
1620 //
1621 // Additionally we might allow work between a unlock and lock before
1622 // giving up eliminating the locks.  The current code disallows any
1623 // conditional control flow between these operations.  A formulation
1624 // similar to partial redundancy elimination computing the
1625 // availability of unlocking and the anticipatability of locking at a
1626 // program point would allow detection of fully redundant locking with
1627 // some amount of work in between.  I'm not sure how often I really
1628 // think that would occur though.  Most of the cases I've seen
1629 // indicate it's likely non-trivial work would occur in between.
1630 // There may be other more complicated constructs where we could
1631 // eliminate locking but I haven't seen any others appear as hot or
1632 // interesting.
1633 //
1634 // Locking and unlocking have a canonical form in ideal that looks
1635 // roughly like this:
1636 //
1637 //              <obj>
1638 //                | \\------+
1639 //                |  \       \
1640 //                | BoxLock   \
1641 //                |  |   |     \
1642 //                |  |    \     \
1643 //                |  |   FastLock
1644 //                |  |   /
1645 //                |  |  /
1646 //                |  |  |
1647 //
1648 //               Lock
1649 //                |
1650 //            Proj #0
1651 //                |
1652 //            MembarAcquire
1653 //                |
1654 //            Proj #0
1655 //
1656 //            MembarRelease
1657 //                |
1658 //            Proj #0
1659 //                |
1660 //              Unlock
1661 //                |
1662 //            Proj #0
1663 //
1664 //
1665 // This code proceeds by processing Lock nodes during PhaseIterGVN
1666 // and searching back through its control for the proper code
1667 // patterns.  Once it finds a set of lock and unlock operations to
1668 // eliminate they are marked as eliminatable which causes the
1669 // expansion of the Lock and Unlock macro nodes to make the operation a NOP
1670 //
1671 //=============================================================================
1672 
1673 //
1674 // Utility function to skip over uninteresting control nodes.  Nodes skipped are:
1675 //   - copy regions.  (These may not have been optimized away yet.)
1676 //   - eliminated locking nodes
1677 //
1678 static Node *next_control(Node *ctrl) {
1679   if (ctrl == NULL)
1680     return NULL;
1681   while (1) {
1682     if (ctrl->is_Region()) {
1683       RegionNode *r = ctrl->as_Region();
1684       Node *n = r->is_copy();
1685       if (n == NULL)
1686         break;  // hit a region, return it
1687       else
1688         ctrl = n;
1689     } else if (ctrl->is_Proj()) {
1690       Node *in0 = ctrl->in(0);
1691       if (in0->is_AbstractLock() && in0->as_AbstractLock()->is_eliminated()) {
1692         ctrl = in0->in(0);
1693       } else {
1694         break;
1695       }
1696     } else {
1697       break; // found an interesting control
1698     }
1699   }
1700   return ctrl;
1701 }
1702 //
1703 // Given a control, see if it's the control projection of an Unlock which
1704 // operating on the same object as lock.
1705 //
1706 bool AbstractLockNode::find_matching_unlock(const Node* ctrl, LockNode* lock,
1707                                             GrowableArray<AbstractLockNode*> &lock_ops) {
1708   ProjNode *ctrl_proj = (ctrl->is_Proj()) ? ctrl->as_Proj() : NULL;
1709   if (ctrl_proj != NULL && ctrl_proj->_con == TypeFunc::Control) {
1710     Node *n = ctrl_proj->in(0);
1711     if (n != NULL && n->is_Unlock()) {
1712       UnlockNode *unlock = n->as_Unlock();
1713       if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&
1714           BoxLockNode::same_slot(lock->box_node(), unlock->box_node()) &&
1715           !unlock->is_eliminated()) {
1716         lock_ops.append(unlock);
1717         return true;
1718       }
1719     }
1720   }
1721   return false;
1722 }
1723 
1724 //
1725 // Find the lock matching an unlock.  Returns null if a safepoint
1726 // or complicated control is encountered first.
1727 LockNode *AbstractLockNode::find_matching_lock(UnlockNode* unlock) {
1728   LockNode *lock_result = NULL;
1729   // find the matching lock, or an intervening safepoint
1730   Node *ctrl = next_control(unlock->in(0));
1731   while (1) {
1732     assert(ctrl != NULL, "invalid control graph");
1733     assert(!ctrl->is_Start(), "missing lock for unlock");
1734     if (ctrl->is_top()) break;  // dead control path
1735     if (ctrl->is_Proj()) ctrl = ctrl->in(0);
1736     if (ctrl->is_SafePoint()) {
1737         break;  // found a safepoint (may be the lock we are searching for)
1738     } else if (ctrl->is_Region()) {
1739       // Check for a simple diamond pattern.  Punt on anything more complicated
1740       if (ctrl->req() == 3 && ctrl->in(1) != NULL && ctrl->in(2) != NULL) {
1741         Node *in1 = next_control(ctrl->in(1));
1742         Node *in2 = next_control(ctrl->in(2));
1743         if (((in1->is_IfTrue() && in2->is_IfFalse()) ||
1744              (in2->is_IfTrue() && in1->is_IfFalse())) && (in1->in(0) == in2->in(0))) {
1745           ctrl = next_control(in1->in(0)->in(0));
1746         } else {
1747           break;
1748         }
1749       } else {
1750         break;
1751       }
1752     } else {
1753       ctrl = next_control(ctrl->in(0));  // keep searching
1754     }
1755   }
1756   if (ctrl->is_Lock()) {
1757     LockNode *lock = ctrl->as_Lock();
1758     if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&
1759         BoxLockNode::same_slot(lock->box_node(), unlock->box_node())) {
1760       lock_result = lock;
1761     }
1762   }
1763   return lock_result;
1764 }
1765 
1766 // This code corresponds to case 3 above.
1767 
1768 bool AbstractLockNode::find_lock_and_unlock_through_if(Node* node, LockNode* lock,
1769                                                        GrowableArray<AbstractLockNode*> &lock_ops) {
1770   Node* if_node = node->in(0);
1771   bool  if_true = node->is_IfTrue();
1772 
1773   if (if_node->is_If() && if_node->outcnt() == 2 && (if_true || node->is_IfFalse())) {
1774     Node *lock_ctrl = next_control(if_node->in(0));
1775     if (find_matching_unlock(lock_ctrl, lock, lock_ops)) {
1776       Node* lock1_node = NULL;
1777       ProjNode* proj = if_node->as_If()->proj_out(!if_true);
1778       if (if_true) {
1779         if (proj->is_IfFalse() && proj->outcnt() == 1) {
1780           lock1_node = proj->unique_out();
1781         }
1782       } else {
1783         if (proj->is_IfTrue() && proj->outcnt() == 1) {
1784           lock1_node = proj->unique_out();
1785         }
1786       }
1787       if (lock1_node != NULL && lock1_node->is_Lock()) {
1788         LockNode *lock1 = lock1_node->as_Lock();
1789         if (lock->obj_node()->eqv_uncast(lock1->obj_node()) &&
1790             BoxLockNode::same_slot(lock->box_node(), lock1->box_node()) &&
1791             !lock1->is_eliminated()) {
1792           lock_ops.append(lock1);
1793           return true;
1794         }
1795       }
1796     }
1797   }
1798 
1799   lock_ops.trunc_to(0);
1800   return false;
1801 }
1802 
1803 bool AbstractLockNode::find_unlocks_for_region(const RegionNode* region, LockNode* lock,
1804                                GrowableArray<AbstractLockNode*> &lock_ops) {
1805   // check each control merging at this point for a matching unlock.
1806   // in(0) should be self edge so skip it.
1807   for (int i = 1; i < (int)region->req(); i++) {
1808     Node *in_node = next_control(region->in(i));
1809     if (in_node != NULL) {
1810       if (find_matching_unlock(in_node, lock, lock_ops)) {
1811         // found a match so keep on checking.
1812         continue;
1813       } else if (find_lock_and_unlock_through_if(in_node, lock, lock_ops)) {
1814         continue;
1815       }
1816 
1817       // If we fall through to here then it was some kind of node we
1818       // don't understand or there wasn't a matching unlock, so give
1819       // up trying to merge locks.
1820       lock_ops.trunc_to(0);
1821       return false;
1822     }
1823   }
1824   return true;
1825 
1826 }
1827 
1828 #ifndef PRODUCT
1829 //
1830 // Create a counter which counts the number of times this lock is acquired
1831 //
1832 void AbstractLockNode::create_lock_counter(JVMState* state) {
1833   _counter = OptoRuntime::new_named_counter(state, NamedCounter::LockCounter);
1834 }
1835 
1836 void AbstractLockNode::set_eliminated_lock_counter() {
1837   if (_counter) {
1838     // Update the counter to indicate that this lock was eliminated.
1839     // The counter update code will stay around even though the
1840     // optimizer will eliminate the lock operation itself.
1841     _counter->set_tag(NamedCounter::EliminatedLockCounter);
1842   }
1843 }
1844 
1845 const char* AbstractLockNode::_kind_names[] = {"Regular", "NonEscObj", "Coarsened", "Nested"};
1846 
1847 void AbstractLockNode::dump_spec(outputStream* st) const {
1848   st->print("%s ", _kind_names[_kind]);
1849   CallNode::dump_spec(st);
1850 }
1851 
1852 void AbstractLockNode::dump_compact_spec(outputStream* st) const {
1853   st->print("%s", _kind_names[_kind]);
1854 }
1855 
1856 // The related set of lock nodes includes the control boundary.
1857 void AbstractLockNode::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
1858   if (compact) {
1859       this->collect_nodes(in_rel, 1, false, false);
1860     } else {
1861       this->collect_nodes_in_all_data(in_rel, true);
1862     }
1863     this->collect_nodes(out_rel, -2, false, false);
1864 }
1865 #endif
1866 
1867 //=============================================================================
1868 Node *LockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1869 
1870   // perform any generic optimizations first (returns 'this' or NULL)
1871   Node *result = SafePointNode::Ideal(phase, can_reshape);
1872   if (result != NULL)  return result;
1873   // Don't bother trying to transform a dead node
1874   if (in(0) && in(0)->is_top())  return NULL;
1875 
1876   // Now see if we can optimize away this lock.  We don't actually
1877   // remove the locking here, we simply set the _eliminate flag which
1878   // prevents macro expansion from expanding the lock.  Since we don't
1879   // modify the graph, the value returned from this function is the
1880   // one computed above.
1881   if (can_reshape && EliminateLocks && !is_non_esc_obj()) {
1882     //
1883     // If we are locking an unescaped object, the lock/unlock is unnecessary
1884     //
1885     ConnectionGraph *cgr = phase->C->congraph();
1886     if (cgr != NULL && cgr->not_global_escape(obj_node())) {
1887       assert(!is_eliminated() || is_coarsened(), "sanity");
1888       // The lock could be marked eliminated by lock coarsening
1889       // code during first IGVN before EA. Replace coarsened flag
1890       // to eliminate all associated locks/unlocks.
1891 #ifdef ASSERT
1892       this->log_lock_optimization(phase->C,"eliminate_lock_set_non_esc1");
1893 #endif
1894       this->set_non_esc_obj();
1895       return result;
1896     }
1897 
1898     //
1899     // Try lock coarsening
1900     //
1901     PhaseIterGVN* iter = phase->is_IterGVN();
1902     if (iter != NULL && !is_eliminated()) {
1903 
1904       GrowableArray<AbstractLockNode*>   lock_ops;
1905 
1906       Node *ctrl = next_control(in(0));
1907 
1908       // now search back for a matching Unlock
1909       if (find_matching_unlock(ctrl, this, lock_ops)) {
1910         // found an unlock directly preceding this lock.  This is the
1911         // case of single unlock directly control dependent on a
1912         // single lock which is the trivial version of case 1 or 2.
1913       } else if (ctrl->is_Region() ) {
1914         if (find_unlocks_for_region(ctrl->as_Region(), this, lock_ops)) {
1915         // found lock preceded by multiple unlocks along all paths
1916         // joining at this point which is case 3 in description above.
1917         }
1918       } else {
1919         // see if this lock comes from either half of an if and the
1920         // predecessors merges unlocks and the other half of the if
1921         // performs a lock.
1922         if (find_lock_and_unlock_through_if(ctrl, this, lock_ops)) {
1923           // found unlock splitting to an if with locks on both branches.
1924         }
1925       }
1926 
1927       if (lock_ops.length() > 0) {
1928         // add ourselves to the list of locks to be eliminated.
1929         lock_ops.append(this);
1930 
1931   #ifndef PRODUCT
1932         if (PrintEliminateLocks) {
1933           int locks = 0;
1934           int unlocks = 0;
1935           for (int i = 0; i < lock_ops.length(); i++) {
1936             AbstractLockNode* lock = lock_ops.at(i);
1937             if (lock->Opcode() == Op_Lock)
1938               locks++;
1939             else
1940               unlocks++;
1941             if (Verbose) {
1942               lock->dump(1);
1943             }
1944           }
1945           tty->print_cr("***Eliminated %d unlocks and %d locks", unlocks, locks);
1946         }
1947   #endif
1948 
1949         // for each of the identified locks, mark them
1950         // as eliminatable
1951         for (int i = 0; i < lock_ops.length(); i++) {
1952           AbstractLockNode* lock = lock_ops.at(i);
1953 
1954           // Mark it eliminated by coarsening and update any counters
1955 #ifdef ASSERT
1956           lock->log_lock_optimization(phase->C, "eliminate_lock_set_coarsened");
1957 #endif
1958           lock->set_coarsened();
1959         }
1960       } else if (ctrl->is_Region() &&
1961                  iter->_worklist.member(ctrl)) {
1962         // We weren't able to find any opportunities but the region this
1963         // lock is control dependent on hasn't been processed yet so put
1964         // this lock back on the worklist so we can check again once any
1965         // region simplification has occurred.
1966         iter->_worklist.push(this);
1967       }
1968     }
1969   }
1970 
1971   return result;
1972 }
1973 
1974 //=============================================================================
1975 bool LockNode::is_nested_lock_region() {
1976   return is_nested_lock_region(NULL);
1977 }
1978 
1979 // p is used for access to compilation log; no logging if NULL
1980 bool LockNode::is_nested_lock_region(Compile * c) {
1981   BoxLockNode* box = box_node()->as_BoxLock();
1982   int stk_slot = box->stack_slot();
1983   if (stk_slot <= 0) {
1984 #ifdef ASSERT
1985     this->log_lock_optimization(c, "eliminate_lock_INLR_1");
1986 #endif
1987     return false; // External lock or it is not Box (Phi node).
1988   }
1989 
1990   // Ignore complex cases: merged locks or multiple locks.
1991   Node* obj = obj_node();
1992   LockNode* unique_lock = NULL;
1993   if (!box->is_simple_lock_region(&unique_lock, obj)) {
1994 #ifdef ASSERT
1995     this->log_lock_optimization(c, "eliminate_lock_INLR_2a");
1996 #endif
1997     return false;
1998   }
1999   if (unique_lock != this) {
2000 #ifdef ASSERT
2001     this->log_lock_optimization(c, "eliminate_lock_INLR_2b");
2002 #endif
2003     return false;
2004   }
2005 
2006   // Look for external lock for the same object.
2007   SafePointNode* sfn = this->as_SafePoint();
2008   JVMState* youngest_jvms = sfn->jvms();
2009   int max_depth = youngest_jvms->depth();
2010   for (int depth = 1; depth <= max_depth; depth++) {
2011     JVMState* jvms = youngest_jvms->of_depth(depth);
2012     int num_mon  = jvms->nof_monitors();
2013     // Loop over monitors
2014     for (int idx = 0; idx < num_mon; idx++) {
2015       Node* obj_node = sfn->monitor_obj(jvms, idx);
2016       BoxLockNode* box_node = sfn->monitor_box(jvms, idx)->as_BoxLock();
2017       if ((box_node->stack_slot() < stk_slot) && obj_node->eqv_uncast(obj)) {
2018         return true;
2019       }
2020     }
2021   }
2022 #ifdef ASSERT
2023   this->log_lock_optimization(c, "eliminate_lock_INLR_3");
2024 #endif
2025   return false;
2026 }
2027 
2028 //=============================================================================
2029 uint UnlockNode::size_of() const { return sizeof(*this); }
2030 
2031 //=============================================================================
2032 Node *UnlockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2033 
2034   // perform any generic optimizations first (returns 'this' or NULL)
2035   Node *result = SafePointNode::Ideal(phase, can_reshape);
2036   if (result != NULL)  return result;
2037   // Don't bother trying to transform a dead node
2038   if (in(0) && in(0)->is_top())  return NULL;
2039 
2040   // Now see if we can optimize away this unlock.  We don't actually
2041   // remove the unlocking here, we simply set the _eliminate flag which
2042   // prevents macro expansion from expanding the unlock.  Since we don't
2043   // modify the graph, the value returned from this function is the
2044   // one computed above.
2045   // Escape state is defined after Parse phase.
2046   if (can_reshape && EliminateLocks && !is_non_esc_obj()) {
2047     //
2048     // If we are unlocking an unescaped object, the lock/unlock is unnecessary.
2049     //
2050     ConnectionGraph *cgr = phase->C->congraph();
2051     if (cgr != NULL && cgr->not_global_escape(obj_node())) {
2052       assert(!is_eliminated() || is_coarsened(), "sanity");
2053       // The lock could be marked eliminated by lock coarsening
2054       // code during first IGVN before EA. Replace coarsened flag
2055       // to eliminate all associated locks/unlocks.
2056 #ifdef ASSERT
2057       this->log_lock_optimization(phase->C, "eliminate_lock_set_non_esc2");
2058 #endif
2059       this->set_non_esc_obj();
2060     }
2061   }
2062   return result;
2063 }
2064 
2065 const char * AbstractLockNode::kind_as_string() const {
2066   return is_coarsened()   ? "coarsened" :
2067          is_nested()      ? "nested" :
2068          is_non_esc_obj() ? "non_escaping" :
2069          "?";
2070 }
2071 
2072 void AbstractLockNode::log_lock_optimization(Compile *C, const char * tag)  const {
2073   if (C == NULL) {
2074     return;
2075   }
2076   CompileLog* log = C->log();
2077   if (log != NULL) {
2078     log->begin_head("%s lock='%d' compile_id='%d' class_id='%s' kind='%s'",
2079           tag, is_Lock(), C->compile_id(),
2080           is_Unlock() ? "unlock" : is_Lock() ? "lock" : "?",
2081           kind_as_string());
2082     log->stamp();
2083     log->end_head();
2084     JVMState* p = is_Unlock() ? (as_Unlock()->dbg_jvms()) : jvms();
2085     while (p != NULL) {
2086       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
2087       p = p->caller();
2088     }
2089     log->tail(tag);
2090   }
2091 }
2092 
2093 bool CallNode::may_modify_arraycopy_helper(const TypeOopPtr* dest_t, const TypeOopPtr *t_oop, PhaseTransform *phase) {
2094   if (dest_t->is_known_instance() && t_oop->is_known_instance()) {
2095     return dest_t->instance_id() == t_oop->instance_id();
2096   }
2097 
2098   if (dest_t->isa_instptr() && !dest_t->klass()->equals(phase->C->env()->Object_klass())) {
2099     // clone
2100     if (t_oop->isa_aryptr()) {
2101       return false;
2102     }
2103     if (!t_oop->isa_instptr()) {
2104       return true;
2105     }
2106     if (dest_t->klass()->is_subtype_of(t_oop->klass()) || t_oop->klass()->is_subtype_of(dest_t->klass())) {
2107       return true;
2108     }
2109     // unrelated
2110     return false;
2111   }
2112 
2113   if (dest_t->isa_aryptr()) {
2114     // arraycopy or array clone
2115     if (t_oop->isa_instptr()) {
2116       return false;
2117     }
2118     if (!t_oop->isa_aryptr()) {
2119       return true;
2120     }
2121 
2122     const Type* elem = dest_t->is_aryptr()->elem();
2123     if (elem == Type::BOTTOM) {
2124       // An array but we don't know what elements are
2125       return true;
2126     }
2127 
2128     dest_t = dest_t->add_offset(Type::OffsetBot)->is_oopptr();
2129     uint dest_alias = phase->C->get_alias_index(dest_t);
2130     uint t_oop_alias = phase->C->get_alias_index(t_oop);
2131 
2132     return dest_alias == t_oop_alias;
2133   }
2134 
2135   return true;
2136 }
2137