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