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