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