1 /*
   2  * Copyright (c) 2000, 2015, 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 "ci/bcEscapeAnalyzer.hpp"
  27 #include "ci/ciCallSite.hpp"
  28 #include "ci/ciObjArray.hpp"
  29 #include "ci/ciMemberName.hpp"
  30 #include "ci/ciMethodHandle.hpp"
  31 #include "classfile/javaClasses.hpp"
  32 #include "compiler/compileLog.hpp"
  33 #include "opto/addnode.hpp"
  34 #include "opto/callGenerator.hpp"
  35 #include "opto/callnode.hpp"
  36 #include "opto/castnode.hpp"
  37 #include "opto/cfgnode.hpp"
  38 #include "opto/parse.hpp"
  39 #include "opto/rootnode.hpp"
  40 #include "opto/runtime.hpp"
  41 #include "opto/subnode.hpp"
  42 #include "runtime/sharedRuntime.hpp"
  43 #if INCLUDE_SHENANDOAHGC
  44 #include "gc/shenandoah/c2/shenandoahSupport.hpp"
  45 #endif
  46 
  47 // Utility function.
  48 const TypeFunc* CallGenerator::tf() const {
  49   return TypeFunc::make(method());
  50 }
  51 
  52 bool CallGenerator::is_inlined_method_handle_intrinsic(JVMState* jvms, ciMethod* callee) {
  53   ciMethod* symbolic_info = jvms->method()->get_method_at_bci(jvms->bci());
  54   return symbolic_info->is_method_handle_intrinsic() && !callee->is_method_handle_intrinsic();
  55 }
  56 
  57 //-----------------------------ParseGenerator---------------------------------
  58 // Internal class which handles all direct bytecode traversal.
  59 class ParseGenerator : public InlineCallGenerator {
  60 private:
  61   bool  _is_osr;
  62   float _expected_uses;
  63 
  64 public:
  65   ParseGenerator(ciMethod* method, float expected_uses, bool is_osr = false)
  66     : InlineCallGenerator(method)
  67   {
  68     _is_osr        = is_osr;
  69     _expected_uses = expected_uses;
  70     assert(InlineTree::check_can_parse(method) == NULL, "parse must be possible");
  71   }
  72 
  73   virtual bool      is_parse() const           { return true; }
  74   virtual JVMState* generate(JVMState* jvms);
  75   int is_osr() { return _is_osr; }
  76 
  77 };
  78 
  79 JVMState* ParseGenerator::generate(JVMState* jvms) {
  80   Compile* C = Compile::current();
  81   C->print_inlining_update(this);
  82 
  83   if (is_osr()) {
  84     // The JVMS for a OSR has a single argument (see its TypeFunc).
  85     assert(jvms->depth() == 1, "no inline OSR");
  86   }
  87 
  88   if (C->failing()) {
  89     return NULL;  // bailing out of the compile; do not try to parse
  90   }
  91 
  92   Parse parser(jvms, method(), _expected_uses);
  93   // Grab signature for matching/allocation
  94 #ifdef ASSERT
  95   if (parser.tf() != (parser.depth() == 1 ? C->tf() : tf())) {
  96     MutexLockerEx ml(Compile_lock, Mutex::_no_safepoint_check_flag);
  97     assert(C->env()->system_dictionary_modification_counter_changed(),
  98            "Must invalidate if TypeFuncs differ");
  99   }
 100 #endif
 101 
 102   GraphKit& exits = parser.exits();
 103 
 104   if (C->failing()) {
 105     while (exits.pop_exception_state() != NULL) ;
 106     return NULL;
 107   }
 108 
 109   assert(exits.jvms()->same_calls_as(jvms), "sanity");
 110 
 111   // Simply return the exit state of the parser,
 112   // augmented by any exceptional states.
 113   return exits.transfer_exceptions_into_jvms();
 114 }
 115 
 116 //---------------------------DirectCallGenerator------------------------------
 117 // Internal class which handles all out-of-line calls w/o receiver type checks.
 118 class DirectCallGenerator : public CallGenerator {
 119  private:
 120   CallStaticJavaNode* _call_node;
 121   // Force separate memory and I/O projections for the exceptional
 122   // paths to facilitate late inlinig.
 123   bool                _separate_io_proj;
 124 
 125  public:
 126   DirectCallGenerator(ciMethod* method, bool separate_io_proj)
 127     : CallGenerator(method),
 128       _separate_io_proj(separate_io_proj)
 129   {
 130   }
 131   virtual JVMState* generate(JVMState* jvms);
 132 
 133   CallStaticJavaNode* call_node() const { return _call_node; }
 134 };
 135 
 136 JVMState* DirectCallGenerator::generate(JVMState* jvms) {
 137   GraphKit kit(jvms);
 138   kit.C->print_inlining_update(this);
 139   bool is_static = method()->is_static();
 140   address target = is_static ? SharedRuntime::get_resolve_static_call_stub()
 141                              : SharedRuntime::get_resolve_opt_virtual_call_stub();
 142 
 143   if (kit.C->log() != NULL) {
 144     kit.C->log()->elem("direct_call bci='%d'", jvms->bci());
 145   }
 146 
 147   CallStaticJavaNode *call = new CallStaticJavaNode(kit.C, tf(), target, method(), kit.bci());
 148   if (is_inlined_method_handle_intrinsic(jvms, method())) {
 149     // To be able to issue a direct call and skip a call to MH.linkTo*/invokeBasic adapter,
 150     // additional information about the method being invoked should be attached
 151     // to the call site to make resolution logic work
 152     // (see SharedRuntime::resolve_static_call_C).
 153     call->set_override_symbolic_info(true);
 154   }
 155   _call_node = call;  // Save the call node in case we need it later
 156   if (!is_static) {
 157     // Make an explicit receiver null_check as part of this call.
 158     // Since we share a map with the caller, his JVMS gets adjusted.
 159     kit.null_check_receiver_before_call(method());
 160     if (kit.stopped()) {
 161       // And dump it back to the caller, decorated with any exceptions:
 162       return kit.transfer_exceptions_into_jvms();
 163     }
 164     // Mark the call node as virtual, sort of:
 165     call->set_optimized_virtual(true);
 166     if (method()->is_method_handle_intrinsic() ||
 167         method()->is_compiled_lambda_form()) {
 168       call->set_method_handle_invoke(true);
 169     }
 170   }
 171   kit.set_arguments_for_java_call(call);
 172   kit.set_edges_for_java_call(call, false, _separate_io_proj);
 173   Node* ret = kit.set_results_for_java_call(call, _separate_io_proj);
 174   kit.push_node(method()->return_type()->basic_type(), ret);
 175   return kit.transfer_exceptions_into_jvms();
 176 }
 177 
 178 //--------------------------VirtualCallGenerator------------------------------
 179 // Internal class which handles all out-of-line calls checking receiver type.
 180 class VirtualCallGenerator : public CallGenerator {
 181 private:
 182   int _vtable_index;
 183 public:
 184   VirtualCallGenerator(ciMethod* method, int vtable_index)
 185     : CallGenerator(method), _vtable_index(vtable_index)
 186   {
 187     assert(vtable_index == Method::invalid_vtable_index ||
 188            vtable_index >= 0, "either invalid or usable");
 189   }
 190   virtual bool      is_virtual() const          { return true; }
 191   virtual JVMState* generate(JVMState* jvms);
 192 };
 193 
 194 JVMState* VirtualCallGenerator::generate(JVMState* jvms) {
 195   GraphKit kit(jvms);
 196   Node* receiver = kit.argument(0);
 197 
 198   kit.C->print_inlining_update(this);
 199 
 200   if (kit.C->log() != NULL) {
 201     kit.C->log()->elem("virtual_call bci='%d'", jvms->bci());
 202   }
 203 
 204   // If the receiver is a constant null, do not torture the system
 205   // by attempting to call through it.  The compile will proceed
 206   // correctly, but may bail out in final_graph_reshaping, because
 207   // the call instruction will have a seemingly deficient out-count.
 208   // (The bailout says something misleading about an "infinite loop".)
 209   if (kit.gvn().type(receiver)->higher_equal(TypePtr::NULL_PTR)) {
 210     assert(Bytecodes::is_invoke(kit.java_bc()), "%d: %s", kit.java_bc(), Bytecodes::name(kit.java_bc()));
 211     ciMethod* declared_method = kit.method()->get_method_at_bci(kit.bci());
 212     int arg_size = declared_method->signature()->arg_size_for_bc(kit.java_bc());
 213     kit.inc_sp(arg_size);  // restore arguments
 214     kit.uncommon_trap(Deoptimization::Reason_null_check,
 215                       Deoptimization::Action_none,
 216                       NULL, "null receiver");
 217     return kit.transfer_exceptions_into_jvms();
 218   }
 219 
 220   // Ideally we would unconditionally do a null check here and let it
 221   // be converted to an implicit check based on profile information.
 222   // However currently the conversion to implicit null checks in
 223   // Block::implicit_null_check() only looks for loads and stores, not calls.
 224   ciMethod *caller = kit.method();
 225   ciMethodData *caller_md = (caller == NULL) ? NULL : caller->method_data();
 226   if (!UseInlineCaches || !ImplicitNullChecks || !os::zero_page_read_protected() ||
 227        ((ImplicitNullCheckThreshold > 0) && caller_md &&
 228        (caller_md->trap_count(Deoptimization::Reason_null_check)
 229        >= (uint)ImplicitNullCheckThreshold))) {
 230     // Make an explicit receiver null_check as part of this call.
 231     // Since we share a map with the caller, his JVMS gets adjusted.
 232     receiver = kit.null_check_receiver_before_call(method());
 233     if (kit.stopped()) {
 234       // And dump it back to the caller, decorated with any exceptions:
 235       return kit.transfer_exceptions_into_jvms();
 236     }
 237   }
 238 
 239   assert(!method()->is_static(), "virtual call must not be to static");
 240   assert(!method()->is_final(), "virtual call should not be to final");
 241   assert(!method()->is_private(), "virtual call should not be to private");
 242   assert(_vtable_index == Method::invalid_vtable_index || !UseInlineCaches,
 243          "no vtable calls if +UseInlineCaches ");
 244   address target = SharedRuntime::get_resolve_virtual_call_stub();
 245   // Normal inline cache used for call
 246   CallDynamicJavaNode *call = new CallDynamicJavaNode(tf(), target, method(), _vtable_index, kit.bci());
 247   if (is_inlined_method_handle_intrinsic(jvms, method())) {
 248     // To be able to issue a direct call (optimized virtual or virtual)
 249     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
 250     // about the method being invoked should be attached to the call site to
 251     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
 252     call->set_override_symbolic_info(true);
 253   }
 254   kit.set_arguments_for_java_call(call);
 255   kit.set_edges_for_java_call(call);
 256   Node* ret = kit.set_results_for_java_call(call);
 257   kit.push_node(method()->return_type()->basic_type(), ret);
 258 
 259   // Represent the effect of an implicit receiver null_check
 260   // as part of this call.  Since we share a map with the caller,
 261   // his JVMS gets adjusted.
 262   kit.cast_not_null(receiver);
 263   return kit.transfer_exceptions_into_jvms();
 264 }
 265 
 266 CallGenerator* CallGenerator::for_inline(ciMethod* m, float expected_uses) {
 267   if (InlineTree::check_can_parse(m) != NULL)  return NULL;
 268   return new ParseGenerator(m, expected_uses);
 269 }
 270 
 271 // As a special case, the JVMS passed to this CallGenerator is
 272 // for the method execution already in progress, not just the JVMS
 273 // of the caller.  Thus, this CallGenerator cannot be mixed with others!
 274 CallGenerator* CallGenerator::for_osr(ciMethod* m, int osr_bci) {
 275   if (InlineTree::check_can_parse(m) != NULL)  return NULL;
 276   float past_uses = m->interpreter_invocation_count();
 277   float expected_uses = past_uses;
 278   return new ParseGenerator(m, expected_uses, true);
 279 }
 280 
 281 CallGenerator* CallGenerator::for_direct_call(ciMethod* m, bool separate_io_proj) {
 282   assert(!m->is_abstract(), "for_direct_call mismatch");
 283   return new DirectCallGenerator(m, separate_io_proj);
 284 }
 285 
 286 CallGenerator* CallGenerator::for_virtual_call(ciMethod* m, int vtable_index) {
 287   assert(!m->is_static(), "for_virtual_call mismatch");
 288   assert(!m->is_method_handle_intrinsic(), "should be a direct call");
 289   return new VirtualCallGenerator(m, vtable_index);
 290 }
 291 
 292 // Allow inlining decisions to be delayed
 293 class LateInlineCallGenerator : public DirectCallGenerator {
 294  private:
 295   // unique id for log compilation
 296   jlong _unique_id;
 297 
 298  protected:
 299   CallGenerator* _inline_cg;
 300   virtual bool do_late_inline_check(JVMState* jvms) { return true; }
 301 
 302  public:
 303   LateInlineCallGenerator(ciMethod* method, CallGenerator* inline_cg) :
 304     DirectCallGenerator(method, true), _unique_id(0), _inline_cg(inline_cg) {}
 305 
 306   virtual bool is_late_inline() const { return true; }
 307 
 308   // Convert the CallStaticJava into an inline
 309   virtual void do_late_inline();
 310 
 311   virtual JVMState* generate(JVMState* jvms) {
 312     Compile *C = Compile::current();
 313 
 314     C->log_inline_id(this);
 315 
 316     // Record that this call site should be revisited once the main
 317     // parse is finished.
 318     if (!is_mh_late_inline()) {
 319       C->add_late_inline(this);
 320     }
 321 
 322     // Emit the CallStaticJava and request separate projections so
 323     // that the late inlining logic can distinguish between fall
 324     // through and exceptional uses of the memory and io projections
 325     // as is done for allocations and macro expansion.
 326     return DirectCallGenerator::generate(jvms);
 327   }
 328 
 329   virtual void print_inlining_late(const char* msg) {
 330     CallNode* call = call_node();
 331     Compile* C = Compile::current();
 332     C->print_inlining_assert_ready();
 333     C->print_inlining(method(), call->jvms()->depth()-1, call->jvms()->bci(), msg);
 334     C->print_inlining_move_to(this);
 335     C->print_inlining_update_delayed(this);
 336   }
 337 
 338   virtual void set_unique_id(jlong id) {
 339     _unique_id = id;
 340   }
 341 
 342   virtual jlong unique_id() const {
 343     return _unique_id;
 344   }
 345 };
 346 
 347 void LateInlineCallGenerator::do_late_inline() {
 348   // Can't inline it
 349   CallStaticJavaNode* call = call_node();
 350   if (call == NULL || call->outcnt() == 0 ||
 351       call->in(0) == NULL || call->in(0)->is_top()) {
 352     return;
 353   }
 354 
 355   const TypeTuple *r = call->tf()->domain();
 356   for (int i1 = 0; i1 < method()->arg_size(); i1++) {
 357     if (call->in(TypeFunc::Parms + i1)->is_top() && r->field_at(TypeFunc::Parms + i1) != Type::HALF) {
 358       assert(Compile::current()->inlining_incrementally(), "shouldn't happen during parsing");
 359       return;
 360     }
 361   }
 362 
 363   if (call->in(TypeFunc::Memory)->is_top()) {
 364     assert(Compile::current()->inlining_incrementally(), "shouldn't happen during parsing");
 365     return;
 366   }
 367 
 368   // check for unreachable loop
 369   CallProjections callprojs;
 370   call->extract_projections(&callprojs, true);
 371   if (callprojs.fallthrough_catchproj == call->in(0) ||
 372       callprojs.catchall_catchproj == call->in(0) ||
 373       callprojs.fallthrough_memproj == call->in(TypeFunc::Memory) ||
 374       callprojs.catchall_memproj == call->in(TypeFunc::Memory) ||
 375       callprojs.fallthrough_ioproj == call->in(TypeFunc::I_O) ||
 376       callprojs.catchall_ioproj == call->in(TypeFunc::I_O) ||
 377       (callprojs.resproj != NULL && call->find_edge(callprojs.resproj) != -1) ||
 378       (callprojs.exobj != NULL && call->find_edge(callprojs.exobj) != -1)) {
 379     return;
 380   }
 381 
 382   Compile* C = Compile::current();
 383   // Remove inlined methods from Compiler's lists.
 384   if (call->is_macro()) {
 385     C->remove_macro_node(call);
 386   }
 387 
 388   // Make a clone of the JVMState that appropriate to use for driving a parse
 389   JVMState* old_jvms = call->jvms();
 390   JVMState* jvms = old_jvms->clone_shallow(C);
 391   uint size = call->req();
 392   SafePointNode* map = new SafePointNode(size, jvms);
 393   for (uint i1 = 0; i1 < size; i1++) {
 394     map->init_req(i1, call->in(i1));
 395   }
 396 
 397   // Make sure the state is a MergeMem for parsing.
 398   if (!map->in(TypeFunc::Memory)->is_MergeMem()) {
 399     Node* mem = MergeMemNode::make(map->in(TypeFunc::Memory));
 400     C->initial_gvn()->set_type_bottom(mem);
 401     map->set_req(TypeFunc::Memory, mem);
 402   }
 403 
 404   uint nargs = method()->arg_size();
 405   // blow away old call arguments
 406   Node* top = C->top();
 407   for (uint i1 = 0; i1 < nargs; i1++) {
 408     map->set_req(TypeFunc::Parms + i1, top);
 409   }
 410   jvms->set_map(map);
 411 
 412   // Make enough space in the expression stack to transfer
 413   // the incoming arguments and return value.
 414   map->ensure_stack(jvms, jvms->method()->max_stack());
 415   for (uint i1 = 0; i1 < nargs; i1++) {
 416     map->set_argument(jvms, i1, call->in(TypeFunc::Parms + i1));
 417   }
 418 
 419   C->print_inlining_assert_ready();
 420 
 421   C->print_inlining_move_to(this);
 422 
 423   C->log_late_inline(this);
 424 
 425   // This check is done here because for_method_handle_inline() method
 426   // needs jvms for inlined state.
 427   if (!do_late_inline_check(jvms)) {
 428     map->disconnect_inputs(NULL, C);
 429     return;
 430   }
 431 
 432   // Setup default node notes to be picked up by the inlining
 433   Node_Notes* old_nn = C->node_notes_at(call->_idx);
 434   if (old_nn != NULL) {
 435     Node_Notes* entry_nn = old_nn->clone(C);
 436     entry_nn->set_jvms(jvms);
 437     C->set_default_node_notes(entry_nn);
 438   }
 439 
 440   // Now perform the inlining using the synthesized JVMState
 441   JVMState* new_jvms = _inline_cg->generate(jvms);
 442   if (new_jvms == NULL)  return;  // no change
 443   if (C->failing())      return;
 444 
 445   // Capture any exceptional control flow
 446   GraphKit kit(new_jvms);
 447 
 448   // Find the result object
 449   Node* result = C->top();
 450   int   result_size = method()->return_type()->size();
 451   if (result_size != 0 && !kit.stopped()) {
 452     result = (result_size == 1) ? kit.pop() : kit.pop_pair();
 453   }
 454 
 455   C->set_has_loops(C->has_loops() || _inline_cg->method()->has_loops());
 456   C->env()->notice_inlined_method(_inline_cg->method());
 457   C->set_inlining_progress(true);
 458 
 459   kit.replace_call(call, result, true);
 460 }
 461 
 462 
 463 CallGenerator* CallGenerator::for_late_inline(ciMethod* method, CallGenerator* inline_cg) {
 464   return new LateInlineCallGenerator(method, inline_cg);
 465 }
 466 
 467 class LateInlineMHCallGenerator : public LateInlineCallGenerator {
 468   ciMethod* _caller;
 469   int _attempt;
 470   bool _input_not_const;
 471 
 472   virtual bool do_late_inline_check(JVMState* jvms);
 473   virtual bool already_attempted() const { return _attempt > 0; }
 474 
 475  public:
 476   LateInlineMHCallGenerator(ciMethod* caller, ciMethod* callee, bool input_not_const) :
 477     LateInlineCallGenerator(callee, NULL), _caller(caller), _attempt(0), _input_not_const(input_not_const) {}
 478 
 479   virtual bool is_mh_late_inline() const { return true; }
 480 
 481   virtual JVMState* generate(JVMState* jvms) {
 482     JVMState* new_jvms = LateInlineCallGenerator::generate(jvms);
 483 
 484     Compile* C = Compile::current();
 485     if (_input_not_const) {
 486       // inlining won't be possible so no need to enqueue right now.
 487       call_node()->set_generator(this);
 488     } else {
 489       C->add_late_inline(this);
 490     }
 491     return new_jvms;
 492   }
 493 };
 494 
 495 bool LateInlineMHCallGenerator::do_late_inline_check(JVMState* jvms) {
 496 
 497   CallGenerator* cg = for_method_handle_inline(jvms, _caller, method(), _input_not_const);
 498 
 499   Compile::current()->print_inlining_update_delayed(this);
 500 
 501   if (!_input_not_const) {
 502     _attempt++;
 503   }
 504 
 505   if (cg != NULL && cg->is_inline()) {
 506     assert(!cg->is_late_inline(), "we're doing late inlining");
 507     _inline_cg = cg;
 508     Compile::current()->dec_number_of_mh_late_inlines();
 509     return true;
 510   }
 511 
 512   call_node()->set_generator(this);
 513   return false;
 514 }
 515 
 516 CallGenerator* CallGenerator::for_mh_late_inline(ciMethod* caller, ciMethod* callee, bool input_not_const) {
 517   Compile::current()->inc_number_of_mh_late_inlines();
 518   CallGenerator* cg = new LateInlineMHCallGenerator(caller, callee, input_not_const);
 519   return cg;
 520 }
 521 
 522 class LateInlineStringCallGenerator : public LateInlineCallGenerator {
 523 
 524  public:
 525   LateInlineStringCallGenerator(ciMethod* method, CallGenerator* inline_cg) :
 526     LateInlineCallGenerator(method, inline_cg) {}
 527 
 528   virtual JVMState* generate(JVMState* jvms) {
 529     Compile *C = Compile::current();
 530 
 531     C->log_inline_id(this);
 532 
 533     C->add_string_late_inline(this);
 534 
 535     JVMState* new_jvms =  DirectCallGenerator::generate(jvms);
 536     return new_jvms;
 537   }
 538 
 539   virtual bool is_string_late_inline() const { return true; }
 540 };
 541 
 542 CallGenerator* CallGenerator::for_string_late_inline(ciMethod* method, CallGenerator* inline_cg) {
 543   return new LateInlineStringCallGenerator(method, inline_cg);
 544 }
 545 
 546 class LateInlineBoxingCallGenerator : public LateInlineCallGenerator {
 547 
 548  public:
 549   LateInlineBoxingCallGenerator(ciMethod* method, CallGenerator* inline_cg) :
 550     LateInlineCallGenerator(method, inline_cg) {}
 551 
 552   virtual JVMState* generate(JVMState* jvms) {
 553     Compile *C = Compile::current();
 554 
 555     C->log_inline_id(this);
 556 
 557     C->add_boxing_late_inline(this);
 558 
 559     JVMState* new_jvms =  DirectCallGenerator::generate(jvms);
 560     return new_jvms;
 561   }
 562 };
 563 
 564 CallGenerator* CallGenerator::for_boxing_late_inline(ciMethod* method, CallGenerator* inline_cg) {
 565   return new LateInlineBoxingCallGenerator(method, inline_cg);
 566 }
 567 
 568 //---------------------------WarmCallGenerator--------------------------------
 569 // Internal class which handles initial deferral of inlining decisions.
 570 class WarmCallGenerator : public CallGenerator {
 571   WarmCallInfo*   _call_info;
 572   CallGenerator*  _if_cold;
 573   CallGenerator*  _if_hot;
 574   bool            _is_virtual;   // caches virtuality of if_cold
 575   bool            _is_inline;    // caches inline-ness of if_hot
 576 
 577 public:
 578   WarmCallGenerator(WarmCallInfo* ci,
 579                     CallGenerator* if_cold,
 580                     CallGenerator* if_hot)
 581     : CallGenerator(if_cold->method())
 582   {
 583     assert(method() == if_hot->method(), "consistent choices");
 584     _call_info  = ci;
 585     _if_cold    = if_cold;
 586     _if_hot     = if_hot;
 587     _is_virtual = if_cold->is_virtual();
 588     _is_inline  = if_hot->is_inline();
 589   }
 590 
 591   virtual bool      is_inline() const           { return _is_inline; }
 592   virtual bool      is_virtual() const          { return _is_virtual; }
 593   virtual bool      is_deferred() const         { return true; }
 594 
 595   virtual JVMState* generate(JVMState* jvms);
 596 };
 597 
 598 
 599 CallGenerator* CallGenerator::for_warm_call(WarmCallInfo* ci,
 600                                             CallGenerator* if_cold,
 601                                             CallGenerator* if_hot) {
 602   return new WarmCallGenerator(ci, if_cold, if_hot);
 603 }
 604 
 605 JVMState* WarmCallGenerator::generate(JVMState* jvms) {
 606   Compile* C = Compile::current();
 607   C->print_inlining_update(this);
 608 
 609   if (C->log() != NULL) {
 610     C->log()->elem("warm_call bci='%d'", jvms->bci());
 611   }
 612   jvms = _if_cold->generate(jvms);
 613   if (jvms != NULL) {
 614     Node* m = jvms->map()->control();
 615     if (m->is_CatchProj()) m = m->in(0);  else m = C->top();
 616     if (m->is_Catch())     m = m->in(0);  else m = C->top();
 617     if (m->is_Proj())      m = m->in(0);  else m = C->top();
 618     if (m->is_CallJava()) {
 619       _call_info->set_call(m->as_Call());
 620       _call_info->set_hot_cg(_if_hot);
 621 #ifndef PRODUCT
 622       if (PrintOpto || PrintOptoInlining) {
 623         tty->print_cr("Queueing for warm inlining at bci %d:", jvms->bci());
 624         tty->print("WCI: ");
 625         _call_info->print();
 626       }
 627 #endif
 628       _call_info->set_heat(_call_info->compute_heat());
 629       C->set_warm_calls(_call_info->insert_into(C->warm_calls()));
 630     }
 631   }
 632   return jvms;
 633 }
 634 
 635 void WarmCallInfo::make_hot() {
 636   Unimplemented();
 637 }
 638 
 639 void WarmCallInfo::make_cold() {
 640   // No action:  Just dequeue.
 641 }
 642 
 643 
 644 //------------------------PredictedCallGenerator------------------------------
 645 // Internal class which handles all out-of-line calls checking receiver type.
 646 class PredictedCallGenerator : public CallGenerator {
 647   ciKlass*       _predicted_receiver;
 648   CallGenerator* _if_missed;
 649   CallGenerator* _if_hit;
 650   float          _hit_prob;
 651 
 652 public:
 653   PredictedCallGenerator(ciKlass* predicted_receiver,
 654                          CallGenerator* if_missed,
 655                          CallGenerator* if_hit, float hit_prob)
 656     : CallGenerator(if_missed->method())
 657   {
 658     // The call profile data may predict the hit_prob as extreme as 0 or 1.
 659     // Remove the extremes values from the range.
 660     if (hit_prob > PROB_MAX)   hit_prob = PROB_MAX;
 661     if (hit_prob < PROB_MIN)   hit_prob = PROB_MIN;
 662 
 663     _predicted_receiver = predicted_receiver;
 664     _if_missed          = if_missed;
 665     _if_hit             = if_hit;
 666     _hit_prob           = hit_prob;
 667   }
 668 
 669   virtual bool      is_virtual()   const    { return true; }
 670   virtual bool      is_inline()    const    { return _if_hit->is_inline(); }
 671   virtual bool      is_deferred()  const    { return _if_hit->is_deferred(); }
 672 
 673   virtual JVMState* generate(JVMState* jvms);
 674 };
 675 
 676 
 677 CallGenerator* CallGenerator::for_predicted_call(ciKlass* predicted_receiver,
 678                                                  CallGenerator* if_missed,
 679                                                  CallGenerator* if_hit,
 680                                                  float hit_prob) {
 681   return new PredictedCallGenerator(predicted_receiver, if_missed, if_hit, hit_prob);
 682 }
 683 
 684 
 685 JVMState* PredictedCallGenerator::generate(JVMState* jvms) {
 686   GraphKit kit(jvms);
 687   kit.C->print_inlining_update(this);
 688   PhaseGVN& gvn = kit.gvn();
 689   // We need an explicit receiver null_check before checking its type.
 690   // We share a map with the caller, so his JVMS gets adjusted.
 691   Node* receiver = kit.argument(0);
 692   CompileLog* log = kit.C->log();
 693   if (log != NULL) {
 694     log->elem("predicted_call bci='%d' klass='%d'",
 695               jvms->bci(), log->identify(_predicted_receiver));
 696   }
 697 
 698   receiver = kit.null_check_receiver_before_call(method());
 699   if (kit.stopped()) {
 700     return kit.transfer_exceptions_into_jvms();
 701   }
 702 
 703   // Make a copy of the replaced nodes in case we need to restore them
 704   ReplacedNodes replaced_nodes = kit.map()->replaced_nodes();
 705   replaced_nodes.clone();
 706 
 707   Node* exact_receiver = receiver;  // will get updated in place...
 708   Node* slow_ctl = kit.type_check_receiver(receiver,
 709                                            _predicted_receiver, _hit_prob,
 710                                            &exact_receiver);
 711 
 712   SafePointNode* slow_map = NULL;
 713   JVMState* slow_jvms = NULL;
 714   { PreserveJVMState pjvms(&kit);
 715     kit.set_control(slow_ctl);
 716     if (!kit.stopped()) {
 717       slow_jvms = _if_missed->generate(kit.sync_jvms());
 718       if (kit.failing())
 719         return NULL;  // might happen because of NodeCountInliningCutoff
 720       assert(slow_jvms != NULL, "must be");
 721       kit.add_exception_states_from(slow_jvms);
 722       kit.set_map(slow_jvms->map());
 723       if (!kit.stopped())
 724         slow_map = kit.stop();
 725     }
 726   }
 727 
 728   if (kit.stopped()) {
 729     // Instance exactly does not matches the desired type.
 730     kit.set_jvms(slow_jvms);
 731     return kit.transfer_exceptions_into_jvms();
 732   }
 733 
 734   // fall through if the instance exactly matches the desired type
 735   kit.replace_in_map(receiver, exact_receiver);
 736 
 737   // Make the hot call:
 738   JVMState* new_jvms = _if_hit->generate(kit.sync_jvms());
 739   if (new_jvms == NULL) {
 740     // Inline failed, so make a direct call.
 741     assert(_if_hit->is_inline(), "must have been a failed inline");
 742     CallGenerator* cg = CallGenerator::for_direct_call(_if_hit->method());
 743     new_jvms = cg->generate(kit.sync_jvms());
 744   }
 745   kit.add_exception_states_from(new_jvms);
 746   kit.set_jvms(new_jvms);
 747 
 748   // Need to merge slow and fast?
 749   if (slow_map == NULL) {
 750     // The fast path is the only path remaining.
 751     return kit.transfer_exceptions_into_jvms();
 752   }
 753 
 754   if (kit.stopped()) {
 755     // Inlined method threw an exception, so it's just the slow path after all.
 756     kit.set_jvms(slow_jvms);
 757     return kit.transfer_exceptions_into_jvms();
 758   }
 759 
 760   // There are 2 branches and the replaced nodes are only valid on
 761   // one: restore the replaced nodes to what they were before the
 762   // branch.
 763   kit.map()->set_replaced_nodes(replaced_nodes);
 764 
 765   // Finish the diamond.
 766   kit.C->set_has_split_ifs(true); // Has chance for split-if optimization
 767   RegionNode* region = new RegionNode(3);
 768   region->init_req(1, kit.control());
 769   region->init_req(2, slow_map->control());
 770   kit.set_control(gvn.transform(region));
 771   Node* iophi = PhiNode::make(region, kit.i_o(), Type::ABIO);
 772   iophi->set_req(2, slow_map->i_o());
 773   kit.set_i_o(gvn.transform(iophi));
 774   // Merge memory
 775   kit.merge_memory(slow_map->merged_memory(), region, 2);
 776   // Transform new memory Phis.
 777   for (MergeMemStream mms(kit.merged_memory()); mms.next_non_empty();) {
 778     Node* phi = mms.memory();
 779     if (phi->is_Phi() && phi->in(0) == region) {
 780       mms.set_memory(gvn.transform(phi));
 781     }
 782   }
 783   uint tos = kit.jvms()->stkoff() + kit.sp();
 784   uint limit = slow_map->req();
 785   for (uint i = TypeFunc::Parms; i < limit; i++) {
 786     // Skip unused stack slots; fast forward to monoff();
 787     if (i == tos) {
 788       i = kit.jvms()->monoff();
 789       if( i >= limit ) break;
 790     }
 791     Node* m = kit.map()->in(i);
 792     Node* n = slow_map->in(i);
 793     if (m != n) {
 794       const Type* t = gvn.type(m)->meet_speculative(gvn.type(n));
 795       Node* phi = PhiNode::make(region, m, t);
 796       phi->set_req(2, n);
 797       kit.map()->set_req(i, gvn.transform(phi));
 798     }
 799   }
 800   return kit.transfer_exceptions_into_jvms();
 801 }
 802 
 803 
 804 CallGenerator* CallGenerator::for_method_handle_call(JVMState* jvms, ciMethod* caller, ciMethod* callee, bool delayed_forbidden) {
 805   assert(callee->is_method_handle_intrinsic(), "for_method_handle_call mismatch");
 806   bool input_not_const;
 807   CallGenerator* cg = CallGenerator::for_method_handle_inline(jvms, caller, callee, input_not_const);
 808   Compile* C = Compile::current();
 809   if (cg != NULL) {
 810     if (!delayed_forbidden && AlwaysIncrementalInline) {
 811       return CallGenerator::for_late_inline(callee, cg);
 812     } else {
 813       return cg;
 814     }
 815   }
 816   int bci = jvms->bci();
 817   ciCallProfile profile = caller->call_profile_at_bci(bci);
 818   int call_site_count = caller->scale_count(profile.count());
 819 
 820   if (IncrementalInline && call_site_count > 0 &&
 821       (input_not_const || !C->inlining_incrementally() || C->over_inlining_cutoff())) {
 822     return CallGenerator::for_mh_late_inline(caller, callee, input_not_const);
 823   } else {
 824     // Out-of-line call.
 825     return CallGenerator::for_direct_call(callee);
 826   }
 827 }
 828 
 829 CallGenerator* CallGenerator::for_method_handle_inline(JVMState* jvms, ciMethod* caller, ciMethod* callee, bool& input_not_const) {
 830   GraphKit kit(jvms);
 831   PhaseGVN& gvn = kit.gvn();
 832   Compile* C = kit.C;
 833   vmIntrinsics::ID iid = callee->intrinsic_id();
 834   input_not_const = true;
 835   switch (iid) {
 836   case vmIntrinsics::_invokeBasic:
 837     {
 838       // Get MethodHandle receiver:
 839       Node* receiver = kit.argument(0);
 840  #if INCLUDE_SHENANDOAHGC
 841       receiver = ShenandoahBarrierNode::skip_through_barrier(receiver);
 842  #endif
 843       if (receiver->Opcode() == Op_ConP) {
 844         input_not_const = false;
 845         const TypeOopPtr* oop_ptr = receiver->bottom_type()->is_oopptr();
 846         ciMethod* target = oop_ptr->const_oop()->as_method_handle()->get_vmtarget();
 847         const int vtable_index = Method::invalid_vtable_index;
 848 
 849         if (!ciMethod::is_consistent_info(callee, target)) {
 850           print_inlining_failure(C, callee, jvms->depth() - 1, jvms->bci(),
 851                                  "signatures mismatch");
 852           return NULL;
 853         }
 854 
 855         CallGenerator* cg = C->call_generator(target, vtable_index,
 856                                               false /* call_does_dispatch */,
 857                                               jvms,
 858                                               true /* allow_inline */,
 859                                               PROB_ALWAYS);
 860         return cg;
 861       } else {
 862         print_inlining_failure(C, callee, jvms->depth() - 1, jvms->bci(),
 863                                "receiver not constant");
 864       }
 865     }
 866     break;
 867 
 868   case vmIntrinsics::_linkToVirtual:
 869   case vmIntrinsics::_linkToStatic:
 870 
 871   case vmIntrinsics::_linkToSpecial:
 872   case vmIntrinsics::_linkToInterface:
 873     {
 874       // Get MemberName argument:
 875       Node* member_name = kit.argument(callee->arg_size() - 1);
 876  #if INCLUDE_SHENANDOAHGC
 877       member_name = ShenandoahBarrierNode::skip_through_barrier(member_name);
 878  #endif
 879       if (member_name->Opcode() == Op_ConP) {
 880         input_not_const = false;
 881         const TypeOopPtr* oop_ptr = member_name->bottom_type()->is_oopptr();
 882         ciMethod* target = oop_ptr->const_oop()->as_member_name()->get_vmtarget();
 883 
 884         if (!ciMethod::is_consistent_info(callee, target)) {
 885           print_inlining_failure(C, callee, jvms->depth() - 1, jvms->bci(),
 886                                  "signatures mismatch");
 887           return NULL;
 888         }
 889 
 890         // In lambda forms we erase signature types to avoid resolving issues
 891         // involving class loaders.  When we optimize a method handle invoke
 892         // to a direct call we must cast the receiver and arguments to its
 893         // actual types.
 894         ciSignature* signature = target->signature();
 895         const int receiver_skip = target->is_static() ? 0 : 1;
 896         // Cast receiver to its type.
 897         if (!target->is_static()) {
 898           Node* arg = kit.argument(0);
 899           const TypeOopPtr* arg_type = arg->bottom_type()->isa_oopptr();
 900           const Type*       sig_type = TypeOopPtr::make_from_klass(signature->accessing_klass());
 901           if (arg_type != NULL && !arg_type->higher_equal(sig_type)) {
 902             Node* cast_obj = gvn.transform(new CheckCastPPNode(kit.control(), arg, sig_type));
 903             kit.set_argument(0, cast_obj);
 904           }
 905         }
 906         // Cast reference arguments to its type.
 907         for (int i = 0, j = 0; i < signature->count(); i++) {
 908           ciType* t = signature->type_at(i);
 909           if (t->is_klass()) {
 910             Node* arg = kit.argument(receiver_skip + j);
 911             const TypeOopPtr* arg_type = arg->bottom_type()->isa_oopptr();
 912             const Type*       sig_type = TypeOopPtr::make_from_klass(t->as_klass());
 913             if (arg_type != NULL && !arg_type->higher_equal(sig_type)) {
 914               Node* cast_obj = gvn.transform(new CheckCastPPNode(kit.control(), arg, sig_type));
 915               kit.set_argument(receiver_skip + j, cast_obj);
 916             }
 917           }
 918           j += t->size();  // long and double take two slots
 919         }
 920 
 921         // Try to get the most accurate receiver type
 922         const bool is_virtual              = (iid == vmIntrinsics::_linkToVirtual);
 923         const bool is_virtual_or_interface = (is_virtual || iid == vmIntrinsics::_linkToInterface);
 924         int  vtable_index       = Method::invalid_vtable_index;
 925         bool call_does_dispatch = false;
 926 
 927         ciKlass* speculative_receiver_type = NULL;
 928         if (is_virtual_or_interface) {
 929           ciInstanceKlass* klass = target->holder();
 930           Node*             receiver_node = kit.argument(0);
 931           const TypeOopPtr* receiver_type = gvn.type(receiver_node)->isa_oopptr();
 932           // call_does_dispatch and vtable_index are out-parameters.  They might be changed.
 933           // optimize_virtual_call() takes 2 different holder
 934           // arguments for a corner case that doesn't apply here (see
 935           // Parse::do_call())
 936           target = C->optimize_virtual_call(caller, jvms->bci(), klass, klass,
 937                                             target, receiver_type, is_virtual,
 938                                             call_does_dispatch, vtable_index, // out-parameters
 939                                             false /* check_access */);
 940           // We lack profiling at this call but type speculation may
 941           // provide us with a type
 942           speculative_receiver_type = (receiver_type != NULL) ? receiver_type->speculative_type() : NULL;
 943         }
 944         CallGenerator* cg = C->call_generator(target, vtable_index, call_does_dispatch, jvms,
 945                                               !StressMethodHandleLinkerInlining /* allow_inline */,
 946                                               PROB_ALWAYS,
 947                                               speculative_receiver_type);
 948         return cg;
 949       } else {
 950         print_inlining_failure(C, callee, jvms->depth() - 1, jvms->bci(),
 951                                "member_name not constant");
 952       }
 953     }
 954     break;
 955 
 956   default:
 957     fatal("unexpected intrinsic %d: %s", iid, vmIntrinsics::name_at(iid));
 958     break;
 959   }
 960   return NULL;
 961 }
 962 
 963 
 964 //------------------------PredicatedIntrinsicGenerator------------------------------
 965 // Internal class which handles all predicated Intrinsic calls.
 966 class PredicatedIntrinsicGenerator : public CallGenerator {
 967   CallGenerator* _intrinsic;
 968   CallGenerator* _cg;
 969 
 970 public:
 971   PredicatedIntrinsicGenerator(CallGenerator* intrinsic,
 972                                CallGenerator* cg)
 973     : CallGenerator(cg->method())
 974   {
 975     _intrinsic = intrinsic;
 976     _cg        = cg;
 977   }
 978 
 979   virtual bool      is_virtual()   const    { return true; }
 980   virtual bool      is_inlined()   const    { return true; }
 981   virtual bool      is_intrinsic() const    { return true; }
 982 
 983   virtual JVMState* generate(JVMState* jvms);
 984 };
 985 
 986 
 987 CallGenerator* CallGenerator::for_predicated_intrinsic(CallGenerator* intrinsic,
 988                                                        CallGenerator* cg) {
 989   return new PredicatedIntrinsicGenerator(intrinsic, cg);
 990 }
 991 
 992 
 993 JVMState* PredicatedIntrinsicGenerator::generate(JVMState* jvms) {
 994   // The code we want to generate here is:
 995   //    if (receiver == NULL)
 996   //        uncommon_Trap
 997   //    if (predicate(0))
 998   //        do_intrinsic(0)
 999   //    else
1000   //    if (predicate(1))
1001   //        do_intrinsic(1)
1002   //    ...
1003   //    else
1004   //        do_java_comp
1005 
1006   GraphKit kit(jvms);
1007   PhaseGVN& gvn = kit.gvn();
1008 
1009   CompileLog* log = kit.C->log();
1010   if (log != NULL) {
1011     log->elem("predicated_intrinsic bci='%d' method='%d'",
1012               jvms->bci(), log->identify(method()));
1013   }
1014 
1015   if (!method()->is_static()) {
1016     // We need an explicit receiver null_check before checking its type in predicate.
1017     // We share a map with the caller, so his JVMS gets adjusted.
1018     Node* receiver = kit.null_check_receiver_before_call(method());
1019     if (kit.stopped()) {
1020       return kit.transfer_exceptions_into_jvms();
1021     }
1022   }
1023 
1024   int n_predicates = _intrinsic->predicates_count();
1025   assert(n_predicates > 0, "sanity");
1026 
1027   JVMState** result_jvms = NEW_RESOURCE_ARRAY(JVMState*, (n_predicates+1));
1028 
1029   // Region for normal compilation code if intrinsic failed.
1030   Node* slow_region = new RegionNode(1);
1031 
1032   int results = 0;
1033   for (int predicate = 0; (predicate < n_predicates) && !kit.stopped(); predicate++) {
1034 #ifdef ASSERT
1035     JVMState* old_jvms = kit.jvms();
1036     SafePointNode* old_map = kit.map();
1037     Node* old_io  = old_map->i_o();
1038     Node* old_mem = old_map->memory();
1039     Node* old_exc = old_map->next_exception();
1040 #endif
1041     Node* else_ctrl = _intrinsic->generate_predicate(kit.sync_jvms(), predicate);
1042 #ifdef ASSERT
1043     // Assert(no_new_memory && no_new_io && no_new_exceptions) after generate_predicate.
1044     assert(old_jvms == kit.jvms(), "generate_predicate should not change jvm state");
1045     SafePointNode* new_map = kit.map();
1046     assert(old_io  == new_map->i_o(), "generate_predicate should not change i_o");
1047     assert(old_mem == new_map->memory(), "generate_predicate should not change memory");
1048     assert(old_exc == new_map->next_exception(), "generate_predicate should not add exceptions");
1049 #endif
1050     if (!kit.stopped()) {
1051       PreserveJVMState pjvms(&kit);
1052       // Generate intrinsic code:
1053       JVMState* new_jvms = _intrinsic->generate(kit.sync_jvms());
1054       if (new_jvms == NULL) {
1055         // Intrinsic failed, use normal compilation path for this predicate.
1056         slow_region->add_req(kit.control());
1057       } else {
1058         kit.add_exception_states_from(new_jvms);
1059         kit.set_jvms(new_jvms);
1060         if (!kit.stopped()) {
1061           result_jvms[results++] = kit.jvms();
1062         }
1063       }
1064     }
1065     if (else_ctrl == NULL) {
1066       else_ctrl = kit.C->top();
1067     }
1068     kit.set_control(else_ctrl);
1069   }
1070   if (!kit.stopped()) {
1071     // Final 'else' after predicates.
1072     slow_region->add_req(kit.control());
1073   }
1074   if (slow_region->req() > 1) {
1075     PreserveJVMState pjvms(&kit);
1076     // Generate normal compilation code:
1077     kit.set_control(gvn.transform(slow_region));
1078     JVMState* new_jvms = _cg->generate(kit.sync_jvms());
1079     if (kit.failing())
1080       return NULL;  // might happen because of NodeCountInliningCutoff
1081     assert(new_jvms != NULL, "must be");
1082     kit.add_exception_states_from(new_jvms);
1083     kit.set_jvms(new_jvms);
1084     if (!kit.stopped()) {
1085       result_jvms[results++] = kit.jvms();
1086     }
1087   }
1088 
1089   if (results == 0) {
1090     // All paths ended in uncommon traps.
1091     (void) kit.stop();
1092     return kit.transfer_exceptions_into_jvms();
1093   }
1094 
1095   if (results == 1) { // Only one path
1096     kit.set_jvms(result_jvms[0]);
1097     return kit.transfer_exceptions_into_jvms();
1098   }
1099 
1100   // Merge all paths.
1101   kit.C->set_has_split_ifs(true); // Has chance for split-if optimization
1102   RegionNode* region = new RegionNode(results + 1);
1103   Node* iophi = PhiNode::make(region, kit.i_o(), Type::ABIO);
1104   for (int i = 0; i < results; i++) {
1105     JVMState* jvms = result_jvms[i];
1106     int path = i + 1;
1107     SafePointNode* map = jvms->map();
1108     region->init_req(path, map->control());
1109     iophi->set_req(path, map->i_o());
1110     if (i == 0) {
1111       kit.set_jvms(jvms);
1112     } else {
1113       kit.merge_memory(map->merged_memory(), region, path);
1114     }
1115   }
1116   kit.set_control(gvn.transform(region));
1117   kit.set_i_o(gvn.transform(iophi));
1118   // Transform new memory Phis.
1119   for (MergeMemStream mms(kit.merged_memory()); mms.next_non_empty();) {
1120     Node* phi = mms.memory();
1121     if (phi->is_Phi() && phi->in(0) == region) {
1122       mms.set_memory(gvn.transform(phi));
1123     }
1124   }
1125 
1126   // Merge debug info.
1127   Node** ins = NEW_RESOURCE_ARRAY(Node*, results);
1128   uint tos = kit.jvms()->stkoff() + kit.sp();
1129   Node* map = kit.map();
1130   uint limit = map->req();
1131   for (uint i = TypeFunc::Parms; i < limit; i++) {
1132     // Skip unused stack slots; fast forward to monoff();
1133     if (i == tos) {
1134       i = kit.jvms()->monoff();
1135       if( i >= limit ) break;
1136     }
1137     Node* n = map->in(i);
1138     ins[0] = n;
1139     const Type* t = gvn.type(n);
1140     bool needs_phi = false;
1141     for (int j = 1; j < results; j++) {
1142       JVMState* jvms = result_jvms[j];
1143       Node* jmap = jvms->map();
1144       Node* m = NULL;
1145       if (jmap->req() > i) {
1146         m = jmap->in(i);
1147         if (m != n) {
1148           needs_phi = true;
1149           t = t->meet_speculative(gvn.type(m));
1150         }
1151       }
1152       ins[j] = m;
1153     }
1154     if (needs_phi) {
1155       Node* phi = PhiNode::make(region, n, t);
1156       for (int j = 1; j < results; j++) {
1157         phi->set_req(j + 1, ins[j]);
1158       }
1159       map->set_req(i, gvn.transform(phi));
1160     }
1161   }
1162 
1163   return kit.transfer_exceptions_into_jvms();
1164 }
1165 
1166 //-------------------------UncommonTrapCallGenerator-----------------------------
1167 // Internal class which handles all out-of-line calls checking receiver type.
1168 class UncommonTrapCallGenerator : public CallGenerator {
1169   Deoptimization::DeoptReason _reason;
1170   Deoptimization::DeoptAction _action;
1171 
1172 public:
1173   UncommonTrapCallGenerator(ciMethod* m,
1174                             Deoptimization::DeoptReason reason,
1175                             Deoptimization::DeoptAction action)
1176     : CallGenerator(m)
1177   {
1178     _reason = reason;
1179     _action = action;
1180   }
1181 
1182   virtual bool      is_virtual() const          { ShouldNotReachHere(); return false; }
1183   virtual bool      is_trap() const             { return true; }
1184 
1185   virtual JVMState* generate(JVMState* jvms);
1186 };
1187 
1188 
1189 CallGenerator*
1190 CallGenerator::for_uncommon_trap(ciMethod* m,
1191                                  Deoptimization::DeoptReason reason,
1192                                  Deoptimization::DeoptAction action) {
1193   return new UncommonTrapCallGenerator(m, reason, action);
1194 }
1195 
1196 
1197 JVMState* UncommonTrapCallGenerator::generate(JVMState* jvms) {
1198   GraphKit kit(jvms);
1199   kit.C->print_inlining_update(this);
1200   // Take the trap with arguments pushed on the stack.  (Cf. null_check_receiver).
1201   // Callsite signature can be different from actual method being called (i.e _linkTo* sites).
1202   // Use callsite signature always.
1203   ciMethod* declared_method = kit.method()->get_method_at_bci(kit.bci());
1204   int nargs = declared_method->arg_size();
1205   kit.inc_sp(nargs);
1206   assert(nargs <= kit.sp() && kit.sp() <= jvms->stk_size(), "sane sp w/ args pushed");
1207   if (_reason == Deoptimization::Reason_class_check &&
1208       _action == Deoptimization::Action_maybe_recompile) {
1209     // Temp fix for 6529811
1210     // Don't allow uncommon_trap to override our decision to recompile in the event
1211     // of a class cast failure for a monomorphic call as it will never let us convert
1212     // the call to either bi-morphic or megamorphic and can lead to unc-trap loops
1213     bool keep_exact_action = true;
1214     kit.uncommon_trap(_reason, _action, NULL, "monomorphic vcall checkcast", false, keep_exact_action);
1215   } else {
1216     kit.uncommon_trap(_reason, _action);
1217   }
1218   return kit.transfer_exceptions_into_jvms();
1219 }
1220 
1221 // (Note:  Moved hook_up_call to GraphKit::set_edges_for_java_call.)
1222 
1223 // (Node:  Merged hook_up_exits into ParseGenerator::generate.)
1224 
1225 #define NODES_OVERHEAD_PER_METHOD (30.0)
1226 #define NODES_PER_BYTECODE (9.5)
1227 
1228 void WarmCallInfo::init(JVMState* call_site, ciMethod* call_method, ciCallProfile& profile, float prof_factor) {
1229   int call_count = profile.count();
1230   int code_size = call_method->code_size();
1231 
1232   // Expected execution count is based on the historical count:
1233   _count = call_count < 0 ? 1 : call_site->method()->scale_count(call_count, prof_factor);
1234 
1235   // Expected profit from inlining, in units of simple call-overheads.
1236   _profit = 1.0;
1237 
1238   // Expected work performed by the call in units of call-overheads.
1239   // %%% need an empirical curve fit for "work" (time in call)
1240   float bytecodes_per_call = 3;
1241   _work = 1.0 + code_size / bytecodes_per_call;
1242 
1243   // Expected size of compilation graph:
1244   // -XX:+PrintParseStatistics once reported:
1245   //  Methods seen: 9184  Methods parsed: 9184  Nodes created: 1582391
1246   //  Histogram of 144298 parsed bytecodes:
1247   // %%% Need an better predictor for graph size.
1248   _size = NODES_OVERHEAD_PER_METHOD + (NODES_PER_BYTECODE * code_size);
1249 }
1250 
1251 // is_cold:  Return true if the node should never be inlined.
1252 // This is true if any of the key metrics are extreme.
1253 bool WarmCallInfo::is_cold() const {
1254   if (count()  <  WarmCallMinCount)        return true;
1255   if (profit() <  WarmCallMinProfit)       return true;
1256   if (work()   >  WarmCallMaxWork)         return true;
1257   if (size()   >  WarmCallMaxSize)         return true;
1258   return false;
1259 }
1260 
1261 // is_hot:  Return true if the node should be inlined immediately.
1262 // This is true if any of the key metrics are extreme.
1263 bool WarmCallInfo::is_hot() const {
1264   assert(!is_cold(), "eliminate is_cold cases before testing is_hot");
1265   if (count()  >= HotCallCountThreshold)   return true;
1266   if (profit() >= HotCallProfitThreshold)  return true;
1267   if (work()   <= HotCallTrivialWork)      return true;
1268   if (size()   <= HotCallTrivialSize)      return true;
1269   return false;
1270 }
1271 
1272 // compute_heat:
1273 float WarmCallInfo::compute_heat() const {
1274   assert(!is_cold(), "compute heat only on warm nodes");
1275   assert(!is_hot(),  "compute heat only on warm nodes");
1276   int min_size = MAX2(0,   (int)HotCallTrivialSize);
1277   int max_size = MIN2(500, (int)WarmCallMaxSize);
1278   float method_size = (size() - min_size) / MAX2(1, max_size - min_size);
1279   float size_factor;
1280   if      (method_size < 0.05)  size_factor = 4;   // 2 sigmas better than avg.
1281   else if (method_size < 0.15)  size_factor = 2;   // 1 sigma better than avg.
1282   else if (method_size < 0.5)   size_factor = 1;   // better than avg.
1283   else                          size_factor = 0.5; // worse than avg.
1284   return (count() * profit() * size_factor);
1285 }
1286 
1287 bool WarmCallInfo::warmer_than(WarmCallInfo* that) {
1288   assert(this != that, "compare only different WCIs");
1289   assert(this->heat() != 0 && that->heat() != 0, "call compute_heat 1st");
1290   if (this->heat() > that->heat())   return true;
1291   if (this->heat() < that->heat())   return false;
1292   assert(this->heat() == that->heat(), "no NaN heat allowed");
1293   // Equal heat.  Break the tie some other way.
1294   if (!this->call() || !that->call())  return (address)this > (address)that;
1295   return this->call()->_idx > that->call()->_idx;
1296 }
1297 
1298 //#define UNINIT_NEXT ((WarmCallInfo*)badAddress)
1299 #define UNINIT_NEXT ((WarmCallInfo*)NULL)
1300 
1301 WarmCallInfo* WarmCallInfo::insert_into(WarmCallInfo* head) {
1302   assert(next() == UNINIT_NEXT, "not yet on any list");
1303   WarmCallInfo* prev_p = NULL;
1304   WarmCallInfo* next_p = head;
1305   while (next_p != NULL && next_p->warmer_than(this)) {
1306     prev_p = next_p;
1307     next_p = prev_p->next();
1308   }
1309   // Install this between prev_p and next_p.
1310   this->set_next(next_p);
1311   if (prev_p == NULL)
1312     head = this;
1313   else
1314     prev_p->set_next(this);
1315   return head;
1316 }
1317 
1318 WarmCallInfo* WarmCallInfo::remove_from(WarmCallInfo* head) {
1319   WarmCallInfo* prev_p = NULL;
1320   WarmCallInfo* next_p = head;
1321   while (next_p != this) {
1322     assert(next_p != NULL, "this must be in the list somewhere");
1323     prev_p = next_p;
1324     next_p = prev_p->next();
1325   }
1326   next_p = this->next();
1327   debug_only(this->set_next(UNINIT_NEXT));
1328   // Remove this from between prev_p and next_p.
1329   if (prev_p == NULL)
1330     head = next_p;
1331   else
1332     prev_p->set_next(next_p);
1333   return head;
1334 }
1335 
1336 WarmCallInfo WarmCallInfo::_always_hot(WarmCallInfo::MAX_VALUE(), WarmCallInfo::MAX_VALUE(),
1337                                        WarmCallInfo::MIN_VALUE(), WarmCallInfo::MIN_VALUE());
1338 WarmCallInfo WarmCallInfo::_always_cold(WarmCallInfo::MIN_VALUE(), WarmCallInfo::MIN_VALUE(),
1339                                         WarmCallInfo::MAX_VALUE(), WarmCallInfo::MAX_VALUE());
1340 
1341 WarmCallInfo* WarmCallInfo::always_hot() {
1342   assert(_always_hot.is_hot(), "must always be hot");
1343   return &_always_hot;
1344 }
1345 
1346 WarmCallInfo* WarmCallInfo::always_cold() {
1347   assert(_always_cold.is_cold(), "must always be cold");
1348   return &_always_cold;
1349 }
1350 
1351 
1352 #ifndef PRODUCT
1353 
1354 void WarmCallInfo::print() const {
1355   tty->print("%s : C=%6.1f P=%6.1f W=%6.1f S=%6.1f H=%6.1f -> %p",
1356              is_cold() ? "cold" : is_hot() ? "hot " : "warm",
1357              count(), profit(), work(), size(), compute_heat(), next());
1358   tty->cr();
1359   if (call() != NULL)  call()->dump();
1360 }
1361 
1362 void print_wci(WarmCallInfo* ci) {
1363   ci->print();
1364 }
1365 
1366 void WarmCallInfo::print_all() const {
1367   for (const WarmCallInfo* p = this; p != NULL; p = p->next())
1368     p->print();
1369 }
1370 
1371 int WarmCallInfo::count_all() const {
1372   int cnt = 0;
1373   for (const WarmCallInfo* p = this; p != NULL; p = p->next())
1374     cnt++;
1375   return cnt;
1376 }
1377 
1378 #endif //PRODUCT