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