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   Matcher::c_calling_convention( sig_bt, parm_regs, argcnt );
1098 }
1099 
1100 //=============================================================================
1101 //------------------------------calling_convention-----------------------------
1102 
1103 
1104 //=============================================================================
1105 #ifndef PRODUCT
1106 void CallLeafNode::dump_spec(outputStream *st) const {
1107   st->print("# ");
1108   st->print("%s", _name);
1109   CallNode::dump_spec(st);
1110 }
1111 #endif
1112 
1113 //=============================================================================
1114 
1115 void SafePointNode::set_local(JVMState* jvms, uint idx, Node *c) {
1116   assert(verify_jvms(jvms), "jvms must match");
1117   int loc = jvms->locoff() + idx;
1118   if (in(loc)->is_top() && idx > 0 && !c->is_top() ) {
1119     // If current local idx is top then local idx - 1 could
1120     // be a long/double that needs to be killed since top could
1121     // represent the 2nd half ofthe long/double.
1122     uint ideal = in(loc -1)->ideal_reg();
1123     if (ideal == Op_RegD || ideal == Op_RegL) {
1124       // set other (low index) half to top
1125       set_req(loc - 1, in(loc));
1126     }
1127   }
1128   set_req(loc, c);
1129 }
1130 
1131 uint SafePointNode::size_of() const { return sizeof(*this); }
1132 uint SafePointNode::cmp( const Node &n ) const {
1133   return (&n == this);          // Always fail except on self
1134 }
1135 
1136 //-------------------------set_next_exception----------------------------------
1137 void SafePointNode::set_next_exception(SafePointNode* n) {
1138   assert(n == NULL || n->Opcode() == Op_SafePoint, "correct value for next_exception");
1139   if (len() == req()) {
1140     if (n != NULL)  add_prec(n);
1141   } else {
1142     set_prec(req(), n);
1143   }
1144 }
1145 
1146 
1147 //----------------------------next_exception-----------------------------------
1148 SafePointNode* SafePointNode::next_exception() const {
1149   if (len() == req()) {
1150     return NULL;
1151   } else {
1152     Node* n = in(req());
1153     assert(n == NULL || n->Opcode() == Op_SafePoint, "no other uses of prec edges");
1154     return (SafePointNode*) n;
1155   }
1156 }
1157 
1158 
1159 //------------------------------Ideal------------------------------------------
1160 // Skip over any collapsed Regions
1161 Node *SafePointNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1162   if (remove_dead_region(phase, can_reshape)) {
1163     return this;
1164   }
1165   if (jvms() != NULL) {
1166     bool progress = false;
1167     // A ValueTypeNode that was already heap allocated in the debug
1168     // info?  Reference the object directly. Helps removal of useless
1169     // value type allocations with incremental inlining.
1170     for (uint i = jvms()->debug_start(); i < jvms()->debug_end(); i++) {
1171       Node *arg = in(i);
1172       if (arg->is_ValueType()) {
1173         ValueTypeNode* vt = arg->as_ValueType();
1174         Node* in_oop = vt->get_oop();
1175         const Type* oop_type = phase->type(in_oop);
1176         if (!TypePtr::NULL_PTR->higher_equal(oop_type)) {
1177           set_req(i, in_oop);
1178           progress = true;
1179         }
1180       }
1181     }
1182     if (progress) {
1183       return this;
1184     }
1185   }
1186   return NULL;
1187 }
1188 
1189 //------------------------------Identity---------------------------------------
1190 // Remove obviously duplicate safepoints
1191 Node* SafePointNode::Identity(PhaseGVN* phase) {
1192 
1193   // If you have back to back safepoints, remove one
1194   if( in(TypeFunc::Control)->is_SafePoint() )
1195     return in(TypeFunc::Control);
1196 
1197   if( in(0)->is_Proj() ) {
1198     Node *n0 = in(0)->in(0);
1199     // Check if he is a call projection (except Leaf Call)
1200     if( n0->is_Catch() ) {
1201       n0 = n0->in(0)->in(0);
1202       assert( n0->is_Call(), "expect a call here" );
1203     }
1204     if( n0->is_Call() && n0->as_Call()->guaranteed_safepoint() ) {
1205       // Useless Safepoint, so remove it
1206       return in(TypeFunc::Control);
1207     }
1208   }
1209 
1210   return this;
1211 }
1212 
1213 //------------------------------Value------------------------------------------
1214 const Type* SafePointNode::Value(PhaseGVN* phase) const {
1215   if( phase->type(in(0)) == Type::TOP ) return Type::TOP;
1216   if( phase->eqv( in(0), this ) ) return Type::TOP; // Dead infinite loop
1217   return Type::CONTROL;
1218 }
1219 
1220 #ifndef PRODUCT
1221 void SafePointNode::dump_spec(outputStream *st) const {
1222   st->print(" SafePoint ");
1223   _replaced_nodes.dump(st);
1224 }
1225 
1226 // The related nodes of a SafepointNode are all data inputs, excluding the
1227 // control boundary, as well as all outputs till level 2 (to include projection
1228 // nodes and targets). In compact mode, just include inputs till level 1 and
1229 // outputs as before.
1230 void SafePointNode::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
1231   if (compact) {
1232     this->collect_nodes(in_rel, 1, false, false);
1233   } else {
1234     this->collect_nodes_in_all_data(in_rel, false);
1235   }
1236   this->collect_nodes(out_rel, -2, false, false);
1237 }
1238 #endif
1239 
1240 const RegMask &SafePointNode::in_RegMask(uint idx) const {
1241   if( idx < TypeFunc::Parms ) return RegMask::Empty;
1242   // Values outside the domain represent debug info
1243   return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
1244 }
1245 const RegMask &SafePointNode::out_RegMask() const {
1246   return RegMask::Empty;
1247 }
1248 
1249 
1250 void SafePointNode::grow_stack(JVMState* jvms, uint grow_by) {
1251   assert((int)grow_by > 0, "sanity");
1252   int monoff = jvms->monoff();
1253   int scloff = jvms->scloff();
1254   int endoff = jvms->endoff();
1255   assert(endoff == (int)req(), "no other states or debug info after me");
1256   Node* top = Compile::current()->top();
1257   for (uint i = 0; i < grow_by; i++) {
1258     ins_req(monoff, top);
1259   }
1260   jvms->set_monoff(monoff + grow_by);
1261   jvms->set_scloff(scloff + grow_by);
1262   jvms->set_endoff(endoff + grow_by);
1263 }
1264 
1265 void SafePointNode::push_monitor(const FastLockNode *lock) {
1266   // Add a LockNode, which points to both the original BoxLockNode (the
1267   // stack space for the monitor) and the Object being locked.
1268   const int MonitorEdges = 2;
1269   assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
1270   assert(req() == jvms()->endoff(), "correct sizing");
1271   int nextmon = jvms()->scloff();
1272   if (GenerateSynchronizationCode) {
1273     ins_req(nextmon,   lock->box_node());
1274     ins_req(nextmon+1, lock->obj_node());
1275   } else {
1276     Node* top = Compile::current()->top();
1277     ins_req(nextmon, top);
1278     ins_req(nextmon, top);
1279   }
1280   jvms()->set_scloff(nextmon + MonitorEdges);
1281   jvms()->set_endoff(req());
1282 }
1283 
1284 void SafePointNode::pop_monitor() {
1285   // Delete last monitor from debug info
1286   debug_only(int num_before_pop = jvms()->nof_monitors());
1287   const int MonitorEdges = 2;
1288   assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
1289   int scloff = jvms()->scloff();
1290   int endoff = jvms()->endoff();
1291   int new_scloff = scloff - MonitorEdges;
1292   int new_endoff = endoff - MonitorEdges;
1293   jvms()->set_scloff(new_scloff);
1294   jvms()->set_endoff(new_endoff);
1295   while (scloff > new_scloff)  del_req_ordered(--scloff);
1296   assert(jvms()->nof_monitors() == num_before_pop-1, "");
1297 }
1298 
1299 Node *SafePointNode::peek_monitor_box() const {
1300   int mon = jvms()->nof_monitors() - 1;
1301   assert(mon >= 0, "must have a monitor");
1302   return monitor_box(jvms(), mon);
1303 }
1304 
1305 Node *SafePointNode::peek_monitor_obj() const {
1306   int mon = jvms()->nof_monitors() - 1;
1307   assert(mon >= 0, "must have a monitor");
1308   return monitor_obj(jvms(), mon);
1309 }
1310 
1311 // Do we Match on this edge index or not?  Match no edges
1312 uint SafePointNode::match_edge(uint idx) const {
1313   if( !needs_polling_address_input() )
1314     return 0;
1315 
1316   return (TypeFunc::Parms == idx);
1317 }
1318 
1319 //==============  SafePointScalarObjectNode  ==============
1320 
1321 SafePointScalarObjectNode::SafePointScalarObjectNode(const TypeOopPtr* tp,
1322 #ifdef ASSERT
1323                                                      AllocateNode* alloc,
1324 #endif
1325                                                      uint first_index,
1326                                                      uint n_fields) :
1327   TypeNode(tp, 1), // 1 control input -- seems required.  Get from root.
1328 #ifdef ASSERT
1329   _alloc(alloc),
1330 #endif
1331   _first_index(first_index),
1332   _n_fields(n_fields)
1333 {
1334   init_class_id(Class_SafePointScalarObject);
1335 }
1336 
1337 // Do not allow value-numbering for SafePointScalarObject node.
1338 uint SafePointScalarObjectNode::hash() const { return NO_HASH; }
1339 uint SafePointScalarObjectNode::cmp( const Node &n ) const {
1340   return (&n == this); // Always fail except on self
1341 }
1342 
1343 uint SafePointScalarObjectNode::ideal_reg() const {
1344   return 0; // No matching to machine instruction
1345 }
1346 
1347 const RegMask &SafePointScalarObjectNode::in_RegMask(uint idx) const {
1348   return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
1349 }
1350 
1351 const RegMask &SafePointScalarObjectNode::out_RegMask() const {
1352   return RegMask::Empty;
1353 }
1354 
1355 uint SafePointScalarObjectNode::match_edge(uint idx) const {
1356   return 0;
1357 }
1358 
1359 SafePointScalarObjectNode*
1360 SafePointScalarObjectNode::clone(Dict* sosn_map) const {
1361   void* cached = (*sosn_map)[(void*)this];
1362   if (cached != NULL) {
1363     return (SafePointScalarObjectNode*)cached;
1364   }
1365   SafePointScalarObjectNode* res = (SafePointScalarObjectNode*)Node::clone();
1366   sosn_map->Insert((void*)this, (void*)res);
1367   return res;
1368 }
1369 
1370 
1371 #ifndef PRODUCT
1372 void SafePointScalarObjectNode::dump_spec(outputStream *st) const {
1373   st->print(" # fields@[%d..%d]", first_index(),
1374              first_index() + n_fields() - 1);
1375 }
1376 
1377 #endif
1378 
1379 //=============================================================================
1380 uint AllocateNode::size_of() const { return sizeof(*this); }
1381 
1382 AllocateNode::AllocateNode(Compile* C, const TypeFunc *atype,
1383                            Node *ctrl, Node *mem, Node *abio,
1384                            Node *size, Node *klass_node,
1385                            Node* initial_test, ValueTypeNode* value_node)
1386   : CallNode(atype, NULL, TypeRawPtr::BOTTOM)
1387 {
1388   init_class_id(Class_Allocate);
1389   init_flags(Flag_is_macro);
1390   _is_scalar_replaceable = false;
1391   _is_non_escaping = false;
1392   _is_allocation_MemBar_redundant = false;
1393   Node *topnode = C->top();
1394 
1395   init_req( TypeFunc::Control  , ctrl );
1396   init_req( TypeFunc::I_O      , abio );
1397   init_req( TypeFunc::Memory   , mem );
1398   init_req( TypeFunc::ReturnAdr, topnode );
1399   init_req( TypeFunc::FramePtr , topnode );
1400   init_req( AllocSize          , size);
1401   init_req( KlassNode          , klass_node);
1402   init_req( InitialTest        , initial_test);
1403   init_req( ALength            , topnode);
1404   init_req( ValueNode          , value_node);
1405   C->add_macro_node(this);
1406 }
1407 
1408 void AllocateNode::compute_MemBar_redundancy(ciMethod* initializer)
1409 {
1410   assert(initializer != NULL &&
1411          initializer->is_initializer() &&
1412          !initializer->is_static(),
1413              "unexpected initializer method");
1414   BCEscapeAnalyzer* analyzer = initializer->get_bcea();
1415   if (analyzer == NULL) {
1416     return;
1417   }
1418 
1419   // Allocation node is first parameter in its initializer
1420   if (analyzer->is_arg_stack(0) || analyzer->is_arg_local(0)) {
1421     _is_allocation_MemBar_redundant = true;
1422   }
1423 }
1424 
1425 //=============================================================================
1426 Node* AllocateArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1427   Node* res = SafePointNode::Ideal(phase, can_reshape);
1428   if (res != NULL) {
1429     return res;
1430   }
1431   // Don't bother trying to transform a dead node
1432   if (in(0) && in(0)->is_top())  return NULL;
1433 
1434   const Type* type = phase->type(Ideal_length());
1435   if (type->isa_int() && type->is_int()->_hi < 0) {
1436     if (can_reshape) {
1437       PhaseIterGVN *igvn = phase->is_IterGVN();
1438       // Unreachable fall through path (negative array length),
1439       // the allocation can only throw so disconnect it.
1440       Node* proj = proj_out(TypeFunc::Control);
1441       Node* catchproj = NULL;
1442       if (proj != NULL) {
1443         for (DUIterator_Fast imax, i = proj->fast_outs(imax); i < imax; i++) {
1444           Node *cn = proj->fast_out(i);
1445           if (cn->is_Catch()) {
1446             catchproj = cn->as_Multi()->proj_out(CatchProjNode::fall_through_index);
1447             break;
1448           }
1449         }
1450       }
1451       if (catchproj != NULL && catchproj->outcnt() > 0 &&
1452           (catchproj->outcnt() > 1 ||
1453            catchproj->unique_out()->Opcode() != Op_Halt)) {
1454         assert(catchproj->is_CatchProj(), "must be a CatchProjNode");
1455         Node* nproj = catchproj->clone();
1456         igvn->register_new_node_with_optimizer(nproj);
1457 
1458         Node *frame = new ParmNode( phase->C->start(), TypeFunc::FramePtr );
1459         frame = phase->transform(frame);
1460         // Halt & Catch Fire
1461         Node *halt = new HaltNode( nproj, frame );
1462         phase->C->root()->add_req(halt);
1463         phase->transform(halt);
1464 
1465         igvn->replace_node(catchproj, phase->C->top());
1466         return this;
1467       }
1468     } else {
1469       // Can't correct it during regular GVN so register for IGVN
1470       phase->C->record_for_igvn(this);
1471     }
1472   }
1473   return NULL;
1474 }
1475 
1476 // Retrieve the length from the AllocateArrayNode. Narrow the type with a
1477 // CastII, if appropriate.  If we are not allowed to create new nodes, and
1478 // a CastII is appropriate, return NULL.
1479 Node *AllocateArrayNode::make_ideal_length(const TypeOopPtr* oop_type, PhaseTransform *phase, bool allow_new_nodes) {
1480   Node *length = in(AllocateNode::ALength);
1481   assert(length != NULL, "length is not null");
1482 
1483   const TypeInt* length_type = phase->find_int_type(length);
1484   const TypeAryPtr* ary_type = oop_type->isa_aryptr();
1485 
1486   if (ary_type != NULL && length_type != NULL) {
1487     const TypeInt* narrow_length_type = ary_type->narrow_size_type(length_type);
1488     if (narrow_length_type != length_type) {
1489       // Assert one of:
1490       //   - the narrow_length is 0
1491       //   - the narrow_length is not wider than length
1492       assert(narrow_length_type == TypeInt::ZERO ||
1493              length_type->is_con() && narrow_length_type->is_con() &&
1494                 (narrow_length_type->_hi <= length_type->_lo) ||
1495              (narrow_length_type->_hi <= length_type->_hi &&
1496               narrow_length_type->_lo >= length_type->_lo),
1497              "narrow type must be narrower than length type");
1498 
1499       // Return NULL if new nodes are not allowed
1500       if (!allow_new_nodes) return NULL;
1501       // Create a cast which is control dependent on the initialization to
1502       // propagate the fact that the array length must be positive.
1503       length = new CastIINode(length, narrow_length_type);
1504       length->set_req(0, initialization()->proj_out(0));
1505     }
1506   }
1507 
1508   return length;
1509 }
1510 
1511 //=============================================================================
1512 uint LockNode::size_of() const { return sizeof(*this); }
1513 
1514 // Redundant lock elimination
1515 //
1516 // There are various patterns of locking where we release and
1517 // immediately reacquire a lock in a piece of code where no operations
1518 // occur in between that would be observable.  In those cases we can
1519 // skip releasing and reacquiring the lock without violating any
1520 // fairness requirements.  Doing this around a loop could cause a lock
1521 // to be held for a very long time so we concentrate on non-looping
1522 // control flow.  We also require that the operations are fully
1523 // redundant meaning that we don't introduce new lock operations on
1524 // some paths so to be able to eliminate it on others ala PRE.  This
1525 // would probably require some more extensive graph manipulation to
1526 // guarantee that the memory edges were all handled correctly.
1527 //
1528 // Assuming p is a simple predicate which can't trap in any way and s
1529 // is a synchronized method consider this code:
1530 //
1531 //   s();
1532 //   if (p)
1533 //     s();
1534 //   else
1535 //     s();
1536 //   s();
1537 //
1538 // 1. The unlocks of the first call to s can be eliminated if the
1539 // locks inside the then and else branches are eliminated.
1540 //
1541 // 2. The unlocks of the then and else branches can be eliminated if
1542 // the lock of the final call to s is eliminated.
1543 //
1544 // Either of these cases subsumes the simple case of sequential control flow
1545 //
1546 // Addtionally we can eliminate versions without the else case:
1547 //
1548 //   s();
1549 //   if (p)
1550 //     s();
1551 //   s();
1552 //
1553 // 3. In this case we eliminate the unlock of the first s, the lock
1554 // and unlock in the then case and the lock in the final s.
1555 //
1556 // Note also that in all these cases the then/else pieces don't have
1557 // to be trivial as long as they begin and end with synchronization
1558 // operations.
1559 //
1560 //   s();
1561 //   if (p)
1562 //     s();
1563 //     f();
1564 //     s();
1565 //   s();
1566 //
1567 // The code will work properly for this case, leaving in the unlock
1568 // before the call to f and the relock after it.
1569 //
1570 // A potentially interesting case which isn't handled here is when the
1571 // locking is partially redundant.
1572 //
1573 //   s();
1574 //   if (p)
1575 //     s();
1576 //
1577 // This could be eliminated putting unlocking on the else case and
1578 // eliminating the first unlock and the lock in the then side.
1579 // Alternatively the unlock could be moved out of the then side so it
1580 // was after the merge and the first unlock and second lock
1581 // eliminated.  This might require less manipulation of the memory
1582 // state to get correct.
1583 //
1584 // Additionally we might allow work between a unlock and lock before
1585 // giving up eliminating the locks.  The current code disallows any
1586 // conditional control flow between these operations.  A formulation
1587 // similar to partial redundancy elimination computing the
1588 // availability of unlocking and the anticipatability of locking at a
1589 // program point would allow detection of fully redundant locking with
1590 // some amount of work in between.  I'm not sure how often I really
1591 // think that would occur though.  Most of the cases I've seen
1592 // indicate it's likely non-trivial work would occur in between.
1593 // There may be other more complicated constructs where we could
1594 // eliminate locking but I haven't seen any others appear as hot or
1595 // interesting.
1596 //
1597 // Locking and unlocking have a canonical form in ideal that looks
1598 // roughly like this:
1599 //
1600 //              <obj>
1601 //                | \\------+
1602 //                |  \       \
1603 //                | BoxLock   \
1604 //                |  |   |     \
1605 //                |  |    \     \
1606 //                |  |   FastLock
1607 //                |  |   /
1608 //                |  |  /
1609 //                |  |  |
1610 //
1611 //               Lock
1612 //                |
1613 //            Proj #0
1614 //                |
1615 //            MembarAcquire
1616 //                |
1617 //            Proj #0
1618 //
1619 //            MembarRelease
1620 //                |
1621 //            Proj #0
1622 //                |
1623 //              Unlock
1624 //                |
1625 //            Proj #0
1626 //
1627 //
1628 // This code proceeds by processing Lock nodes during PhaseIterGVN
1629 // and searching back through its control for the proper code
1630 // patterns.  Once it finds a set of lock and unlock operations to
1631 // eliminate they are marked as eliminatable which causes the
1632 // expansion of the Lock and Unlock macro nodes to make the operation a NOP
1633 //
1634 //=============================================================================
1635 
1636 //
1637 // Utility function to skip over uninteresting control nodes.  Nodes skipped are:
1638 //   - copy regions.  (These may not have been optimized away yet.)
1639 //   - eliminated locking nodes
1640 //
1641 static Node *next_control(Node *ctrl) {
1642   if (ctrl == NULL)
1643     return NULL;
1644   while (1) {
1645     if (ctrl->is_Region()) {
1646       RegionNode *r = ctrl->as_Region();
1647       Node *n = r->is_copy();
1648       if (n == NULL)
1649         break;  // hit a region, return it
1650       else
1651         ctrl = n;
1652     } else if (ctrl->is_Proj()) {
1653       Node *in0 = ctrl->in(0);
1654       if (in0->is_AbstractLock() && in0->as_AbstractLock()->is_eliminated()) {
1655         ctrl = in0->in(0);
1656       } else {
1657         break;
1658       }
1659     } else {
1660       break; // found an interesting control
1661     }
1662   }
1663   return ctrl;
1664 }
1665 //
1666 // Given a control, see if it's the control projection of an Unlock which
1667 // operating on the same object as lock.
1668 //
1669 bool AbstractLockNode::find_matching_unlock(const Node* ctrl, LockNode* lock,
1670                                             GrowableArray<AbstractLockNode*> &lock_ops) {
1671   ProjNode *ctrl_proj = (ctrl->is_Proj()) ? ctrl->as_Proj() : NULL;
1672   if (ctrl_proj != NULL && ctrl_proj->_con == TypeFunc::Control) {
1673     Node *n = ctrl_proj->in(0);
1674     if (n != NULL && n->is_Unlock()) {
1675       UnlockNode *unlock = n->as_Unlock();
1676       if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&
1677           BoxLockNode::same_slot(lock->box_node(), unlock->box_node()) &&
1678           !unlock->is_eliminated()) {
1679         lock_ops.append(unlock);
1680         return true;
1681       }
1682     }
1683   }
1684   return false;
1685 }
1686 
1687 //
1688 // Find the lock matching an unlock.  Returns null if a safepoint
1689 // or complicated control is encountered first.
1690 LockNode *AbstractLockNode::find_matching_lock(UnlockNode* unlock) {
1691   LockNode *lock_result = NULL;
1692   // find the matching lock, or an intervening safepoint
1693   Node *ctrl = next_control(unlock->in(0));
1694   while (1) {
1695     assert(ctrl != NULL, "invalid control graph");
1696     assert(!ctrl->is_Start(), "missing lock for unlock");
1697     if (ctrl->is_top()) break;  // dead control path
1698     if (ctrl->is_Proj()) ctrl = ctrl->in(0);
1699     if (ctrl->is_SafePoint()) {
1700         break;  // found a safepoint (may be the lock we are searching for)
1701     } else if (ctrl->is_Region()) {
1702       // Check for a simple diamond pattern.  Punt on anything more complicated
1703       if (ctrl->req() == 3 && ctrl->in(1) != NULL && ctrl->in(2) != NULL) {
1704         Node *in1 = next_control(ctrl->in(1));
1705         Node *in2 = next_control(ctrl->in(2));
1706         if (((in1->is_IfTrue() && in2->is_IfFalse()) ||
1707              (in2->is_IfTrue() && in1->is_IfFalse())) && (in1->in(0) == in2->in(0))) {
1708           ctrl = next_control(in1->in(0)->in(0));
1709         } else {
1710           break;
1711         }
1712       } else {
1713         break;
1714       }
1715     } else {
1716       ctrl = next_control(ctrl->in(0));  // keep searching
1717     }
1718   }
1719   if (ctrl->is_Lock()) {
1720     LockNode *lock = ctrl->as_Lock();
1721     if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&
1722         BoxLockNode::same_slot(lock->box_node(), unlock->box_node())) {
1723       lock_result = lock;
1724     }
1725   }
1726   return lock_result;
1727 }
1728 
1729 // This code corresponds to case 3 above.
1730 
1731 bool AbstractLockNode::find_lock_and_unlock_through_if(Node* node, LockNode* lock,
1732                                                        GrowableArray<AbstractLockNode*> &lock_ops) {
1733   Node* if_node = node->in(0);
1734   bool  if_true = node->is_IfTrue();
1735 
1736   if (if_node->is_If() && if_node->outcnt() == 2 && (if_true || node->is_IfFalse())) {
1737     Node *lock_ctrl = next_control(if_node->in(0));
1738     if (find_matching_unlock(lock_ctrl, lock, lock_ops)) {
1739       Node* lock1_node = NULL;
1740       ProjNode* proj = if_node->as_If()->proj_out(!if_true);
1741       if (if_true) {
1742         if (proj->is_IfFalse() && proj->outcnt() == 1) {
1743           lock1_node = proj->unique_out();
1744         }
1745       } else {
1746         if (proj->is_IfTrue() && proj->outcnt() == 1) {
1747           lock1_node = proj->unique_out();
1748         }
1749       }
1750       if (lock1_node != NULL && lock1_node->is_Lock()) {
1751         LockNode *lock1 = lock1_node->as_Lock();
1752         if (lock->obj_node()->eqv_uncast(lock1->obj_node()) &&
1753             BoxLockNode::same_slot(lock->box_node(), lock1->box_node()) &&
1754             !lock1->is_eliminated()) {
1755           lock_ops.append(lock1);
1756           return true;
1757         }
1758       }
1759     }
1760   }
1761 
1762   lock_ops.trunc_to(0);
1763   return false;
1764 }
1765 
1766 bool AbstractLockNode::find_unlocks_for_region(const RegionNode* region, LockNode* lock,
1767                                GrowableArray<AbstractLockNode*> &lock_ops) {
1768   // check each control merging at this point for a matching unlock.
1769   // in(0) should be self edge so skip it.
1770   for (int i = 1; i < (int)region->req(); i++) {
1771     Node *in_node = next_control(region->in(i));
1772     if (in_node != NULL) {
1773       if (find_matching_unlock(in_node, lock, lock_ops)) {
1774         // found a match so keep on checking.
1775         continue;
1776       } else if (find_lock_and_unlock_through_if(in_node, lock, lock_ops)) {
1777         continue;
1778       }
1779 
1780       // If we fall through to here then it was some kind of node we
1781       // don't understand or there wasn't a matching unlock, so give
1782       // up trying to merge locks.
1783       lock_ops.trunc_to(0);
1784       return false;
1785     }
1786   }
1787   return true;
1788 
1789 }
1790 
1791 #ifndef PRODUCT
1792 //
1793 // Create a counter which counts the number of times this lock is acquired
1794 //
1795 void AbstractLockNode::create_lock_counter(JVMState* state) {
1796   _counter = OptoRuntime::new_named_counter(state, NamedCounter::LockCounter);
1797 }
1798 
1799 void AbstractLockNode::set_eliminated_lock_counter() {
1800   if (_counter) {
1801     // Update the counter to indicate that this lock was eliminated.
1802     // The counter update code will stay around even though the
1803     // optimizer will eliminate the lock operation itself.
1804     _counter->set_tag(NamedCounter::EliminatedLockCounter);
1805   }
1806 }
1807 
1808 const char* AbstractLockNode::_kind_names[] = {"Regular", "NonEscObj", "Coarsened", "Nested"};
1809 
1810 void AbstractLockNode::dump_spec(outputStream* st) const {
1811   st->print("%s ", _kind_names[_kind]);
1812   CallNode::dump_spec(st);
1813 }
1814 
1815 void AbstractLockNode::dump_compact_spec(outputStream* st) const {
1816   st->print("%s", _kind_names[_kind]);
1817 }
1818 
1819 // The related set of lock nodes includes the control boundary.
1820 void AbstractLockNode::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
1821   if (compact) {
1822       this->collect_nodes(in_rel, 1, false, false);
1823     } else {
1824       this->collect_nodes_in_all_data(in_rel, true);
1825     }
1826     this->collect_nodes(out_rel, -2, false, false);
1827 }
1828 #endif
1829 
1830 //=============================================================================
1831 Node *LockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1832 
1833   // perform any generic optimizations first (returns 'this' or NULL)
1834   Node *result = SafePointNode::Ideal(phase, can_reshape);
1835   if (result != NULL)  return result;
1836   // Don't bother trying to transform a dead node
1837   if (in(0) && in(0)->is_top())  return NULL;
1838 
1839   // Now see if we can optimize away this lock.  We don't actually
1840   // remove the locking here, we simply set the _eliminate flag which
1841   // prevents macro expansion from expanding the lock.  Since we don't
1842   // modify the graph, the value returned from this function is the
1843   // one computed above.
1844   if (can_reshape && EliminateLocks && !is_non_esc_obj()) {
1845     //
1846     // If we are locking an unescaped object, the lock/unlock is unnecessary
1847     //
1848     ConnectionGraph *cgr = phase->C->congraph();
1849     if (cgr != NULL && cgr->not_global_escape(obj_node())) {
1850       assert(!is_eliminated() || is_coarsened(), "sanity");
1851       // The lock could be marked eliminated by lock coarsening
1852       // code during first IGVN before EA. Replace coarsened flag
1853       // to eliminate all associated locks/unlocks.
1854 #ifdef ASSERT
1855       this->log_lock_optimization(phase->C,"eliminate_lock_set_non_esc1");
1856 #endif
1857       this->set_non_esc_obj();
1858       return result;
1859     }
1860 
1861     //
1862     // Try lock coarsening
1863     //
1864     PhaseIterGVN* iter = phase->is_IterGVN();
1865     if (iter != NULL && !is_eliminated()) {
1866 
1867       GrowableArray<AbstractLockNode*>   lock_ops;
1868 
1869       Node *ctrl = next_control(in(0));
1870 
1871       // now search back for a matching Unlock
1872       if (find_matching_unlock(ctrl, this, lock_ops)) {
1873         // found an unlock directly preceding this lock.  This is the
1874         // case of single unlock directly control dependent on a
1875         // single lock which is the trivial version of case 1 or 2.
1876       } else if (ctrl->is_Region() ) {
1877         if (find_unlocks_for_region(ctrl->as_Region(), this, lock_ops)) {
1878         // found lock preceded by multiple unlocks along all paths
1879         // joining at this point which is case 3 in description above.
1880         }
1881       } else {
1882         // see if this lock comes from either half of an if and the
1883         // predecessors merges unlocks and the other half of the if
1884         // performs a lock.
1885         if (find_lock_and_unlock_through_if(ctrl, this, lock_ops)) {
1886           // found unlock splitting to an if with locks on both branches.
1887         }
1888       }
1889 
1890       if (lock_ops.length() > 0) {
1891         // add ourselves to the list of locks to be eliminated.
1892         lock_ops.append(this);
1893 
1894   #ifndef PRODUCT
1895         if (PrintEliminateLocks) {
1896           int locks = 0;
1897           int unlocks = 0;
1898           for (int i = 0; i < lock_ops.length(); i++) {
1899             AbstractLockNode* lock = lock_ops.at(i);
1900             if (lock->Opcode() == Op_Lock)
1901               locks++;
1902             else
1903               unlocks++;
1904             if (Verbose) {
1905               lock->dump(1);
1906             }
1907           }
1908           tty->print_cr("***Eliminated %d unlocks and %d locks", unlocks, locks);
1909         }
1910   #endif
1911 
1912         // for each of the identified locks, mark them
1913         // as eliminatable
1914         for (int i = 0; i < lock_ops.length(); i++) {
1915           AbstractLockNode* lock = lock_ops.at(i);
1916 
1917           // Mark it eliminated by coarsening and update any counters
1918 #ifdef ASSERT
1919           lock->log_lock_optimization(phase->C, "eliminate_lock_set_coarsened");
1920 #endif
1921           lock->set_coarsened();
1922         }
1923       } else if (ctrl->is_Region() &&
1924                  iter->_worklist.member(ctrl)) {
1925         // We weren't able to find any opportunities but the region this
1926         // lock is control dependent on hasn't been processed yet so put
1927         // this lock back on the worklist so we can check again once any
1928         // region simplification has occurred.
1929         iter->_worklist.push(this);
1930       }
1931     }
1932   }
1933 
1934   return result;
1935 }
1936 
1937 //=============================================================================
1938 bool LockNode::is_nested_lock_region() {
1939   return is_nested_lock_region(NULL);
1940 }
1941 
1942 // p is used for access to compilation log; no logging if NULL
1943 bool LockNode::is_nested_lock_region(Compile * c) {
1944   BoxLockNode* box = box_node()->as_BoxLock();
1945   int stk_slot = box->stack_slot();
1946   if (stk_slot <= 0) {
1947 #ifdef ASSERT
1948     this->log_lock_optimization(c, "eliminate_lock_INLR_1");
1949 #endif
1950     return false; // External lock or it is not Box (Phi node).
1951   }
1952 
1953   // Ignore complex cases: merged locks or multiple locks.
1954   Node* obj = obj_node();
1955   LockNode* unique_lock = NULL;
1956   if (!box->is_simple_lock_region(&unique_lock, obj)) {
1957 #ifdef ASSERT
1958     this->log_lock_optimization(c, "eliminate_lock_INLR_2a");
1959 #endif
1960     return false;
1961   }
1962   if (unique_lock != this) {
1963 #ifdef ASSERT
1964     this->log_lock_optimization(c, "eliminate_lock_INLR_2b");
1965 #endif
1966     return false;
1967   }
1968 
1969   // Look for external lock for the same object.
1970   SafePointNode* sfn = this->as_SafePoint();
1971   JVMState* youngest_jvms = sfn->jvms();
1972   int max_depth = youngest_jvms->depth();
1973   for (int depth = 1; depth <= max_depth; depth++) {
1974     JVMState* jvms = youngest_jvms->of_depth(depth);
1975     int num_mon  = jvms->nof_monitors();
1976     // Loop over monitors
1977     for (int idx = 0; idx < num_mon; idx++) {
1978       Node* obj_node = sfn->monitor_obj(jvms, idx);
1979       BoxLockNode* box_node = sfn->monitor_box(jvms, idx)->as_BoxLock();
1980       if ((box_node->stack_slot() < stk_slot) && obj_node->eqv_uncast(obj)) {
1981         return true;
1982       }
1983     }
1984   }
1985 #ifdef ASSERT
1986   this->log_lock_optimization(c, "eliminate_lock_INLR_3");
1987 #endif
1988   return false;
1989 }
1990 
1991 //=============================================================================
1992 uint UnlockNode::size_of() const { return sizeof(*this); }
1993 
1994 //=============================================================================
1995 Node *UnlockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1996 
1997   // perform any generic optimizations first (returns 'this' or NULL)
1998   Node *result = SafePointNode::Ideal(phase, can_reshape);
1999   if (result != NULL)  return result;
2000   // Don't bother trying to transform a dead node
2001   if (in(0) && in(0)->is_top())  return NULL;
2002 
2003   // Now see if we can optimize away this unlock.  We don't actually
2004   // remove the unlocking here, we simply set the _eliminate flag which
2005   // prevents macro expansion from expanding the unlock.  Since we don't
2006   // modify the graph, the value returned from this function is the
2007   // one computed above.
2008   // Escape state is defined after Parse phase.
2009   if (can_reshape && EliminateLocks && !is_non_esc_obj()) {
2010     //
2011     // If we are unlocking an unescaped object, the lock/unlock is unnecessary.
2012     //
2013     ConnectionGraph *cgr = phase->C->congraph();
2014     if (cgr != NULL && cgr->not_global_escape(obj_node())) {
2015       assert(!is_eliminated() || is_coarsened(), "sanity");
2016       // The lock could be marked eliminated by lock coarsening
2017       // code during first IGVN before EA. Replace coarsened flag
2018       // to eliminate all associated locks/unlocks.
2019 #ifdef ASSERT
2020       this->log_lock_optimization(phase->C, "eliminate_lock_set_non_esc2");
2021 #endif
2022       this->set_non_esc_obj();
2023     }
2024   }
2025   return result;
2026 }
2027 
2028 const char * AbstractLockNode::kind_as_string() const {
2029   return is_coarsened()   ? "coarsened" :
2030          is_nested()      ? "nested" :
2031          is_non_esc_obj() ? "non_escaping" :
2032          "?";
2033 }
2034 
2035 void AbstractLockNode::log_lock_optimization(Compile *C, const char * tag)  const {
2036   if (C == NULL) {
2037     return;
2038   }
2039   CompileLog* log = C->log();
2040   if (log != NULL) {
2041     log->begin_head("%s lock='%d' compile_id='%d' class_id='%s' kind='%s'",
2042           tag, is_Lock(), C->compile_id(),
2043           is_Unlock() ? "unlock" : is_Lock() ? "lock" : "?",
2044           kind_as_string());
2045     log->stamp();
2046     log->end_head();
2047     JVMState* p = is_Unlock() ? (as_Unlock()->dbg_jvms()) : jvms();
2048     while (p != NULL) {
2049       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
2050       p = p->caller();
2051     }
2052     log->tail(tag);
2053   }
2054 }
2055 
2056 bool CallNode::may_modify_arraycopy_helper(const TypeOopPtr* dest_t, const TypeOopPtr *t_oop, PhaseTransform *phase) {
2057   if (dest_t->is_known_instance() && t_oop->is_known_instance()) {
2058     return dest_t->instance_id() == t_oop->instance_id();
2059   }
2060 
2061   if (dest_t->isa_instptr() && !dest_t->klass()->equals(phase->C->env()->Object_klass())) {
2062     // clone
2063     if (t_oop->isa_aryptr()) {
2064       return false;
2065     }
2066     if (!t_oop->isa_instptr()) {
2067       return true;
2068     }
2069     if (dest_t->klass()->is_subtype_of(t_oop->klass()) || t_oop->klass()->is_subtype_of(dest_t->klass())) {
2070       return true;
2071     }
2072     // unrelated
2073     return false;
2074   }
2075 
2076   if (dest_t->isa_aryptr()) {
2077     // arraycopy or array clone
2078     if (t_oop->isa_instptr()) {
2079       return false;
2080     }
2081     if (!t_oop->isa_aryptr()) {
2082       return true;
2083     }
2084 
2085     const Type* elem = dest_t->is_aryptr()->elem();
2086     if (elem == Type::BOTTOM) {
2087       // An array but we don't know what elements are
2088       return true;
2089     }
2090 
2091     dest_t = dest_t->add_offset(Type::OffsetBot)->is_oopptr();
2092     uint dest_alias = phase->C->get_alias_index(dest_t);
2093     uint t_oop_alias = phase->C->get_alias_index(t_oop);
2094 
2095     return dest_alias == t_oop_alias;
2096   }
2097 
2098   return true;
2099 }
2100