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