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