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