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