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