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