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