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