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