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